babylon.2.1-alpha.debug.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591
  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.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  639. var v = SIMD.float32x4.loadXYZ(vector, 0);
  640. var m0 = SIMD.float32x4.load(transformation.m, 0);
  641. var m1 = SIMD.float32x4.load(transformation.m, 4);
  642. var m2 = SIMD.float32x4.load(transformation.m, 8);
  643. var m3 = SIMD.float32x4.load(transformation.m, 12);
  644. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  645. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  646. SIMD.float32x4.storeXYZ(result, 0, r);
  647. };
  648. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  649. var v0 = SIMD.float32x4.splat(x);
  650. var v1 = SIMD.float32x4.splat(y);
  651. var v2 = SIMD.float32x4.splat(z);
  652. var m0 = SIMD.float32x4.load(transformation.m, 0);
  653. var m1 = SIMD.float32x4.load(transformation.m, 4);
  654. var m2 = SIMD.float32x4.load(transformation.m, 8);
  655. var m3 = SIMD.float32x4.load(transformation.m, 12);
  656. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  657. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  658. SIMD.float32x4.storeXYZ(result, 0, r);
  659. };
  660. Vector3.TransformNormal = function (vector, transformation) {
  661. var result = Vector3.Zero();
  662. Vector3.TransformNormalToRef(vector, transformation, result);
  663. return result;
  664. };
  665. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  666. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  667. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  668. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  669. };
  670. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  671. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  672. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  673. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  674. };
  675. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  676. var squared = amount * amount;
  677. var cubed = amount * squared;
  678. 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));
  679. 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));
  680. 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));
  681. return new Vector3(x, y, z);
  682. };
  683. Vector3.Clamp = function (value, min, max) {
  684. var x = value.x;
  685. x = (x > max.x) ? max.x : x;
  686. x = (x < min.x) ? min.x : x;
  687. var y = value.y;
  688. y = (y > max.y) ? max.y : y;
  689. y = (y < min.y) ? min.y : y;
  690. var z = value.z;
  691. z = (z > max.z) ? max.z : z;
  692. z = (z < min.z) ? min.z : z;
  693. return new Vector3(x, y, z);
  694. };
  695. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  696. var squared = amount * amount;
  697. var cubed = amount * squared;
  698. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  699. var part2 = (-2.0 * cubed) + (3.0 * squared);
  700. var part3 = (cubed - (2.0 * squared)) + amount;
  701. var part4 = cubed - squared;
  702. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  703. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  704. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  705. return new Vector3(x, y, z);
  706. };
  707. Vector3.Lerp = function (start, end, amount) {
  708. var x = start.x + ((end.x - start.x) * amount);
  709. var y = start.y + ((end.y - start.y) * amount);
  710. var z = start.z + ((end.z - start.z) * amount);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Dot = function (left, right) {
  714. return (left.x * right.x + left.y * right.y + left.z * right.z);
  715. };
  716. Vector3.Cross = function (left, right) {
  717. var result = Vector3.Zero();
  718. Vector3.CrossToRef(left, right, result);
  719. return result;
  720. };
  721. Vector3.CrossToRef = function (left, right, result) {
  722. result.x = left.y * right.z - left.z * right.y;
  723. result.y = left.z * right.x - left.x * right.z;
  724. result.z = left.x * right.y - left.y * right.x;
  725. };
  726. Vector3.Normalize = function (vector) {
  727. var result = Vector3.Zero();
  728. Vector3.NormalizeToRef(vector, result);
  729. return result;
  730. };
  731. Vector3.NormalizeToRef = function (vector, result) {
  732. result.copyFrom(vector);
  733. result.normalize();
  734. };
  735. Vector3.Project = function (vector, world, transform, viewport) {
  736. var cw = viewport.width;
  737. var ch = viewport.height;
  738. var cx = viewport.x;
  739. var cy = viewport.y;
  740. 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);
  741. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  742. return Vector3.TransformCoordinates(vector, finalMatrix);
  743. };
  744. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  745. var matrix = world.multiply(transform);
  746. matrix.invert();
  747. source.x = source.x / viewportWidth * 2 - 1;
  748. source.y = -(source.y / viewportHeight * 2 - 1);
  749. var vector = Vector3.TransformCoordinates(source, matrix);
  750. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  751. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  752. vector = vector.scale(1.0 / num);
  753. }
  754. return vector;
  755. };
  756. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  757. var matrix = world.multiply(view).multiply(projection);
  758. matrix.invert();
  759. source.x = source.x / viewportWidth * 2 - 1;
  760. source.y = -(source.y / viewportHeight * 2 - 1);
  761. var vector = Vector3.TransformCoordinates(source, matrix);
  762. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  763. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  764. vector = vector.scale(1.0 / num);
  765. }
  766. return vector;
  767. };
  768. Vector3.Minimize = function (left, right) {
  769. var min = left.clone();
  770. min.MinimizeInPlace(right);
  771. return min;
  772. };
  773. Vector3.Maximize = function (left, right) {
  774. var max = left.clone();
  775. max.MaximizeInPlace(right);
  776. return max;
  777. };
  778. Vector3.Distance = function (value1, value2) {
  779. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  780. };
  781. Vector3.DistanceSquared = function (value1, value2) {
  782. var x = value1.x - value2.x;
  783. var y = value1.y - value2.y;
  784. var z = value1.z - value2.z;
  785. return (x * x) + (y * y) + (z * z);
  786. };
  787. Vector3.Center = function (value1, value2) {
  788. var center = value1.add(value2);
  789. center.scaleInPlace(0.5);
  790. return center;
  791. };
  792. return Vector3;
  793. })();
  794. BABYLON.Vector3 = Vector3;
  795. //Vector4 class created for EulerAngle class conversion to Quaternion
  796. var Vector4 = (function () {
  797. function Vector4(x, y, z, w) {
  798. this.x = x;
  799. this.y = y;
  800. this.z = z;
  801. this.w = w;
  802. }
  803. Vector4.prototype.toString = function () {
  804. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  805. };
  806. // Operators
  807. Vector4.prototype.asArray = function () {
  808. var result = [];
  809. this.toArray(result, 0);
  810. return result;
  811. };
  812. Vector4.prototype.toArray = function (array, index) {
  813. if (index === undefined) {
  814. index = 0;
  815. }
  816. array[index] = this.x;
  817. array[index + 1] = this.y;
  818. array[index + 2] = this.z;
  819. array[index + 3] = this.w;
  820. return this;
  821. };
  822. Vector4.prototype.addInPlace = function (otherVector) {
  823. this.x += otherVector.x;
  824. this.y += otherVector.y;
  825. this.z += otherVector.z;
  826. this.w += otherVector.w;
  827. return this;
  828. };
  829. Vector4.prototype.add = function (otherVector) {
  830. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  831. };
  832. Vector4.prototype.addToRef = function (otherVector, result) {
  833. result.x = this.x + otherVector.x;
  834. result.y = this.y + otherVector.y;
  835. result.z = this.z + otherVector.z;
  836. result.w = this.w + otherVector.w;
  837. return this;
  838. };
  839. Vector4.prototype.subtractInPlace = function (otherVector) {
  840. this.x -= otherVector.x;
  841. this.y -= otherVector.y;
  842. this.z -= otherVector.z;
  843. this.w -= otherVector.w;
  844. return this;
  845. };
  846. Vector4.prototype.subtract = function (otherVector) {
  847. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  848. };
  849. Vector4.prototype.subtractToRef = function (otherVector, result) {
  850. result.x = this.x - otherVector.x;
  851. result.y = this.y - otherVector.y;
  852. result.z = this.z - otherVector.z;
  853. result.w = this.w - otherVector.w;
  854. return this;
  855. };
  856. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  857. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  858. };
  859. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  860. result.x = this.x - x;
  861. result.y = this.y - y;
  862. result.z = this.z - z;
  863. result.w = this.w - w;
  864. return this;
  865. };
  866. Vector4.prototype.negate = function () {
  867. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  868. };
  869. Vector4.prototype.scaleInPlace = function (scale) {
  870. this.x *= scale;
  871. this.y *= scale;
  872. this.z *= scale;
  873. this.w *= scale;
  874. return this;
  875. };
  876. Vector4.prototype.scale = function (scale) {
  877. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  878. };
  879. Vector4.prototype.scaleToRef = function (scale, result) {
  880. result.x = this.x * scale;
  881. result.y = this.y * scale;
  882. result.z = this.z * scale;
  883. result.w = this.w * scale;
  884. };
  885. Vector4.prototype.equals = function (otherVector) {
  886. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  887. };
  888. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  889. 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;
  890. };
  891. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  892. return this.x === x && this.y === y && this.z === z && this.w === w;
  893. };
  894. Vector4.prototype.multiplyInPlace = function (otherVector) {
  895. this.x *= otherVector.x;
  896. this.y *= otherVector.y;
  897. this.z *= otherVector.z;
  898. this.w *= otherVector.w;
  899. return this;
  900. };
  901. Vector4.prototype.multiply = function (otherVector) {
  902. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  903. };
  904. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  905. result.x = this.x * otherVector.x;
  906. result.y = this.y * otherVector.y;
  907. result.z = this.z * otherVector.z;
  908. result.w = this.w * otherVector.w;
  909. return this;
  910. };
  911. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  912. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  913. };
  914. Vector4.prototype.divide = function (otherVector) {
  915. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  916. };
  917. Vector4.prototype.divideToRef = function (otherVector, result) {
  918. result.x = this.x / otherVector.x;
  919. result.y = this.y / otherVector.y;
  920. result.z = this.z / otherVector.z;
  921. result.w = this.w / otherVector.w;
  922. return this;
  923. };
  924. Vector4.prototype.MinimizeInPlace = function (other) {
  925. if (other.x < this.x)
  926. this.x = other.x;
  927. if (other.y < this.y)
  928. this.y = other.y;
  929. if (other.z < this.z)
  930. this.z = other.z;
  931. if (other.w < this.w)
  932. this.w = other.w;
  933. return this;
  934. };
  935. Vector4.prototype.MaximizeInPlace = function (other) {
  936. if (other.x > this.x)
  937. this.x = other.x;
  938. if (other.y > this.y)
  939. this.y = other.y;
  940. if (other.z > this.z)
  941. this.z = other.z;
  942. if (other.w > this.w)
  943. this.w = other.w;
  944. return this;
  945. };
  946. // Properties
  947. Vector4.prototype.length = function () {
  948. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  949. };
  950. Vector4.prototype.lengthSquared = function () {
  951. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  952. };
  953. // Methods
  954. Vector4.prototype.normalize = function () {
  955. var len = this.length();
  956. if (len === 0)
  957. return this;
  958. var num = 1.0 / len;
  959. this.x *= num;
  960. this.y *= num;
  961. this.z *= num;
  962. this.w *= num;
  963. return this;
  964. };
  965. Vector4.prototype.clone = function () {
  966. return new Vector4(this.x, this.y, this.z, this.w);
  967. };
  968. Vector4.prototype.copyFrom = function (source) {
  969. this.x = source.x;
  970. this.y = source.y;
  971. this.z = source.z;
  972. this.w = source.w;
  973. return this;
  974. };
  975. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. return this;
  981. };
  982. // Statics
  983. Vector4.FromArray = function (array, offset) {
  984. if (!offset) {
  985. offset = 0;
  986. }
  987. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  988. };
  989. Vector4.FromArrayToRef = function (array, offset, result) {
  990. result.x = array[offset];
  991. result.y = array[offset + 1];
  992. result.z = array[offset + 2];
  993. result.w = array[offset + 3];
  994. };
  995. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1002. result.x = x;
  1003. result.y = y;
  1004. result.z = z;
  1005. result.w = w;
  1006. };
  1007. Vector4.Zero = function () {
  1008. return new Vector4(0, 0, 0, 0);
  1009. };
  1010. Vector4.Normalize = function (vector) {
  1011. var result = Vector4.Zero();
  1012. Vector4.NormalizeToRef(vector, result);
  1013. return result;
  1014. };
  1015. Vector4.NormalizeToRef = function (vector, result) {
  1016. result.copyFrom(vector);
  1017. result.normalize();
  1018. };
  1019. Vector4.Minimize = function (left, right) {
  1020. var min = left.clone();
  1021. min.MinimizeInPlace(right);
  1022. return min;
  1023. };
  1024. Vector4.Maximize = function (left, right) {
  1025. var max = left.clone();
  1026. max.MaximizeInPlace(right);
  1027. return max;
  1028. };
  1029. Vector4.Distance = function (value1, value2) {
  1030. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1031. };
  1032. Vector4.DistanceSquared = function (value1, value2) {
  1033. var x = value1.x - value2.x;
  1034. var y = value1.y - value2.y;
  1035. var z = value1.z - value2.z;
  1036. var w = value1.w - value2.w;
  1037. return (x * x) + (y * y) + (z * z) + (w * w);
  1038. };
  1039. Vector4.Center = function (value1, value2) {
  1040. var center = value1.add(value2);
  1041. center.scaleInPlace(0.5);
  1042. return center;
  1043. };
  1044. return Vector4;
  1045. })();
  1046. BABYLON.Vector4 = Vector4;
  1047. var Quaternion = (function () {
  1048. function Quaternion(x, y, z, w) {
  1049. if (x === void 0) { x = 0; }
  1050. if (y === void 0) { y = 0; }
  1051. if (z === void 0) { z = 0; }
  1052. if (w === void 0) { w = 1; }
  1053. this.x = x;
  1054. this.y = y;
  1055. this.z = z;
  1056. this.w = w;
  1057. }
  1058. Quaternion.prototype.toString = function () {
  1059. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1060. };
  1061. Quaternion.prototype.asArray = function () {
  1062. return [this.x, this.y, this.z, this.w];
  1063. };
  1064. Quaternion.prototype.equals = function (otherQuaternion) {
  1065. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1066. };
  1067. Quaternion.prototype.clone = function () {
  1068. return new Quaternion(this.x, this.y, this.z, this.w);
  1069. };
  1070. Quaternion.prototype.copyFrom = function (other) {
  1071. this.x = other.x;
  1072. this.y = other.y;
  1073. this.z = other.z;
  1074. this.w = other.w;
  1075. return this;
  1076. };
  1077. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1078. this.x = x;
  1079. this.y = y;
  1080. this.z = z;
  1081. this.w = w;
  1082. return this;
  1083. };
  1084. Quaternion.prototype.add = function (other) {
  1085. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1086. };
  1087. Quaternion.prototype.subtract = function (other) {
  1088. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1089. };
  1090. Quaternion.prototype.scale = function (value) {
  1091. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1092. };
  1093. Quaternion.prototype.multiply = function (q1) {
  1094. var result = new Quaternion(0, 0, 0, 1.0);
  1095. this.multiplyToRef(q1, result);
  1096. return result;
  1097. };
  1098. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1099. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1100. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1101. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1102. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1103. return this;
  1104. };
  1105. Quaternion.prototype.length = function () {
  1106. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1107. };
  1108. Quaternion.prototype.normalize = function () {
  1109. var length = 1.0 / this.length();
  1110. this.x *= length;
  1111. this.y *= length;
  1112. this.z *= length;
  1113. this.w *= length;
  1114. return this;
  1115. };
  1116. Quaternion.prototype.toEulerAngles = function () {
  1117. var result = Vector3.Zero();
  1118. this.toEulerAnglesToRef(result);
  1119. return result;
  1120. };
  1121. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1122. //result is an EulerAngles in the in the z-x-z convention
  1123. var qx = this.x;
  1124. var qy = this.y;
  1125. var qz = this.z;
  1126. var qw = this.w;
  1127. var qxy = qx * qy;
  1128. var qxz = qx * qz;
  1129. var qwy = qw * qy;
  1130. var qwz = qw * qz;
  1131. var qwx = qw * qx;
  1132. var qyz = qy * qz;
  1133. var sqx = qx * qx;
  1134. var sqy = qy * qy;
  1135. var determinant = sqx + sqy;
  1136. if (determinant !== 0.000 && determinant !== 1.000) {
  1137. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1138. result.y = Math.acos(1 - 2 * determinant);
  1139. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1140. }
  1141. else {
  1142. if (determinant === 0.0) {
  1143. result.x = 0.0;
  1144. result.y = 0.0;
  1145. 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)
  1146. }
  1147. else {
  1148. 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)
  1149. result.y = Math.PI;
  1150. result.z = 0.0;
  1151. }
  1152. }
  1153. return this;
  1154. };
  1155. Quaternion.prototype.toRotationMatrix = function (result) {
  1156. var xx = this.x * this.x;
  1157. var yy = this.y * this.y;
  1158. var zz = this.z * this.z;
  1159. var xy = this.x * this.y;
  1160. var zw = this.z * this.w;
  1161. var zx = this.z * this.x;
  1162. var yw = this.y * this.w;
  1163. var yz = this.y * this.z;
  1164. var xw = this.x * this.w;
  1165. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1166. result.m[1] = 2.0 * (xy + zw);
  1167. result.m[2] = 2.0 * (zx - yw);
  1168. result.m[3] = 0;
  1169. result.m[4] = 2.0 * (xy - zw);
  1170. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1171. result.m[6] = 2.0 * (yz + xw);
  1172. result.m[7] = 0;
  1173. result.m[8] = 2.0 * (zx + yw);
  1174. result.m[9] = 2.0 * (yz - xw);
  1175. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1176. result.m[11] = 0;
  1177. result.m[12] = 0;
  1178. result.m[13] = 0;
  1179. result.m[14] = 0;
  1180. result.m[15] = 1.0;
  1181. return this;
  1182. };
  1183. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1184. Quaternion.FromRotationMatrixToRef(matrix, this);
  1185. return this;
  1186. };
  1187. // Statics
  1188. Quaternion.FromRotationMatrix = function (matrix) {
  1189. var result = new Quaternion();
  1190. Quaternion.FromRotationMatrixToRef(matrix, result);
  1191. return result;
  1192. };
  1193. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1194. var data = matrix.m;
  1195. var m11 = data[0], m12 = data[4], m13 = data[8];
  1196. var m21 = data[1], m22 = data[5], m23 = data[9];
  1197. var m31 = data[2], m32 = data[6], m33 = data[10];
  1198. var trace = m11 + m22 + m33;
  1199. var s;
  1200. if (trace > 0) {
  1201. s = 0.5 / Math.sqrt(trace + 1.0);
  1202. result.w = 0.25 / s;
  1203. result.x = (m32 - m23) * s;
  1204. result.y = (m13 - m31) * s;
  1205. result.z = (m21 - m12) * s;
  1206. }
  1207. else if (m11 > m22 && m11 > m33) {
  1208. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1209. result.w = (m32 - m23) / s;
  1210. result.x = 0.25 * s;
  1211. result.y = (m12 + m21) / s;
  1212. result.z = (m13 + m31) / s;
  1213. }
  1214. else if (m22 > m33) {
  1215. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1216. result.w = (m13 - m31) / s;
  1217. result.x = (m12 + m21) / s;
  1218. result.y = 0.25 * s;
  1219. result.z = (m23 + m32) / s;
  1220. }
  1221. else {
  1222. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1223. result.w = (m21 - m12) / s;
  1224. result.x = (m13 + m31) / s;
  1225. result.y = (m23 + m32) / s;
  1226. result.z = 0.25 * s;
  1227. }
  1228. };
  1229. Quaternion.Inverse = function (q) {
  1230. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1231. };
  1232. Quaternion.Identity = function () {
  1233. return new Quaternion(0, 0, 0, 1);
  1234. };
  1235. Quaternion.RotationAxis = function (axis, angle) {
  1236. var result = new Quaternion();
  1237. var sin = Math.sin(angle / 2);
  1238. result.w = Math.cos(angle / 2);
  1239. result.x = axis.x * sin;
  1240. result.y = axis.y * sin;
  1241. result.z = axis.z * sin;
  1242. return result;
  1243. };
  1244. Quaternion.FromArray = function (array, offset) {
  1245. if (!offset) {
  1246. offset = 0;
  1247. }
  1248. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1249. };
  1250. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1251. var result = new Quaternion();
  1252. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1253. return result;
  1254. };
  1255. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1256. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1257. var halfRoll = roll * 0.5;
  1258. var halfPitch = pitch * 0.5;
  1259. var halfYaw = yaw * 0.5;
  1260. var sinRoll = Math.sin(halfRoll);
  1261. var cosRoll = Math.cos(halfRoll);
  1262. var sinPitch = Math.sin(halfPitch);
  1263. var cosPitch = Math.cos(halfPitch);
  1264. var sinYaw = Math.sin(halfYaw);
  1265. var cosYaw = Math.cos(halfYaw);
  1266. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1267. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1268. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1269. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1270. };
  1271. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1272. var result = new Quaternion();
  1273. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1274. return result;
  1275. };
  1276. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1277. // Produces a quaternion from Euler angles in the z-x-z orientation
  1278. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1279. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1280. var halfBeta = beta * 0.5;
  1281. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1282. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1283. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1284. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1285. };
  1286. Quaternion.Slerp = function (left, right, amount) {
  1287. var num2;
  1288. var num3;
  1289. var num = amount;
  1290. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1291. var flag = false;
  1292. if (num4 < 0) {
  1293. flag = true;
  1294. num4 = -num4;
  1295. }
  1296. if (num4 > 0.999999) {
  1297. num3 = 1 - num;
  1298. num2 = flag ? -num : num;
  1299. }
  1300. else {
  1301. var num5 = Math.acos(num4);
  1302. var num6 = (1.0 / Math.sin(num5));
  1303. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1304. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1305. }
  1306. 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));
  1307. };
  1308. return Quaternion;
  1309. })();
  1310. BABYLON.Quaternion = Quaternion;
  1311. var Matrix = (function () {
  1312. function Matrix() {
  1313. this.m = new Float32Array(16);
  1314. }
  1315. // Properties
  1316. Matrix.prototype.isIdentity = function () {
  1317. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1318. return false;
  1319. 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)
  1320. return false;
  1321. return true;
  1322. };
  1323. Matrix.prototype.determinant = function () {
  1324. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1325. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1326. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1327. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1328. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1329. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1330. 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))));
  1331. };
  1332. // Methods
  1333. Matrix.prototype.toArray = function () {
  1334. return this.m;
  1335. };
  1336. Matrix.prototype.asArray = function () {
  1337. return this.toArray();
  1338. };
  1339. Matrix.prototype.invert = function () {
  1340. this.invertToRef(this);
  1341. return this;
  1342. };
  1343. Matrix.prototype.invertToRef = function (other) {
  1344. var l1 = this.m[0];
  1345. var l2 = this.m[1];
  1346. var l3 = this.m[2];
  1347. var l4 = this.m[3];
  1348. var l5 = this.m[4];
  1349. var l6 = this.m[5];
  1350. var l7 = this.m[6];
  1351. var l8 = this.m[7];
  1352. var l9 = this.m[8];
  1353. var l10 = this.m[9];
  1354. var l11 = this.m[10];
  1355. var l12 = this.m[11];
  1356. var l13 = this.m[12];
  1357. var l14 = this.m[13];
  1358. var l15 = this.m[14];
  1359. var l16 = this.m[15];
  1360. var l17 = (l11 * l16) - (l12 * l15);
  1361. var l18 = (l10 * l16) - (l12 * l14);
  1362. var l19 = (l10 * l15) - (l11 * l14);
  1363. var l20 = (l9 * l16) - (l12 * l13);
  1364. var l21 = (l9 * l15) - (l11 * l13);
  1365. var l22 = (l9 * l14) - (l10 * l13);
  1366. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1367. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1368. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1369. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1370. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1371. var l28 = (l7 * l16) - (l8 * l15);
  1372. var l29 = (l6 * l16) - (l8 * l14);
  1373. var l30 = (l6 * l15) - (l7 * l14);
  1374. var l31 = (l5 * l16) - (l8 * l13);
  1375. var l32 = (l5 * l15) - (l7 * l13);
  1376. var l33 = (l5 * l14) - (l6 * l13);
  1377. var l34 = (l7 * l12) - (l8 * l11);
  1378. var l35 = (l6 * l12) - (l8 * l10);
  1379. var l36 = (l6 * l11) - (l7 * l10);
  1380. var l37 = (l5 * l12) - (l8 * l9);
  1381. var l38 = (l5 * l11) - (l7 * l9);
  1382. var l39 = (l5 * l10) - (l6 * l9);
  1383. other.m[0] = l23 * l27;
  1384. other.m[4] = l24 * l27;
  1385. other.m[8] = l25 * l27;
  1386. other.m[12] = l26 * l27;
  1387. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1388. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1389. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1390. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1391. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1392. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1393. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1394. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1395. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1396. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1397. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1398. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1399. return this;
  1400. };
  1401. Matrix.prototype.setTranslation = function (vector3) {
  1402. this.m[12] = vector3.x;
  1403. this.m[13] = vector3.y;
  1404. this.m[14] = vector3.z;
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiply = function (other) {
  1408. var result = new Matrix();
  1409. this.multiplyToRef(other, result);
  1410. return result;
  1411. };
  1412. Matrix.prototype.copyFrom = function (other) {
  1413. for (var index = 0; index < 16; index++) {
  1414. this.m[index] = other.m[index];
  1415. }
  1416. return this;
  1417. };
  1418. Matrix.prototype.copyToArray = function (array, offset) {
  1419. if (offset === void 0) { offset = 0; }
  1420. for (var index = 0; index < 16; index++) {
  1421. array[offset + index] = this.m[index];
  1422. }
  1423. return this;
  1424. };
  1425. Matrix.prototype.multiplyToRef = function (other, result) {
  1426. this.multiplyToArray(other, result.m, 0);
  1427. return this;
  1428. };
  1429. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1430. var tm0 = this.m[0];
  1431. var tm1 = this.m[1];
  1432. var tm2 = this.m[2];
  1433. var tm3 = this.m[3];
  1434. var tm4 = this.m[4];
  1435. var tm5 = this.m[5];
  1436. var tm6 = this.m[6];
  1437. var tm7 = this.m[7];
  1438. var tm8 = this.m[8];
  1439. var tm9 = this.m[9];
  1440. var tm10 = this.m[10];
  1441. var tm11 = this.m[11];
  1442. var tm12 = this.m[12];
  1443. var tm13 = this.m[13];
  1444. var tm14 = this.m[14];
  1445. var tm15 = this.m[15];
  1446. var om0 = other.m[0];
  1447. var om1 = other.m[1];
  1448. var om2 = other.m[2];
  1449. var om3 = other.m[3];
  1450. var om4 = other.m[4];
  1451. var om5 = other.m[5];
  1452. var om6 = other.m[6];
  1453. var om7 = other.m[7];
  1454. var om8 = other.m[8];
  1455. var om9 = other.m[9];
  1456. var om10 = other.m[10];
  1457. var om11 = other.m[11];
  1458. var om12 = other.m[12];
  1459. var om13 = other.m[13];
  1460. var om14 = other.m[14];
  1461. var om15 = other.m[15];
  1462. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1463. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1464. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1465. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1466. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1467. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1468. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1469. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1470. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1471. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1472. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1473. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1474. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1475. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1476. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1477. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1478. return this;
  1479. };
  1480. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1481. if (offset === void 0) { offset = 0; }
  1482. var tm = this.m;
  1483. var om = other.m;
  1484. var om0 = SIMD.float32x4.load(om, 0);
  1485. var om1 = SIMD.float32x4.load(om, 4);
  1486. var om2 = SIMD.float32x4.load(om, 8);
  1487. var om3 = SIMD.float32x4.load(om, 12);
  1488. var tm0 = SIMD.float32x4.load(tm, 0);
  1489. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1490. var tm1 = SIMD.float32x4.load(tm, 4);
  1491. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1492. var tm2 = SIMD.float32x4.load(tm, 8);
  1493. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1494. var tm3 = SIMD.float32x4.load(tm, 12);
  1495. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1496. };
  1497. Matrix.prototype.equals = function (value) {
  1498. 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]);
  1499. };
  1500. Matrix.prototype.clone = function () {
  1501. 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]);
  1502. };
  1503. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1504. translation.x = this.m[12];
  1505. translation.y = this.m[13];
  1506. translation.z = this.m[14];
  1507. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1508. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1509. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1510. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1511. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1512. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1513. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1514. rotation.x = 0;
  1515. rotation.y = 0;
  1516. rotation.z = 0;
  1517. rotation.w = 1;
  1518. return false;
  1519. }
  1520. 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);
  1521. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1522. return true;
  1523. };
  1524. // Statics
  1525. Matrix.FromArray = function (array, offset) {
  1526. var result = new Matrix();
  1527. if (!offset) {
  1528. offset = 0;
  1529. }
  1530. Matrix.FromArrayToRef(array, offset, result);
  1531. return result;
  1532. };
  1533. Matrix.FromArrayToRef = function (array, offset, result) {
  1534. for (var index = 0; index < 16; index++) {
  1535. result.m[index] = array[index + offset];
  1536. }
  1537. };
  1538. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1539. result.m[0] = initialM11;
  1540. result.m[1] = initialM12;
  1541. result.m[2] = initialM13;
  1542. result.m[3] = initialM14;
  1543. result.m[4] = initialM21;
  1544. result.m[5] = initialM22;
  1545. result.m[6] = initialM23;
  1546. result.m[7] = initialM24;
  1547. result.m[8] = initialM31;
  1548. result.m[9] = initialM32;
  1549. result.m[10] = initialM33;
  1550. result.m[11] = initialM34;
  1551. result.m[12] = initialM41;
  1552. result.m[13] = initialM42;
  1553. result.m[14] = initialM43;
  1554. result.m[15] = initialM44;
  1555. };
  1556. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1557. var result = new Matrix();
  1558. result.m[0] = initialM11;
  1559. result.m[1] = initialM12;
  1560. result.m[2] = initialM13;
  1561. result.m[3] = initialM14;
  1562. result.m[4] = initialM21;
  1563. result.m[5] = initialM22;
  1564. result.m[6] = initialM23;
  1565. result.m[7] = initialM24;
  1566. result.m[8] = initialM31;
  1567. result.m[9] = initialM32;
  1568. result.m[10] = initialM33;
  1569. result.m[11] = initialM34;
  1570. result.m[12] = initialM41;
  1571. result.m[13] = initialM42;
  1572. result.m[14] = initialM43;
  1573. result.m[15] = initialM44;
  1574. return result;
  1575. };
  1576. Matrix.Compose = function (scale, rotation, translation) {
  1577. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1578. var rotationMatrix = Matrix.Identity();
  1579. rotation.toRotationMatrix(rotationMatrix);
  1580. result = result.multiply(rotationMatrix);
  1581. result.setTranslation(translation);
  1582. return result;
  1583. };
  1584. Matrix.Identity = function () {
  1585. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1586. };
  1587. Matrix.IdentityToRef = function (result) {
  1588. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1589. };
  1590. Matrix.Zero = function () {
  1591. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1592. };
  1593. Matrix.RotationX = function (angle) {
  1594. var result = new Matrix();
  1595. Matrix.RotationXToRef(angle, result);
  1596. return result;
  1597. };
  1598. Matrix.Invert = function (source) {
  1599. var result = new Matrix();
  1600. source.invertToRef(result);
  1601. return result;
  1602. };
  1603. Matrix.RotationXToRef = function (angle, result) {
  1604. var s = Math.sin(angle);
  1605. var c = Math.cos(angle);
  1606. result.m[0] = 1.0;
  1607. result.m[15] = 1.0;
  1608. result.m[5] = c;
  1609. result.m[10] = c;
  1610. result.m[9] = -s;
  1611. result.m[6] = s;
  1612. result.m[1] = 0;
  1613. result.m[2] = 0;
  1614. result.m[3] = 0;
  1615. result.m[4] = 0;
  1616. result.m[7] = 0;
  1617. result.m[8] = 0;
  1618. result.m[11] = 0;
  1619. result.m[12] = 0;
  1620. result.m[13] = 0;
  1621. result.m[14] = 0;
  1622. };
  1623. Matrix.RotationY = function (angle) {
  1624. var result = new Matrix();
  1625. Matrix.RotationYToRef(angle, result);
  1626. return result;
  1627. };
  1628. Matrix.RotationYToRef = function (angle, result) {
  1629. var s = Math.sin(angle);
  1630. var c = Math.cos(angle);
  1631. result.m[5] = 1.0;
  1632. result.m[15] = 1.0;
  1633. result.m[0] = c;
  1634. result.m[2] = -s;
  1635. result.m[8] = s;
  1636. result.m[10] = c;
  1637. result.m[1] = 0;
  1638. result.m[3] = 0;
  1639. result.m[4] = 0;
  1640. result.m[6] = 0;
  1641. result.m[7] = 0;
  1642. result.m[9] = 0;
  1643. result.m[11] = 0;
  1644. result.m[12] = 0;
  1645. result.m[13] = 0;
  1646. result.m[14] = 0;
  1647. };
  1648. Matrix.RotationZ = function (angle) {
  1649. var result = new Matrix();
  1650. Matrix.RotationZToRef(angle, result);
  1651. return result;
  1652. };
  1653. Matrix.RotationZToRef = function (angle, result) {
  1654. var s = Math.sin(angle);
  1655. var c = Math.cos(angle);
  1656. result.m[10] = 1.0;
  1657. result.m[15] = 1.0;
  1658. result.m[0] = c;
  1659. result.m[1] = s;
  1660. result.m[4] = -s;
  1661. result.m[5] = c;
  1662. result.m[2] = 0;
  1663. result.m[3] = 0;
  1664. result.m[6] = 0;
  1665. result.m[7] = 0;
  1666. result.m[8] = 0;
  1667. result.m[9] = 0;
  1668. result.m[11] = 0;
  1669. result.m[12] = 0;
  1670. result.m[13] = 0;
  1671. result.m[14] = 0;
  1672. };
  1673. Matrix.RotationAxis = function (axis, angle) {
  1674. var s = Math.sin(-angle);
  1675. var c = Math.cos(-angle);
  1676. var c1 = 1 - c;
  1677. axis.normalize();
  1678. var result = Matrix.Zero();
  1679. result.m[0] = (axis.x * axis.x) * c1 + c;
  1680. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1681. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1682. result.m[3] = 0.0;
  1683. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1684. result.m[5] = (axis.y * axis.y) * c1 + c;
  1685. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1686. result.m[7] = 0.0;
  1687. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1688. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1689. result.m[10] = (axis.z * axis.z) * c1 + c;
  1690. result.m[11] = 0.0;
  1691. result.m[15] = 1.0;
  1692. return result;
  1693. };
  1694. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1695. var result = new Matrix();
  1696. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1697. return result;
  1698. };
  1699. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1700. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1701. this._tempQuaternion.toRotationMatrix(result);
  1702. };
  1703. Matrix.Scaling = function (x, y, z) {
  1704. var result = Matrix.Zero();
  1705. Matrix.ScalingToRef(x, y, z, result);
  1706. return result;
  1707. };
  1708. Matrix.ScalingToRef = function (x, y, z, result) {
  1709. result.m[0] = x;
  1710. result.m[1] = 0;
  1711. result.m[2] = 0;
  1712. result.m[3] = 0;
  1713. result.m[4] = 0;
  1714. result.m[5] = y;
  1715. result.m[6] = 0;
  1716. result.m[7] = 0;
  1717. result.m[8] = 0;
  1718. result.m[9] = 0;
  1719. result.m[10] = z;
  1720. result.m[11] = 0;
  1721. result.m[12] = 0;
  1722. result.m[13] = 0;
  1723. result.m[14] = 0;
  1724. result.m[15] = 1.0;
  1725. };
  1726. Matrix.Translation = function (x, y, z) {
  1727. var result = Matrix.Identity();
  1728. Matrix.TranslationToRef(x, y, z, result);
  1729. return result;
  1730. };
  1731. Matrix.TranslationToRef = function (x, y, z, result) {
  1732. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1733. };
  1734. Matrix.LookAtLH = function (eye, target, up) {
  1735. var result = Matrix.Zero();
  1736. Matrix.LookAtLHToRef(eye, target, up, result);
  1737. return result;
  1738. };
  1739. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1740. // Z axis
  1741. target.subtractToRef(eye, this._zAxis);
  1742. this._zAxis.normalize();
  1743. // X axis
  1744. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1745. this._xAxis.normalize();
  1746. // Y axis
  1747. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1748. this._yAxis.normalize();
  1749. // Eye angles
  1750. var ex = -Vector3.Dot(this._xAxis, eye);
  1751. var ey = -Vector3.Dot(this._yAxis, eye);
  1752. var ez = -Vector3.Dot(this._zAxis, eye);
  1753. 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);
  1754. };
  1755. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1756. var matrix = Matrix.Zero();
  1757. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1758. return matrix;
  1759. };
  1760. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1761. var hw = 2.0 / width;
  1762. var hh = 2.0 / height;
  1763. var id = 1.0 / (zfar - znear);
  1764. var nid = znear / (znear - zfar);
  1765. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1766. };
  1767. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1768. var matrix = Matrix.Zero();
  1769. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1770. return matrix;
  1771. };
  1772. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1773. result.m[0] = 2.0 / (right - left);
  1774. result.m[1] = result.m[2] = result.m[3] = 0;
  1775. result.m[5] = 2.0 / (top - bottom);
  1776. result.m[4] = result.m[6] = result.m[7] = 0;
  1777. result.m[10] = -1.0 / (znear - zfar);
  1778. result.m[8] = result.m[9] = result.m[11] = 0;
  1779. result.m[12] = (left + right) / (left - right);
  1780. result.m[13] = (top + bottom) / (bottom - top);
  1781. result.m[14] = znear / (znear - zfar);
  1782. result.m[15] = 1.0;
  1783. };
  1784. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1785. var matrix = Matrix.Zero();
  1786. matrix.m[0] = (2.0 * znear) / width;
  1787. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1788. matrix.m[5] = (2.0 * znear) / height;
  1789. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1790. matrix.m[10] = -zfar / (znear - zfar);
  1791. matrix.m[8] = matrix.m[9] = 0.0;
  1792. matrix.m[11] = 1.0;
  1793. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1794. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1795. return matrix;
  1796. };
  1797. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1798. var matrix = Matrix.Zero();
  1799. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1800. return matrix;
  1801. };
  1802. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1803. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1804. var tan = 1.0 / (Math.tan(fov * 0.5));
  1805. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1806. if (v_fixed) {
  1807. result.m[0] = tan / aspect;
  1808. }
  1809. else {
  1810. result.m[0] = tan;
  1811. }
  1812. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1813. if (v_fixed) {
  1814. result.m[5] = tan;
  1815. }
  1816. else {
  1817. result.m[5] = tan * aspect;
  1818. }
  1819. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1820. result.m[8] = result.m[9] = 0.0;
  1821. result.m[10] = -zfar / (znear - zfar);
  1822. result.m[11] = 1.0;
  1823. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1824. result.m[14] = (znear * zfar) / (znear - zfar);
  1825. };
  1826. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1827. var cw = viewport.width;
  1828. var ch = viewport.height;
  1829. var cx = viewport.x;
  1830. var cy = viewport.y;
  1831. 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);
  1832. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1833. };
  1834. Matrix.Transpose = function (matrix) {
  1835. var result = new Matrix();
  1836. result.m[0] = matrix.m[0];
  1837. result.m[1] = matrix.m[4];
  1838. result.m[2] = matrix.m[8];
  1839. result.m[3] = matrix.m[12];
  1840. result.m[4] = matrix.m[1];
  1841. result.m[5] = matrix.m[5];
  1842. result.m[6] = matrix.m[9];
  1843. result.m[7] = matrix.m[13];
  1844. result.m[8] = matrix.m[2];
  1845. result.m[9] = matrix.m[6];
  1846. result.m[10] = matrix.m[10];
  1847. result.m[11] = matrix.m[14];
  1848. result.m[12] = matrix.m[3];
  1849. result.m[13] = matrix.m[7];
  1850. result.m[14] = matrix.m[11];
  1851. result.m[15] = matrix.m[15];
  1852. return result;
  1853. };
  1854. Matrix.Reflection = function (plane) {
  1855. var matrix = new Matrix();
  1856. Matrix.ReflectionToRef(plane, matrix);
  1857. return matrix;
  1858. };
  1859. Matrix.ReflectionToRef = function (plane, result) {
  1860. plane.normalize();
  1861. var x = plane.normal.x;
  1862. var y = plane.normal.y;
  1863. var z = plane.normal.z;
  1864. var temp = -2 * x;
  1865. var temp2 = -2 * y;
  1866. var temp3 = -2 * z;
  1867. result.m[0] = (temp * x) + 1;
  1868. result.m[1] = temp2 * x;
  1869. result.m[2] = temp3 * x;
  1870. result.m[3] = 0.0;
  1871. result.m[4] = temp * y;
  1872. result.m[5] = (temp2 * y) + 1;
  1873. result.m[6] = temp3 * y;
  1874. result.m[7] = 0.0;
  1875. result.m[8] = temp * z;
  1876. result.m[9] = temp2 * z;
  1877. result.m[10] = (temp3 * z) + 1;
  1878. result.m[11] = 0.0;
  1879. result.m[12] = temp * plane.d;
  1880. result.m[13] = temp2 * plane.d;
  1881. result.m[14] = temp3 * plane.d;
  1882. result.m[15] = 1.0;
  1883. };
  1884. Matrix._tempQuaternion = new Quaternion();
  1885. Matrix._xAxis = Vector3.Zero();
  1886. Matrix._yAxis = Vector3.Zero();
  1887. Matrix._zAxis = Vector3.Zero();
  1888. return Matrix;
  1889. })();
  1890. BABYLON.Matrix = Matrix;
  1891. var Plane = (function () {
  1892. function Plane(a, b, c, d) {
  1893. this.normal = new Vector3(a, b, c);
  1894. this.d = d;
  1895. }
  1896. Plane.prototype.asArray = function () {
  1897. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1898. };
  1899. // Methods
  1900. Plane.prototype.clone = function () {
  1901. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1902. };
  1903. Plane.prototype.normalize = function () {
  1904. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1905. var magnitude = 0;
  1906. if (norm !== 0) {
  1907. magnitude = 1.0 / norm;
  1908. }
  1909. this.normal.x *= magnitude;
  1910. this.normal.y *= magnitude;
  1911. this.normal.z *= magnitude;
  1912. this.d *= magnitude;
  1913. return this;
  1914. };
  1915. Plane.prototype.transform = function (transformation) {
  1916. var transposedMatrix = Matrix.Transpose(transformation);
  1917. var x = this.normal.x;
  1918. var y = this.normal.y;
  1919. var z = this.normal.z;
  1920. var d = this.d;
  1921. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1922. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1923. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1924. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1925. return new Plane(normalX, normalY, normalZ, finalD);
  1926. };
  1927. Plane.prototype.dotCoordinate = function (point) {
  1928. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1929. };
  1930. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1931. var x1 = point2.x - point1.x;
  1932. var y1 = point2.y - point1.y;
  1933. var z1 = point2.z - point1.z;
  1934. var x2 = point3.x - point1.x;
  1935. var y2 = point3.y - point1.y;
  1936. var z2 = point3.z - point1.z;
  1937. var yz = (y1 * z2) - (z1 * y2);
  1938. var xz = (z1 * x2) - (x1 * z2);
  1939. var xy = (x1 * y2) - (y1 * x2);
  1940. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1941. var invPyth;
  1942. if (pyth !== 0) {
  1943. invPyth = 1.0 / pyth;
  1944. }
  1945. else {
  1946. invPyth = 0;
  1947. }
  1948. this.normal.x = yz * invPyth;
  1949. this.normal.y = xz * invPyth;
  1950. this.normal.z = xy * invPyth;
  1951. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1952. return this;
  1953. };
  1954. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1955. var dot = Vector3.Dot(this.normal, direction);
  1956. return (dot <= epsilon);
  1957. };
  1958. Plane.prototype.signedDistanceTo = function (point) {
  1959. return Vector3.Dot(point, this.normal) + this.d;
  1960. };
  1961. // Statics
  1962. Plane.FromArray = function (array) {
  1963. return new Plane(array[0], array[1], array[2], array[3]);
  1964. };
  1965. Plane.FromPoints = function (point1, point2, point3) {
  1966. var result = new Plane(0, 0, 0, 0);
  1967. result.copyFromPoints(point1, point2, point3);
  1968. return result;
  1969. };
  1970. Plane.FromPositionAndNormal = function (origin, normal) {
  1971. var result = new Plane(0, 0, 0, 0);
  1972. normal.normalize();
  1973. result.normal = normal;
  1974. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1975. return result;
  1976. };
  1977. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1978. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1979. return Vector3.Dot(point, normal) + d;
  1980. };
  1981. return Plane;
  1982. })();
  1983. BABYLON.Plane = Plane;
  1984. var Viewport = (function () {
  1985. function Viewport(x, y, width, height) {
  1986. this.x = x;
  1987. this.y = y;
  1988. this.width = width;
  1989. this.height = height;
  1990. }
  1991. Viewport.prototype.toGlobal = function (engine) {
  1992. var width = engine.getRenderWidth();
  1993. var height = engine.getRenderHeight();
  1994. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1995. };
  1996. return Viewport;
  1997. })();
  1998. BABYLON.Viewport = Viewport;
  1999. var Frustum = (function () {
  2000. function Frustum() {
  2001. }
  2002. Frustum.GetPlanes = function (transform) {
  2003. var frustumPlanes = [];
  2004. for (var index = 0; index < 6; index++) {
  2005. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2006. }
  2007. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2008. return frustumPlanes;
  2009. };
  2010. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2011. // Near
  2012. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2013. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2014. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2015. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2016. frustumPlanes[0].normalize();
  2017. // Far
  2018. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2019. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2020. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2021. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2022. frustumPlanes[1].normalize();
  2023. // Left
  2024. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2025. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2026. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2027. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2028. frustumPlanes[2].normalize();
  2029. // Right
  2030. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2031. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2032. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2033. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2034. frustumPlanes[3].normalize();
  2035. // Top
  2036. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2037. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2038. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2039. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2040. frustumPlanes[4].normalize();
  2041. // Bottom
  2042. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2043. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2044. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2045. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2046. frustumPlanes[5].normalize();
  2047. };
  2048. return Frustum;
  2049. })();
  2050. BABYLON.Frustum = Frustum;
  2051. var Ray = (function () {
  2052. function Ray(origin, direction, length) {
  2053. if (length === void 0) { length = Number.MAX_VALUE; }
  2054. this.origin = origin;
  2055. this.direction = direction;
  2056. this.length = length;
  2057. }
  2058. // Methods
  2059. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2060. var d = 0.0;
  2061. var maxValue = Number.MAX_VALUE;
  2062. if (Math.abs(this.direction.x) < 0.0000001) {
  2063. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2064. return false;
  2065. }
  2066. }
  2067. else {
  2068. var inv = 1.0 / this.direction.x;
  2069. var min = (minimum.x - this.origin.x) * inv;
  2070. var max = (maximum.x - this.origin.x) * inv;
  2071. if (max === -Infinity) {
  2072. max = Infinity;
  2073. }
  2074. if (min > max) {
  2075. var temp = min;
  2076. min = max;
  2077. max = temp;
  2078. }
  2079. d = Math.max(min, d);
  2080. maxValue = Math.min(max, maxValue);
  2081. if (d > maxValue) {
  2082. return false;
  2083. }
  2084. }
  2085. if (Math.abs(this.direction.y) < 0.0000001) {
  2086. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2087. return false;
  2088. }
  2089. }
  2090. else {
  2091. inv = 1.0 / this.direction.y;
  2092. min = (minimum.y - this.origin.y) * inv;
  2093. max = (maximum.y - this.origin.y) * inv;
  2094. if (max === -Infinity) {
  2095. max = Infinity;
  2096. }
  2097. if (min > max) {
  2098. temp = min;
  2099. min = max;
  2100. max = temp;
  2101. }
  2102. d = Math.max(min, d);
  2103. maxValue = Math.min(max, maxValue);
  2104. if (d > maxValue) {
  2105. return false;
  2106. }
  2107. }
  2108. if (Math.abs(this.direction.z) < 0.0000001) {
  2109. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2110. return false;
  2111. }
  2112. }
  2113. else {
  2114. inv = 1.0 / this.direction.z;
  2115. min = (minimum.z - this.origin.z) * inv;
  2116. max = (maximum.z - this.origin.z) * inv;
  2117. if (max === -Infinity) {
  2118. max = Infinity;
  2119. }
  2120. if (min > max) {
  2121. temp = min;
  2122. min = max;
  2123. max = temp;
  2124. }
  2125. d = Math.max(min, d);
  2126. maxValue = Math.min(max, maxValue);
  2127. if (d > maxValue) {
  2128. return false;
  2129. }
  2130. }
  2131. return true;
  2132. };
  2133. Ray.prototype.intersectsBox = function (box) {
  2134. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2135. };
  2136. Ray.prototype.intersectsSphere = function (sphere) {
  2137. var x = sphere.center.x - this.origin.x;
  2138. var y = sphere.center.y - this.origin.y;
  2139. var z = sphere.center.z - this.origin.z;
  2140. var pyth = (x * x) + (y * y) + (z * z);
  2141. var rr = sphere.radius * sphere.radius;
  2142. if (pyth <= rr) {
  2143. return true;
  2144. }
  2145. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2146. if (dot < 0.0) {
  2147. return false;
  2148. }
  2149. var temp = pyth - (dot * dot);
  2150. return temp <= rr;
  2151. };
  2152. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2153. if (!this._edge1) {
  2154. this._edge1 = Vector3.Zero();
  2155. this._edge2 = Vector3.Zero();
  2156. this._pvec = Vector3.Zero();
  2157. this._tvec = Vector3.Zero();
  2158. this._qvec = Vector3.Zero();
  2159. }
  2160. vertex1.subtractToRef(vertex0, this._edge1);
  2161. vertex2.subtractToRef(vertex0, this._edge2);
  2162. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2163. var det = Vector3.Dot(this._edge1, this._pvec);
  2164. if (det === 0) {
  2165. return null;
  2166. }
  2167. var invdet = 1 / det;
  2168. this.origin.subtractToRef(vertex0, this._tvec);
  2169. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2170. if (bu < 0 || bu > 1.0) {
  2171. return null;
  2172. }
  2173. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2174. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2175. if (bv < 0 || bu + bv > 1.0) {
  2176. return null;
  2177. }
  2178. //check if the distance is longer than the predefined length.
  2179. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2180. if (distance > this.length) {
  2181. return null;
  2182. }
  2183. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2184. };
  2185. // Statics
  2186. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2187. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2188. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2189. var direction = end.subtract(start);
  2190. direction.normalize();
  2191. return new Ray(start, direction);
  2192. };
  2193. /**
  2194. * 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
  2195. * transformed to the given world matrix.
  2196. * @param origin The origin point
  2197. * @param end The end point
  2198. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2199. */
  2200. Ray.CreateNewFromTo = function (origin, end, world) {
  2201. if (world === void 0) { world = Matrix.Identity(); }
  2202. var direction = end.subtract(origin);
  2203. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2204. direction.normalize();
  2205. return Ray.Transform(new Ray(origin, direction, length), world);
  2206. };
  2207. Ray.Transform = function (ray, matrix) {
  2208. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2209. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2210. return new Ray(newOrigin, newDirection, ray.length);
  2211. };
  2212. return Ray;
  2213. })();
  2214. BABYLON.Ray = Ray;
  2215. (function (Space) {
  2216. Space[Space["LOCAL"] = 0] = "LOCAL";
  2217. Space[Space["WORLD"] = 1] = "WORLD";
  2218. })(BABYLON.Space || (BABYLON.Space = {}));
  2219. var Space = BABYLON.Space;
  2220. var Axis = (function () {
  2221. function Axis() {
  2222. }
  2223. Axis.X = new Vector3(1, 0, 0);
  2224. Axis.Y = new Vector3(0, 1, 0);
  2225. Axis.Z = new Vector3(0, 0, 1);
  2226. return Axis;
  2227. })();
  2228. BABYLON.Axis = Axis;
  2229. ;
  2230. var BezierCurve = (function () {
  2231. function BezierCurve() {
  2232. }
  2233. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2234. // Extract X (which is equal to time here)
  2235. var f0 = 1 - 3 * x2 + 3 * x1;
  2236. var f1 = 3 * x2 - 6 * x1;
  2237. var f2 = 3 * x1;
  2238. var refinedT = t;
  2239. for (var i = 0; i < 5; i++) {
  2240. var refinedT2 = refinedT * refinedT;
  2241. var refinedT3 = refinedT2 * refinedT;
  2242. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2243. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2244. refinedT -= (x - t) * slope;
  2245. refinedT = Math.min(1, Math.max(0, refinedT));
  2246. }
  2247. // Resolve cubic bezier for the given x
  2248. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2249. };
  2250. return BezierCurve;
  2251. })();
  2252. BABYLON.BezierCurve = BezierCurve;
  2253. (function (Orientation) {
  2254. Orientation[Orientation["CW"] = 0] = "CW";
  2255. Orientation[Orientation["CCW"] = 1] = "CCW";
  2256. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2257. var Orientation = BABYLON.Orientation;
  2258. var Angle = (function () {
  2259. function Angle(radians) {
  2260. var _this = this;
  2261. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2262. this.radians = function () { return _this._radians; };
  2263. this._radians = radians;
  2264. if (this._radians < 0)
  2265. this._radians += (2 * Math.PI);
  2266. }
  2267. Angle.BetweenTwoPoints = function (a, b) {
  2268. var delta = b.subtract(a);
  2269. var theta = Math.atan2(delta.y, delta.x);
  2270. return new Angle(theta);
  2271. };
  2272. Angle.FromRadians = function (radians) {
  2273. return new Angle(radians);
  2274. };
  2275. Angle.FromDegrees = function (degrees) {
  2276. return new Angle(degrees * Math.PI / 180);
  2277. };
  2278. return Angle;
  2279. })();
  2280. BABYLON.Angle = Angle;
  2281. var Arc2 = (function () {
  2282. function Arc2(startPoint, midPoint, endPoint) {
  2283. this.startPoint = startPoint;
  2284. this.midPoint = midPoint;
  2285. this.endPoint = endPoint;
  2286. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2287. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2288. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2289. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2290. 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);
  2291. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2292. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2293. var a1 = this.startAngle.degrees();
  2294. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2295. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2296. // angles correction
  2297. if (a2 - a1 > +180.0)
  2298. a2 -= 360.0;
  2299. if (a2 - a1 < -180.0)
  2300. a2 += 360.0;
  2301. if (a3 - a2 > +180.0)
  2302. a3 -= 360.0;
  2303. if (a3 - a2 < -180.0)
  2304. a3 += 360.0;
  2305. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2306. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2307. }
  2308. return Arc2;
  2309. })();
  2310. BABYLON.Arc2 = Arc2;
  2311. var PathCursor = (function () {
  2312. function PathCursor(path) {
  2313. this.path = path;
  2314. this._onchange = new Array();
  2315. this.value = 0;
  2316. this.animations = new Array();
  2317. }
  2318. PathCursor.prototype.getPoint = function () {
  2319. var point = this.path.getPointAtLengthPosition(this.value);
  2320. return new Vector3(point.x, 0, point.y);
  2321. };
  2322. PathCursor.prototype.moveAhead = function (step) {
  2323. if (step === void 0) { step = 0.002; }
  2324. this.move(step);
  2325. return this;
  2326. };
  2327. PathCursor.prototype.moveBack = function (step) {
  2328. if (step === void 0) { step = 0.002; }
  2329. this.move(-step);
  2330. return this;
  2331. };
  2332. PathCursor.prototype.move = function (step) {
  2333. if (Math.abs(step) > 1) {
  2334. throw "step size should be less than 1.";
  2335. }
  2336. this.value += step;
  2337. this.ensureLimits();
  2338. this.raiseOnChange();
  2339. return this;
  2340. };
  2341. PathCursor.prototype.ensureLimits = function () {
  2342. while (this.value > 1) {
  2343. this.value -= 1;
  2344. }
  2345. while (this.value < 0) {
  2346. this.value += 1;
  2347. }
  2348. return this;
  2349. };
  2350. // used by animation engine
  2351. PathCursor.prototype.markAsDirty = function (propertyName) {
  2352. this.ensureLimits();
  2353. this.raiseOnChange();
  2354. return this;
  2355. };
  2356. PathCursor.prototype.raiseOnChange = function () {
  2357. var _this = this;
  2358. this._onchange.forEach(function (f) { return f(_this); });
  2359. return this;
  2360. };
  2361. PathCursor.prototype.onchange = function (f) {
  2362. this._onchange.push(f);
  2363. return this;
  2364. };
  2365. return PathCursor;
  2366. })();
  2367. BABYLON.PathCursor = PathCursor;
  2368. var Path2 = (function () {
  2369. function Path2(x, y) {
  2370. this._points = new Array();
  2371. this._length = 0;
  2372. this.closed = false;
  2373. this._points.push(new Vector2(x, y));
  2374. }
  2375. Path2.prototype.addLineTo = function (x, y) {
  2376. if (closed) {
  2377. BABYLON.Tools.Error("cannot add lines to closed paths");
  2378. return this;
  2379. }
  2380. var newPoint = new Vector2(x, y);
  2381. var previousPoint = this._points[this._points.length - 1];
  2382. this._points.push(newPoint);
  2383. this._length += newPoint.subtract(previousPoint).length();
  2384. return this;
  2385. };
  2386. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2387. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2388. if (closed) {
  2389. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2390. return this;
  2391. }
  2392. var startPoint = this._points[this._points.length - 1];
  2393. var midPoint = new Vector2(midX, midY);
  2394. var endPoint = new Vector2(endX, endY);
  2395. var arc = new Arc2(startPoint, midPoint, endPoint);
  2396. var increment = arc.angle.radians() / numberOfSegments;
  2397. if (arc.orientation === 0 /* CW */)
  2398. increment *= -1;
  2399. var currentAngle = arc.startAngle.radians() + increment;
  2400. for (var i = 0; i < numberOfSegments; i++) {
  2401. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2402. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2403. this.addLineTo(x, y);
  2404. currentAngle += increment;
  2405. }
  2406. return this;
  2407. };
  2408. Path2.prototype.close = function () {
  2409. this.closed = true;
  2410. return this;
  2411. };
  2412. Path2.prototype.length = function () {
  2413. var result = this._length;
  2414. if (!this.closed) {
  2415. var lastPoint = this._points[this._points.length - 1];
  2416. var firstPoint = this._points[0];
  2417. result += (firstPoint.subtract(lastPoint).length());
  2418. }
  2419. return result;
  2420. };
  2421. Path2.prototype.getPoints = function () {
  2422. return this._points;
  2423. };
  2424. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2425. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2426. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2427. return Vector2.Zero();
  2428. }
  2429. var lengthPosition = normalizedLengthPosition * this.length();
  2430. var previousOffset = 0;
  2431. for (var i = 0; i < this._points.length; i++) {
  2432. var j = (i + 1) % this._points.length;
  2433. var a = this._points[i];
  2434. var b = this._points[j];
  2435. var bToA = b.subtract(a);
  2436. var nextOffset = (bToA.length() + previousOffset);
  2437. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2438. var dir = bToA.normalize();
  2439. var localOffset = lengthPosition - previousOffset;
  2440. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2441. }
  2442. previousOffset = nextOffset;
  2443. }
  2444. BABYLON.Tools.Error("internal error");
  2445. return Vector2.Zero();
  2446. };
  2447. Path2.StartingAt = function (x, y) {
  2448. return new Path2(x, y);
  2449. };
  2450. return Path2;
  2451. })();
  2452. BABYLON.Path2 = Path2;
  2453. var Path3D = (function () {
  2454. function Path3D(path) {
  2455. this.path = path;
  2456. this._curve = new Array();
  2457. this._distances = new Array();
  2458. this._tangents = new Array();
  2459. this._normals = new Array();
  2460. this._binormals = new Array();
  2461. this._curve = path.slice(); // copy array
  2462. var l = this._curve.length;
  2463. // first and last tangents
  2464. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2465. this._tangents[0].normalize();
  2466. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2467. this._tangents[l - 1].normalize();
  2468. // normals and binormals at first point : arbitrary vector with _normalVector()
  2469. var tg0 = this._tangents[0];
  2470. var pp0 = this._normalVector(this._curve[0], tg0);
  2471. this._normals[0] = pp0;
  2472. this._normals[0].normalize();
  2473. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2474. this._normals[0].normalize();
  2475. this._distances[0] = 0;
  2476. // normals and binormals : next points
  2477. var prev; // previous vector (segment)
  2478. var cur; // current vector (segment)
  2479. var curTang; // current tangent
  2480. var prevNorm; // previous normal
  2481. var prevBinor; // previous binormal
  2482. for (var i = 1; i < l; i++) {
  2483. // tangents
  2484. prev = this._curve[i].subtract(this._curve[i - 1]);
  2485. if (i < l - 1) {
  2486. cur = this._curve[i + 1].subtract(this._curve[i]);
  2487. this._tangents[i] = prev.add(cur);
  2488. this._tangents[i].normalize();
  2489. }
  2490. this._distances[i] = this._distances[i - 1] + prev.length();
  2491. // normals and binormals
  2492. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2493. curTang = this._tangents[i];
  2494. prevNorm = this._normals[i - 1];
  2495. prevBinor = this._binormals[i - 1];
  2496. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2497. this._normals[i].normalize();
  2498. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2499. this._binormals[i].normalize();
  2500. }
  2501. }
  2502. Path3D.prototype.getCurve = function () {
  2503. return this._curve;
  2504. };
  2505. Path3D.prototype.getTangents = function () {
  2506. return this._tangents;
  2507. };
  2508. Path3D.prototype.getNormals = function () {
  2509. return this._normals;
  2510. };
  2511. Path3D.prototype.getBinormals = function () {
  2512. return this._binormals;
  2513. };
  2514. Path3D.prototype.getDistances = function () {
  2515. return this._distances;
  2516. };
  2517. // private function normalVector(v0, vt) :
  2518. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2519. Path3D.prototype._normalVector = function (v0, vt) {
  2520. var point;
  2521. if (vt.x !== 1) {
  2522. point = new Vector3(1, 0, 0);
  2523. }
  2524. else if (vt.y !== 1) {
  2525. point = new Vector3(0, 1, 0);
  2526. }
  2527. else if (vt.z !== 1) {
  2528. point = new Vector3(0, 0, 1);
  2529. }
  2530. var normal0 = Vector3.Cross(vt, point);
  2531. normal0.normalize();
  2532. return normal0;
  2533. };
  2534. return Path3D;
  2535. })();
  2536. BABYLON.Path3D = Path3D;
  2537. var Curve3 = (function () {
  2538. function Curve3(points) {
  2539. this._points = points;
  2540. }
  2541. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2542. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2543. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2544. var bez = new Array();
  2545. var step = 1 / nbPoints;
  2546. var equation = function (t, val0, val1, val2) {
  2547. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2548. return res;
  2549. };
  2550. for (var i = 0; i <= 1; i += step) {
  2551. 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)));
  2552. }
  2553. return new Curve3(bez);
  2554. };
  2555. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2556. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2557. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2558. var bez = new Array();
  2559. var step = 1 / nbPoints;
  2560. var equation = function (t, val0, val1, val2, val3) {
  2561. 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;
  2562. return res;
  2563. };
  2564. for (var i = 0; i <= 1; i += step) {
  2565. 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)));
  2566. }
  2567. return new Curve3(bez);
  2568. };
  2569. Curve3.prototype.getPoints = function () {
  2570. return this._points;
  2571. };
  2572. return Curve3;
  2573. })();
  2574. BABYLON.Curve3 = Curve3;
  2575. // SIMD
  2576. if (window.SIMD !== undefined) {
  2577. // Replace functions
  2578. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2579. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2580. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2581. }
  2582. })(BABYLON || (BABYLON = {}));
  2583. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2584. (function (BABYLON) {
  2585. // Screenshots
  2586. var screenshotCanvas;
  2587. var cloneValue = function (source, destinationObject) {
  2588. if (!source)
  2589. return null;
  2590. if (source instanceof BABYLON.Mesh) {
  2591. return null;
  2592. }
  2593. if (source instanceof BABYLON.SubMesh) {
  2594. return source.clone(destinationObject);
  2595. }
  2596. else if (source.clone) {
  2597. return source.clone();
  2598. }
  2599. return null;
  2600. };
  2601. var Tools = (function () {
  2602. function Tools() {
  2603. }
  2604. Tools.GetFilename = function (path) {
  2605. var index = path.lastIndexOf("/");
  2606. if (index < 0)
  2607. return path;
  2608. return path.substring(index + 1);
  2609. };
  2610. Tools.GetDOMTextContent = function (element) {
  2611. var result = "";
  2612. var child = element.firstChild;
  2613. while (child) {
  2614. if (child.nodeType === 3) {
  2615. result += child.textContent;
  2616. }
  2617. child = child.nextSibling;
  2618. }
  2619. return result;
  2620. };
  2621. Tools.ToDegrees = function (angle) {
  2622. return angle * 180 / Math.PI;
  2623. };
  2624. Tools.ToRadians = function (angle) {
  2625. return angle * Math.PI / 180;
  2626. };
  2627. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2628. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2629. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2630. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2631. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2632. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2633. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2634. }
  2635. return {
  2636. minimum: minimum,
  2637. maximum: maximum
  2638. };
  2639. };
  2640. Tools.ExtractMinAndMax = function (positions, start, count) {
  2641. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2642. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2643. for (var index = start; index < start + count; index++) {
  2644. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2645. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2646. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2647. }
  2648. return {
  2649. minimum: minimum,
  2650. maximum: maximum
  2651. };
  2652. };
  2653. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2654. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2655. return undefined;
  2656. return Array.isArray(obj) ? obj : [obj];
  2657. };
  2658. // Misc.
  2659. Tools.GetPointerPrefix = function () {
  2660. var eventPrefix = "pointer";
  2661. // Check if hand.js is referenced or if the browser natively supports pointer events
  2662. if (!navigator.pointerEnabled) {
  2663. eventPrefix = "mouse";
  2664. }
  2665. return eventPrefix;
  2666. };
  2667. Tools.QueueNewFrame = function (func) {
  2668. if (window.requestAnimationFrame)
  2669. window.requestAnimationFrame(func);
  2670. else if (window.msRequestAnimationFrame)
  2671. window.msRequestAnimationFrame(func);
  2672. else if (window.webkitRequestAnimationFrame)
  2673. window.webkitRequestAnimationFrame(func);
  2674. else if (window.mozRequestAnimationFrame)
  2675. window.mozRequestAnimationFrame(func);
  2676. else if (window.oRequestAnimationFrame)
  2677. window.oRequestAnimationFrame(func);
  2678. else {
  2679. window.setTimeout(func, 16);
  2680. }
  2681. };
  2682. Tools.RequestFullscreen = function (element) {
  2683. if (element.requestFullscreen)
  2684. element.requestFullscreen();
  2685. else if (element.msRequestFullscreen)
  2686. element.msRequestFullscreen();
  2687. else if (element.webkitRequestFullscreen)
  2688. element.webkitRequestFullscreen();
  2689. else if (element.mozRequestFullScreen)
  2690. element.mozRequestFullScreen();
  2691. };
  2692. Tools.ExitFullscreen = function () {
  2693. if (document.exitFullscreen) {
  2694. document.exitFullscreen();
  2695. }
  2696. else if (document.mozCancelFullScreen) {
  2697. document.mozCancelFullScreen();
  2698. }
  2699. else if (document.webkitCancelFullScreen) {
  2700. document.webkitCancelFullScreen();
  2701. }
  2702. else if (document.msCancelFullScreen) {
  2703. document.msCancelFullScreen();
  2704. }
  2705. };
  2706. // External files
  2707. Tools.CleanUrl = function (url) {
  2708. url = url.replace(/#/mg, "%23");
  2709. return url;
  2710. };
  2711. Tools.LoadImage = function (url, onload, onerror, database) {
  2712. url = Tools.CleanUrl(url);
  2713. var img = new Image();
  2714. if (url.substr(0, 5) !== "data:")
  2715. img.crossOrigin = 'anonymous';
  2716. img.onload = function () {
  2717. onload(img);
  2718. };
  2719. img.onerror = function (err) {
  2720. onerror(img, err);
  2721. };
  2722. var noIndexedDB = function () {
  2723. img.src = url;
  2724. };
  2725. var loadFromIndexedDB = function () {
  2726. database.loadImageFromDB(url, img);
  2727. };
  2728. //ANY database to do!
  2729. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2730. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2731. }
  2732. else {
  2733. if (url.indexOf("file:") === -1) {
  2734. noIndexedDB();
  2735. }
  2736. else {
  2737. try {
  2738. var textureName = url.substring(5);
  2739. var blobURL;
  2740. try {
  2741. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2742. }
  2743. catch (ex) {
  2744. // Chrome doesn't support oneTimeOnly parameter
  2745. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2746. }
  2747. img.src = blobURL;
  2748. }
  2749. catch (e) {
  2750. Tools.Log("Error while trying to load texture: " + textureName);
  2751. img.src = null;
  2752. }
  2753. }
  2754. }
  2755. return img;
  2756. };
  2757. //ANY
  2758. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2759. url = Tools.CleanUrl(url);
  2760. var noIndexedDB = function () {
  2761. var request = new XMLHttpRequest();
  2762. var loadUrl = Tools.BaseUrl + url;
  2763. request.open('GET', loadUrl, true);
  2764. if (useArrayBuffer) {
  2765. request.responseType = "arraybuffer";
  2766. }
  2767. request.onprogress = progressCallBack;
  2768. request.onreadystatechange = function () {
  2769. if (request.readyState === 4) {
  2770. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2771. callback(!useArrayBuffer ? request.responseText : request.response);
  2772. }
  2773. else {
  2774. if (onError) {
  2775. onError();
  2776. }
  2777. else {
  2778. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2779. }
  2780. }
  2781. }
  2782. };
  2783. request.send(null);
  2784. };
  2785. var loadFromIndexedDB = function () {
  2786. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2787. };
  2788. if (url.indexOf("file:") !== -1) {
  2789. var fileName = url.substring(5);
  2790. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2791. }
  2792. else {
  2793. // Caching all files
  2794. if (database && database.enableSceneOffline) {
  2795. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2796. }
  2797. else {
  2798. noIndexedDB();
  2799. }
  2800. }
  2801. };
  2802. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2803. var reader = new FileReader();
  2804. reader.onload = function (e) {
  2805. //target doesn't have result from ts 1.3
  2806. callback(e.target['result']);
  2807. };
  2808. reader.onprogress = progressCallback;
  2809. reader.readAsDataURL(fileToLoad);
  2810. };
  2811. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2812. var reader = new FileReader();
  2813. reader.onerror = function (e) {
  2814. Tools.Log("Error while reading file: " + fileToLoad.name);
  2815. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  2816. };
  2817. reader.onload = function (e) {
  2818. //target doesn't have result from ts 1.3
  2819. callback(e.target['result']);
  2820. };
  2821. reader.onprogress = progressCallBack;
  2822. if (!useArrayBuffer) {
  2823. // Asynchronous read
  2824. reader.readAsText(fileToLoad);
  2825. }
  2826. else {
  2827. reader.readAsArrayBuffer(fileToLoad);
  2828. }
  2829. };
  2830. // Misc.
  2831. Tools.Clamp = function (value, min, max) {
  2832. if (min === void 0) { min = 0; }
  2833. if (max === void 0) { max = 1; }
  2834. return Math.min(max, Math.max(min, value));
  2835. };
  2836. // Returns -1 when value is a negative number and
  2837. // +1 when value is a positive number.
  2838. Tools.Sign = function (value) {
  2839. value = +value; // convert to a number
  2840. if (value === 0 || isNaN(value))
  2841. return value;
  2842. return value > 0 ? 1 : -1;
  2843. };
  2844. Tools.Format = function (value, decimals) {
  2845. if (decimals === void 0) { decimals = 2; }
  2846. return value.toFixed(decimals);
  2847. };
  2848. Tools.CheckExtends = function (v, min, max) {
  2849. if (v.x < min.x)
  2850. min.x = v.x;
  2851. if (v.y < min.y)
  2852. min.y = v.y;
  2853. if (v.z < min.z)
  2854. min.z = v.z;
  2855. if (v.x > max.x)
  2856. max.x = v.x;
  2857. if (v.y > max.y)
  2858. max.y = v.y;
  2859. if (v.z > max.z)
  2860. max.z = v.z;
  2861. };
  2862. Tools.WithinEpsilon = function (a, b, epsilon) {
  2863. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2864. var num = a - b;
  2865. return -epsilon <= num && num <= epsilon;
  2866. };
  2867. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2868. for (var prop in source) {
  2869. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2870. continue;
  2871. }
  2872. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2873. continue;
  2874. }
  2875. var sourceValue = source[prop];
  2876. var typeOfSourceValue = typeof sourceValue;
  2877. if (typeOfSourceValue === "function") {
  2878. continue;
  2879. }
  2880. if (typeOfSourceValue === "object") {
  2881. if (sourceValue instanceof Array) {
  2882. destination[prop] = [];
  2883. if (sourceValue.length > 0) {
  2884. if (typeof sourceValue[0] == "object") {
  2885. for (var index = 0; index < sourceValue.length; index++) {
  2886. var clonedValue = cloneValue(sourceValue[index], destination);
  2887. if (destination[prop].indexOf(clonedValue) === -1) {
  2888. destination[prop].push(clonedValue);
  2889. }
  2890. }
  2891. }
  2892. else {
  2893. destination[prop] = sourceValue.slice(0);
  2894. }
  2895. }
  2896. }
  2897. else {
  2898. destination[prop] = cloneValue(sourceValue, destination);
  2899. }
  2900. }
  2901. else {
  2902. destination[prop] = sourceValue;
  2903. }
  2904. }
  2905. };
  2906. Tools.IsEmpty = function (obj) {
  2907. for (var i in obj) {
  2908. return false;
  2909. }
  2910. return true;
  2911. };
  2912. Tools.RegisterTopRootEvents = function (events) {
  2913. for (var index = 0; index < events.length; index++) {
  2914. var event = events[index];
  2915. window.addEventListener(event.name, event.handler, false);
  2916. try {
  2917. if (window.parent) {
  2918. window.parent.addEventListener(event.name, event.handler, false);
  2919. }
  2920. }
  2921. catch (e) {
  2922. }
  2923. }
  2924. };
  2925. Tools.UnregisterTopRootEvents = function (events) {
  2926. for (var index = 0; index < events.length; index++) {
  2927. var event = events[index];
  2928. window.removeEventListener(event.name, event.handler);
  2929. try {
  2930. if (window.parent) {
  2931. window.parent.removeEventListener(event.name, event.handler);
  2932. }
  2933. }
  2934. catch (e) {
  2935. }
  2936. }
  2937. };
  2938. Tools.DumpFramebuffer = function (width, height, engine) {
  2939. // Read the contents of the framebuffer
  2940. var numberOfChannelsByLine = width * 4;
  2941. var halfHeight = height / 2;
  2942. //Reading datas from WebGL
  2943. var data = engine.readPixels(0, 0, width, height);
  2944. for (var i = 0; i < halfHeight; i++) {
  2945. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2946. var currentCell = j + i * numberOfChannelsByLine;
  2947. var targetLine = height - i - 1;
  2948. var targetCell = j + targetLine * numberOfChannelsByLine;
  2949. var temp = data[currentCell];
  2950. data[currentCell] = data[targetCell];
  2951. data[targetCell] = temp;
  2952. }
  2953. }
  2954. // Create a 2D canvas to store the result
  2955. if (!screenshotCanvas) {
  2956. screenshotCanvas = document.createElement('canvas');
  2957. }
  2958. screenshotCanvas.width = width;
  2959. screenshotCanvas.height = height;
  2960. var context = screenshotCanvas.getContext('2d');
  2961. // Copy the pixels to a 2D canvas
  2962. var imageData = context.createImageData(width, height);
  2963. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2964. var castData = imageData.data;
  2965. castData.set(data);
  2966. context.putImageData(imageData, 0, 0);
  2967. var base64Image = screenshotCanvas.toDataURL();
  2968. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2969. if (("download" in document.createElement("a"))) {
  2970. var a = window.document.createElement("a");
  2971. a.href = base64Image;
  2972. var date = new Date();
  2973. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2974. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2975. window.document.body.appendChild(a);
  2976. a.addEventListener("click", function () {
  2977. a.parentElement.removeChild(a);
  2978. });
  2979. a.click();
  2980. }
  2981. else {
  2982. var newWindow = window.open("");
  2983. var img = newWindow.document.createElement("img");
  2984. img.src = base64Image;
  2985. newWindow.document.body.appendChild(img);
  2986. }
  2987. };
  2988. Tools.CreateScreenshot = function (engine, camera, size) {
  2989. var width;
  2990. var height;
  2991. var scene = camera.getScene();
  2992. var previousCamera = null;
  2993. if (scene.activeCamera !== camera) {
  2994. previousCamera = scene.activeCamera;
  2995. scene.activeCamera = camera;
  2996. }
  2997. //If a precision value is specified
  2998. if (size.precision) {
  2999. width = Math.round(engine.getRenderWidth() * size.precision);
  3000. height = Math.round(width / engine.getAspectRatio(camera));
  3001. size = { width: width, height: height };
  3002. }
  3003. else if (size.width && size.height) {
  3004. width = size.width;
  3005. height = size.height;
  3006. }
  3007. else if (size.width && !size.height) {
  3008. width = size.width;
  3009. height = Math.round(width / engine.getAspectRatio(camera));
  3010. size = { width: width, height: height };
  3011. }
  3012. else if (size.height && !size.width) {
  3013. height = size.height;
  3014. width = Math.round(height * engine.getAspectRatio(camera));
  3015. size = { width: width, height: height };
  3016. }
  3017. else if (!isNaN(size)) {
  3018. height = size;
  3019. width = size;
  3020. }
  3021. else {
  3022. Tools.Error("Invalid 'size' parameter !");
  3023. return;
  3024. }
  3025. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3026. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3027. texture.renderList = scene.meshes;
  3028. texture.onAfterRender = function () {
  3029. Tools.DumpFramebuffer(width, height, engine);
  3030. };
  3031. scene.incrementRenderId();
  3032. texture.render(true);
  3033. texture.dispose();
  3034. if (previousCamera) {
  3035. scene.activeCamera = previousCamera;
  3036. }
  3037. };
  3038. // XHR response validator for local file scenario
  3039. Tools.ValidateXHRData = function (xhr, dataType) {
  3040. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3041. if (dataType === void 0) { dataType = 7; }
  3042. try {
  3043. if (dataType & 1) {
  3044. if (xhr.responseText && xhr.responseText.length > 0) {
  3045. return true;
  3046. }
  3047. else if (dataType === 1) {
  3048. return false;
  3049. }
  3050. }
  3051. if (dataType & 2) {
  3052. // Check header width and height since there is no "TGA" magic number
  3053. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3054. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3055. return true;
  3056. }
  3057. else if (dataType === 2) {
  3058. return false;
  3059. }
  3060. }
  3061. if (dataType & 4) {
  3062. // Check for the "DDS" magic number
  3063. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3064. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3065. return true;
  3066. }
  3067. else {
  3068. return false;
  3069. }
  3070. }
  3071. }
  3072. catch (e) {
  3073. }
  3074. return false;
  3075. };
  3076. Object.defineProperty(Tools, "NoneLogLevel", {
  3077. get: function () {
  3078. return Tools._NoneLogLevel;
  3079. },
  3080. enumerable: true,
  3081. configurable: true
  3082. });
  3083. Object.defineProperty(Tools, "MessageLogLevel", {
  3084. get: function () {
  3085. return Tools._MessageLogLevel;
  3086. },
  3087. enumerable: true,
  3088. configurable: true
  3089. });
  3090. Object.defineProperty(Tools, "WarningLogLevel", {
  3091. get: function () {
  3092. return Tools._WarningLogLevel;
  3093. },
  3094. enumerable: true,
  3095. configurable: true
  3096. });
  3097. Object.defineProperty(Tools, "ErrorLogLevel", {
  3098. get: function () {
  3099. return Tools._ErrorLogLevel;
  3100. },
  3101. enumerable: true,
  3102. configurable: true
  3103. });
  3104. Object.defineProperty(Tools, "AllLogLevel", {
  3105. get: function () {
  3106. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3107. },
  3108. enumerable: true,
  3109. configurable: true
  3110. });
  3111. Tools._AddLogEntry = function (entry) {
  3112. Tools._LogCache = entry + Tools._LogCache;
  3113. if (Tools.OnNewCacheEntry) {
  3114. Tools.OnNewCacheEntry(entry);
  3115. }
  3116. };
  3117. Tools._FormatMessage = function (message) {
  3118. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3119. var date = new Date();
  3120. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3121. };
  3122. Tools._LogDisabled = function (message) {
  3123. // nothing to do
  3124. };
  3125. Tools._LogEnabled = function (message) {
  3126. var formattedMessage = Tools._FormatMessage(message);
  3127. console.log("BJS - " + formattedMessage);
  3128. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3129. Tools._AddLogEntry(entry);
  3130. };
  3131. Tools._WarnDisabled = function (message) {
  3132. // nothing to do
  3133. };
  3134. Tools._WarnEnabled = function (message) {
  3135. var formattedMessage = Tools._FormatMessage(message);
  3136. console.warn("BJS - " + formattedMessage);
  3137. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3138. Tools._AddLogEntry(entry);
  3139. };
  3140. Tools._ErrorDisabled = function (message) {
  3141. // nothing to do
  3142. };
  3143. Tools._ErrorEnabled = function (message) {
  3144. var formattedMessage = Tools._FormatMessage(message);
  3145. console.error("BJS - " + formattedMessage);
  3146. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3147. Tools._AddLogEntry(entry);
  3148. };
  3149. Object.defineProperty(Tools, "LogCache", {
  3150. get: function () {
  3151. return Tools._LogCache;
  3152. },
  3153. enumerable: true,
  3154. configurable: true
  3155. });
  3156. Object.defineProperty(Tools, "LogLevels", {
  3157. set: function (level) {
  3158. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3159. Tools.Log = Tools._LogEnabled;
  3160. }
  3161. else {
  3162. Tools.Log = Tools._LogDisabled;
  3163. }
  3164. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3165. Tools.Warn = Tools._WarnEnabled;
  3166. }
  3167. else {
  3168. Tools.Warn = Tools._WarnDisabled;
  3169. }
  3170. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3171. Tools.Error = Tools._ErrorEnabled;
  3172. }
  3173. else {
  3174. Tools.Error = Tools._ErrorDisabled;
  3175. }
  3176. },
  3177. enumerable: true,
  3178. configurable: true
  3179. });
  3180. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3181. get: function () {
  3182. return Tools._PerformanceNoneLogLevel;
  3183. },
  3184. enumerable: true,
  3185. configurable: true
  3186. });
  3187. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3188. get: function () {
  3189. return Tools._PerformanceUserMarkLogLevel;
  3190. },
  3191. enumerable: true,
  3192. configurable: true
  3193. });
  3194. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3195. get: function () {
  3196. return Tools._PerformanceConsoleLogLevel;
  3197. },
  3198. enumerable: true,
  3199. configurable: true
  3200. });
  3201. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3202. set: function (level) {
  3203. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3204. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3205. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3206. return;
  3207. }
  3208. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3209. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3210. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3211. return;
  3212. }
  3213. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3214. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3215. },
  3216. enumerable: true,
  3217. configurable: true
  3218. });
  3219. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3220. };
  3221. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3222. };
  3223. Tools._StartUserMark = function (counterName, condition) {
  3224. if (condition === void 0) { condition = true; }
  3225. if (!condition || !Tools._performance.mark) {
  3226. return;
  3227. }
  3228. Tools._performance.mark(counterName + "-Begin");
  3229. };
  3230. Tools._EndUserMark = function (counterName, condition) {
  3231. if (condition === void 0) { condition = true; }
  3232. if (!condition || !Tools._performance.mark) {
  3233. return;
  3234. }
  3235. Tools._performance.mark(counterName + "-End");
  3236. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3237. };
  3238. Tools._StartPerformanceConsole = function (counterName, condition) {
  3239. if (condition === void 0) { condition = true; }
  3240. if (!condition) {
  3241. return;
  3242. }
  3243. Tools._StartUserMark(counterName, condition);
  3244. if (console.time) {
  3245. console.time(counterName);
  3246. }
  3247. };
  3248. Tools._EndPerformanceConsole = function (counterName, condition) {
  3249. if (condition === void 0) { condition = true; }
  3250. if (!condition) {
  3251. return;
  3252. }
  3253. Tools._EndUserMark(counterName, condition);
  3254. if (console.time) {
  3255. console.timeEnd(counterName);
  3256. }
  3257. };
  3258. Object.defineProperty(Tools, "Now", {
  3259. get: function () {
  3260. if (window.performance && window.performance.now) {
  3261. return window.performance.now();
  3262. }
  3263. return new Date().getTime();
  3264. },
  3265. enumerable: true,
  3266. configurable: true
  3267. });
  3268. // Deprecated
  3269. Tools.GetFps = function () {
  3270. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3271. return 0;
  3272. };
  3273. Tools.BaseUrl = "";
  3274. Tools.GetExponantOfTwo = function (value, max) {
  3275. var count = 1;
  3276. do {
  3277. count *= 2;
  3278. } while (count < value);
  3279. if (count > max)
  3280. count = max;
  3281. return count;
  3282. };
  3283. // Logs
  3284. Tools._NoneLogLevel = 0;
  3285. Tools._MessageLogLevel = 1;
  3286. Tools._WarningLogLevel = 2;
  3287. Tools._ErrorLogLevel = 4;
  3288. Tools._LogCache = "";
  3289. Tools.Log = Tools._LogEnabled;
  3290. Tools.Warn = Tools._WarnEnabled;
  3291. Tools.Error = Tools._ErrorEnabled;
  3292. // Performances
  3293. Tools._PerformanceNoneLogLevel = 0;
  3294. Tools._PerformanceUserMarkLogLevel = 1;
  3295. Tools._PerformanceConsoleLogLevel = 2;
  3296. Tools._performance = window.performance;
  3297. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3298. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3299. return Tools;
  3300. })();
  3301. BABYLON.Tools = Tools;
  3302. /**
  3303. * An implementation of a loop for asynchronous functions.
  3304. */
  3305. var AsyncLoop = (function () {
  3306. /**
  3307. * Constroctor.
  3308. * @param iterations the number of iterations.
  3309. * @param _fn the function to run each iteration
  3310. * @param _successCallback the callback that will be called upon succesful execution
  3311. * @param offset starting offset.
  3312. */
  3313. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3314. if (offset === void 0) { offset = 0; }
  3315. this.iterations = iterations;
  3316. this._fn = _fn;
  3317. this._successCallback = _successCallback;
  3318. this.index = offset - 1;
  3319. this._done = false;
  3320. }
  3321. /**
  3322. * Execute the next iteration. Must be called after the last iteration was finished.
  3323. */
  3324. AsyncLoop.prototype.executeNext = function () {
  3325. if (!this._done) {
  3326. if (this.index + 1 < this.iterations) {
  3327. ++this.index;
  3328. this._fn(this);
  3329. }
  3330. else {
  3331. this.breakLoop();
  3332. }
  3333. }
  3334. };
  3335. /**
  3336. * Break the loop and run the success callback.
  3337. */
  3338. AsyncLoop.prototype.breakLoop = function () {
  3339. this._done = true;
  3340. this._successCallback();
  3341. };
  3342. /**
  3343. * Helper function
  3344. */
  3345. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3346. if (offset === void 0) { offset = 0; }
  3347. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3348. loop.executeNext();
  3349. return loop;
  3350. };
  3351. /**
  3352. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3353. * @param iterations total number of iterations
  3354. * @param syncedIterations number of synchronous iterations in each async iteration.
  3355. * @param fn the function to call each iteration.
  3356. * @param callback a success call back that will be called when iterating stops.
  3357. * @param breakFunction a break condition (optional)
  3358. * @param timeout timeout settings for the setTimeout function. default - 0.
  3359. * @constructor
  3360. */
  3361. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3362. if (timeout === void 0) { timeout = 0; }
  3363. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3364. if (breakFunction && breakFunction())
  3365. loop.breakLoop();
  3366. else {
  3367. setTimeout(function () {
  3368. for (var i = 0; i < syncedIterations; ++i) {
  3369. var iteration = (loop.index * syncedIterations) + i;
  3370. if (iteration >= iterations)
  3371. break;
  3372. fn(iteration);
  3373. if (breakFunction && breakFunction()) {
  3374. loop.breakLoop();
  3375. break;
  3376. }
  3377. }
  3378. loop.executeNext();
  3379. }, timeout);
  3380. }
  3381. }, callback);
  3382. };
  3383. return AsyncLoop;
  3384. })();
  3385. BABYLON.AsyncLoop = AsyncLoop;
  3386. })(BABYLON || (BABYLON = {}));
  3387. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3388. (function (BABYLON) {
  3389. var _DepthCullingState = (function () {
  3390. function _DepthCullingState() {
  3391. this._isDepthTestDirty = false;
  3392. this._isDepthMaskDirty = false;
  3393. this._isDepthFuncDirty = false;
  3394. this._isCullFaceDirty = false;
  3395. this._isCullDirty = false;
  3396. }
  3397. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3398. get: function () {
  3399. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3400. },
  3401. enumerable: true,
  3402. configurable: true
  3403. });
  3404. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3405. get: function () {
  3406. return this._cullFace;
  3407. },
  3408. set: function (value) {
  3409. if (this._cullFace === value) {
  3410. return;
  3411. }
  3412. this._cullFace = value;
  3413. this._isCullFaceDirty = true;
  3414. },
  3415. enumerable: true,
  3416. configurable: true
  3417. });
  3418. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3419. get: function () {
  3420. return this._cull;
  3421. },
  3422. set: function (value) {
  3423. if (this._cull === value) {
  3424. return;
  3425. }
  3426. this._cull = value;
  3427. this._isCullDirty = true;
  3428. },
  3429. enumerable: true,
  3430. configurable: true
  3431. });
  3432. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3433. get: function () {
  3434. return this._depthFunc;
  3435. },
  3436. set: function (value) {
  3437. if (this._depthFunc === value) {
  3438. return;
  3439. }
  3440. this._depthFunc = value;
  3441. this._isDepthFuncDirty = true;
  3442. },
  3443. enumerable: true,
  3444. configurable: true
  3445. });
  3446. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3447. get: function () {
  3448. return this._depthMask;
  3449. },
  3450. set: function (value) {
  3451. if (this._depthMask === value) {
  3452. return;
  3453. }
  3454. this._depthMask = value;
  3455. this._isDepthMaskDirty = true;
  3456. },
  3457. enumerable: true,
  3458. configurable: true
  3459. });
  3460. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3461. get: function () {
  3462. return this._depthTest;
  3463. },
  3464. set: function (value) {
  3465. if (this._depthTest === value) {
  3466. return;
  3467. }
  3468. this._depthTest = value;
  3469. this._isDepthTestDirty = true;
  3470. },
  3471. enumerable: true,
  3472. configurable: true
  3473. });
  3474. _DepthCullingState.prototype.reset = function () {
  3475. this._depthMask = true;
  3476. this._depthTest = true;
  3477. this._depthFunc = null;
  3478. this._cull = null;
  3479. this._cullFace = null;
  3480. this._isDepthTestDirty = true;
  3481. this._isDepthMaskDirty = true;
  3482. this._isDepthFuncDirty = false;
  3483. this._isCullFaceDirty = false;
  3484. this._isCullDirty = false;
  3485. };
  3486. _DepthCullingState.prototype.apply = function (gl) {
  3487. if (!this.isDirty) {
  3488. return;
  3489. }
  3490. // Cull
  3491. if (this._isCullDirty) {
  3492. if (this.cull) {
  3493. gl.enable(gl.CULL_FACE);
  3494. }
  3495. else {
  3496. gl.disable(gl.CULL_FACE);
  3497. }
  3498. this._isCullDirty = false;
  3499. }
  3500. // Cull face
  3501. if (this._isCullFaceDirty) {
  3502. gl.cullFace(this.cullFace);
  3503. this._isCullFaceDirty = false;
  3504. }
  3505. // Depth mask
  3506. if (this._isDepthMaskDirty) {
  3507. gl.depthMask(this.depthMask);
  3508. this._isDepthMaskDirty = false;
  3509. }
  3510. // Depth test
  3511. if (this._isDepthTestDirty) {
  3512. if (this.depthTest) {
  3513. gl.enable(gl.DEPTH_TEST);
  3514. }
  3515. else {
  3516. gl.disable(gl.DEPTH_TEST);
  3517. }
  3518. this._isDepthTestDirty = false;
  3519. }
  3520. // Depth func
  3521. if (this._isDepthFuncDirty) {
  3522. gl.depthFunc(this.depthFunc);
  3523. this._isDepthFuncDirty = false;
  3524. }
  3525. };
  3526. return _DepthCullingState;
  3527. })();
  3528. BABYLON._DepthCullingState = _DepthCullingState;
  3529. var _AlphaState = (function () {
  3530. function _AlphaState() {
  3531. this._isAlphaBlendDirty = false;
  3532. this._isBlendFunctionParametersDirty = false;
  3533. this._alphaBlend = false;
  3534. this._blendFunctionParameters = new Array(4);
  3535. }
  3536. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3537. get: function () {
  3538. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3539. },
  3540. enumerable: true,
  3541. configurable: true
  3542. });
  3543. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3544. get: function () {
  3545. return this._alphaBlend;
  3546. },
  3547. set: function (value) {
  3548. if (this._alphaBlend === value) {
  3549. return;
  3550. }
  3551. this._alphaBlend = value;
  3552. this._isAlphaBlendDirty = true;
  3553. },
  3554. enumerable: true,
  3555. configurable: true
  3556. });
  3557. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3558. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3559. return;
  3560. }
  3561. this._blendFunctionParameters[0] = value0;
  3562. this._blendFunctionParameters[1] = value1;
  3563. this._blendFunctionParameters[2] = value2;
  3564. this._blendFunctionParameters[3] = value3;
  3565. this._isBlendFunctionParametersDirty = true;
  3566. };
  3567. _AlphaState.prototype.reset = function () {
  3568. this._alphaBlend = false;
  3569. this._blendFunctionParameters[0] = null;
  3570. this._blendFunctionParameters[1] = null;
  3571. this._blendFunctionParameters[2] = null;
  3572. this._blendFunctionParameters[3] = null;
  3573. this._isAlphaBlendDirty = true;
  3574. this._isBlendFunctionParametersDirty = false;
  3575. };
  3576. _AlphaState.prototype.apply = function (gl) {
  3577. if (!this.isDirty) {
  3578. return;
  3579. }
  3580. // Alpha blend
  3581. if (this._isAlphaBlendDirty) {
  3582. if (this._alphaBlend) {
  3583. gl.enable(gl.BLEND);
  3584. }
  3585. else {
  3586. gl.disable(gl.BLEND);
  3587. }
  3588. this._isAlphaBlendDirty = false;
  3589. }
  3590. // Alpha function
  3591. if (this._isBlendFunctionParametersDirty) {
  3592. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3593. this._isBlendFunctionParametersDirty = false;
  3594. }
  3595. };
  3596. return _AlphaState;
  3597. })();
  3598. BABYLON._AlphaState = _AlphaState;
  3599. var compileShader = function (gl, source, type, defines) {
  3600. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3601. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3602. gl.compileShader(shader);
  3603. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3604. throw new Error(gl.getShaderInfoLog(shader));
  3605. }
  3606. return shader;
  3607. };
  3608. var getWebGLTextureType = function (gl, type) {
  3609. var textureType = gl.UNSIGNED_BYTE;
  3610. if (type === Engine.TEXTURETYPE_FLOAT)
  3611. textureType = gl.FLOAT;
  3612. return textureType;
  3613. };
  3614. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3615. var magFilter = gl.NEAREST;
  3616. var minFilter = gl.NEAREST;
  3617. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3618. magFilter = gl.LINEAR;
  3619. if (generateMipMaps) {
  3620. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3621. }
  3622. else {
  3623. minFilter = gl.LINEAR;
  3624. }
  3625. }
  3626. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3627. magFilter = gl.LINEAR;
  3628. if (generateMipMaps) {
  3629. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3630. }
  3631. else {
  3632. minFilter = gl.LINEAR;
  3633. }
  3634. }
  3635. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3636. magFilter = gl.NEAREST;
  3637. if (generateMipMaps) {
  3638. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3639. }
  3640. else {
  3641. minFilter = gl.NEAREST;
  3642. }
  3643. }
  3644. return {
  3645. min: minFilter,
  3646. mag: magFilter
  3647. };
  3648. };
  3649. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3651. var engine = scene.getEngine();
  3652. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3653. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3654. gl.bindTexture(gl.TEXTURE_2D, texture);
  3655. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3656. processFunction(potWidth, potHeight);
  3657. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3658. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3659. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3660. if (!noMipmap && !isCompressed) {
  3661. gl.generateMipmap(gl.TEXTURE_2D);
  3662. }
  3663. gl.bindTexture(gl.TEXTURE_2D, null);
  3664. engine._activeTexturesCache = [];
  3665. texture._baseWidth = width;
  3666. texture._baseHeight = height;
  3667. texture._width = potWidth;
  3668. texture._height = potHeight;
  3669. texture.isReady = true;
  3670. texture.samplingMode = samplingMode;
  3671. scene._removePendingData(texture);
  3672. };
  3673. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3674. var onload = function () {
  3675. loadedImages[index] = img;
  3676. loadedImages._internalCount++;
  3677. scene._removePendingData(img);
  3678. if (loadedImages._internalCount === 6) {
  3679. onfinish(loadedImages);
  3680. }
  3681. };
  3682. var onerror = function () {
  3683. scene._removePendingData(img);
  3684. };
  3685. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3686. scene._addPendingData(img);
  3687. };
  3688. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3689. var loadedImages = [];
  3690. loadedImages._internalCount = 0;
  3691. for (var index = 0; index < 6; index++) {
  3692. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3693. }
  3694. };
  3695. var EngineCapabilities = (function () {
  3696. function EngineCapabilities() {
  3697. }
  3698. return EngineCapabilities;
  3699. })();
  3700. BABYLON.EngineCapabilities = EngineCapabilities;
  3701. /**
  3702. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3703. */
  3704. var Engine = (function () {
  3705. /**
  3706. * @constructor
  3707. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3708. * @param {boolean} [antialias] - enable antialias
  3709. * @param options - further options to be sent to the getContext function
  3710. */
  3711. function Engine(canvas, antialias, options) {
  3712. var _this = this;
  3713. // Public members
  3714. this.isFullscreen = false;
  3715. this.isPointerLock = false;
  3716. this.cullBackFaces = true;
  3717. this.renderEvenInBackground = true;
  3718. this.scenes = new Array();
  3719. this._windowIsBackground = false;
  3720. this._loadingDivBackgroundColor = "black";
  3721. this._drawCalls = 0;
  3722. this._renderingQueueLaunched = false;
  3723. this._activeRenderLoops = [];
  3724. // FPS
  3725. this.fpsRange = 60;
  3726. this.previousFramesDuration = [];
  3727. this.fps = 60;
  3728. this.deltaTime = 0;
  3729. // States
  3730. this._depthCullingState = new _DepthCullingState();
  3731. this._alphaState = new _AlphaState();
  3732. this._alphaMode = Engine.ALPHA_DISABLE;
  3733. // Cache
  3734. this._loadedTexturesCache = new Array();
  3735. this._activeTexturesCache = new Array();
  3736. this._compiledEffects = {};
  3737. this._uintIndicesCurrentlySet = false;
  3738. this._renderingCanvas = canvas;
  3739. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3740. options = options || {};
  3741. options.antialias = antialias;
  3742. try {
  3743. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3744. }
  3745. catch (e) {
  3746. throw new Error("WebGL not supported");
  3747. }
  3748. if (!this._gl) {
  3749. throw new Error("WebGL not supported");
  3750. }
  3751. this._onBlur = function () {
  3752. _this._windowIsBackground = true;
  3753. };
  3754. this._onFocus = function () {
  3755. _this._windowIsBackground = false;
  3756. };
  3757. window.addEventListener("blur", this._onBlur);
  3758. window.addEventListener("focus", this._onFocus);
  3759. // Textures
  3760. this._workingCanvas = document.createElement("canvas");
  3761. this._workingContext = this._workingCanvas.getContext("2d");
  3762. // Viewport
  3763. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3764. this.resize();
  3765. // Caps
  3766. this._caps = new EngineCapabilities();
  3767. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3768. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3769. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3770. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3771. // Infos
  3772. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3773. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3774. if (rendererInfo != null) {
  3775. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3776. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3777. }
  3778. if (!this._glVendor) {
  3779. this._glVendor = "Unknown vendor";
  3780. }
  3781. if (!this._glRenderer) {
  3782. this._glRenderer = "Unknown renderer";
  3783. }
  3784. // Extensions
  3785. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3786. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3787. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3788. 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');
  3789. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3790. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3791. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3792. // Depth buffer
  3793. this.setDepthBuffer(true);
  3794. this.setDepthFunctionToLessOrEqual();
  3795. this.setDepthWrite(true);
  3796. // Fullscreen
  3797. this._onFullscreenChange = function () {
  3798. if (document.fullscreen !== undefined) {
  3799. _this.isFullscreen = document.fullscreen;
  3800. }
  3801. else if (document.mozFullScreen !== undefined) {
  3802. _this.isFullscreen = document.mozFullScreen;
  3803. }
  3804. else if (document.webkitIsFullScreen !== undefined) {
  3805. _this.isFullscreen = document.webkitIsFullScreen;
  3806. }
  3807. else if (document.msIsFullScreen !== undefined) {
  3808. _this.isFullscreen = document.msIsFullScreen;
  3809. }
  3810. // Pointer lock
  3811. if (_this.isFullscreen && _this._pointerLockRequested) {
  3812. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3813. if (canvas.requestPointerLock) {
  3814. canvas.requestPointerLock();
  3815. }
  3816. }
  3817. };
  3818. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3819. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3820. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3821. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3822. // Pointer lock
  3823. this._onPointerLockChange = function () {
  3824. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3825. };
  3826. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3827. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3828. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3829. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3830. if (!Engine.audioEngine) {
  3831. Engine.audioEngine = new BABYLON.AudioEngine();
  3832. }
  3833. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3834. }
  3835. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3836. get: function () {
  3837. return Engine._ALPHA_DISABLE;
  3838. },
  3839. enumerable: true,
  3840. configurable: true
  3841. });
  3842. Object.defineProperty(Engine, "ALPHA_ADD", {
  3843. get: function () {
  3844. return Engine._ALPHA_ADD;
  3845. },
  3846. enumerable: true,
  3847. configurable: true
  3848. });
  3849. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3850. get: function () {
  3851. return Engine._ALPHA_COMBINE;
  3852. },
  3853. enumerable: true,
  3854. configurable: true
  3855. });
  3856. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3857. get: function () {
  3858. return Engine._DELAYLOADSTATE_NONE;
  3859. },
  3860. enumerable: true,
  3861. configurable: true
  3862. });
  3863. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3864. get: function () {
  3865. return Engine._DELAYLOADSTATE_LOADED;
  3866. },
  3867. enumerable: true,
  3868. configurable: true
  3869. });
  3870. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3871. get: function () {
  3872. return Engine._DELAYLOADSTATE_LOADING;
  3873. },
  3874. enumerable: true,
  3875. configurable: true
  3876. });
  3877. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3878. get: function () {
  3879. return Engine._DELAYLOADSTATE_NOTLOADED;
  3880. },
  3881. enumerable: true,
  3882. configurable: true
  3883. });
  3884. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3885. get: function () {
  3886. return Engine._TEXTUREFORMAT_ALPHA;
  3887. },
  3888. enumerable: true,
  3889. configurable: true
  3890. });
  3891. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3892. get: function () {
  3893. return Engine._TEXTUREFORMAT_LUMINANCE;
  3894. },
  3895. enumerable: true,
  3896. configurable: true
  3897. });
  3898. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3899. get: function () {
  3900. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3901. },
  3902. enumerable: true,
  3903. configurable: true
  3904. });
  3905. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3906. get: function () {
  3907. return Engine._TEXTUREFORMAT_RGB;
  3908. },
  3909. enumerable: true,
  3910. configurable: true
  3911. });
  3912. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3913. get: function () {
  3914. return Engine._TEXTUREFORMAT_RGBA;
  3915. },
  3916. enumerable: true,
  3917. configurable: true
  3918. });
  3919. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3920. get: function () {
  3921. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3922. },
  3923. enumerable: true,
  3924. configurable: true
  3925. });
  3926. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3927. get: function () {
  3928. return Engine._TEXTURETYPE_FLOAT;
  3929. },
  3930. enumerable: true,
  3931. configurable: true
  3932. });
  3933. Object.defineProperty(Engine, "Version", {
  3934. get: function () {
  3935. return "2.1.0 alpha";
  3936. },
  3937. enumerable: true,
  3938. configurable: true
  3939. });
  3940. Engine.prototype.getGlInfo = function () {
  3941. return {
  3942. vendor: this._glVendor,
  3943. renderer: this._glRenderer,
  3944. version: this._glVersion
  3945. };
  3946. };
  3947. Engine.prototype.getAspectRatio = function (camera) {
  3948. var viewport = camera.viewport;
  3949. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3950. };
  3951. Engine.prototype.getRenderWidth = function () {
  3952. if (this._currentRenderTarget) {
  3953. return this._currentRenderTarget._width;
  3954. }
  3955. return this._renderingCanvas.width;
  3956. };
  3957. Engine.prototype.getRenderHeight = function () {
  3958. if (this._currentRenderTarget) {
  3959. return this._currentRenderTarget._height;
  3960. }
  3961. return this._renderingCanvas.height;
  3962. };
  3963. Engine.prototype.getRenderingCanvas = function () {
  3964. return this._renderingCanvas;
  3965. };
  3966. Engine.prototype.getRenderingCanvasClientRect = function () {
  3967. return this._renderingCanvas.getBoundingClientRect();
  3968. };
  3969. Engine.prototype.setHardwareScalingLevel = function (level) {
  3970. this._hardwareScalingLevel = level;
  3971. this.resize();
  3972. };
  3973. Engine.prototype.getHardwareScalingLevel = function () {
  3974. return this._hardwareScalingLevel;
  3975. };
  3976. Engine.prototype.getLoadedTexturesCache = function () {
  3977. return this._loadedTexturesCache;
  3978. };
  3979. Engine.prototype.getCaps = function () {
  3980. return this._caps;
  3981. };
  3982. Object.defineProperty(Engine.prototype, "drawCalls", {
  3983. get: function () {
  3984. return this._drawCalls;
  3985. },
  3986. enumerable: true,
  3987. configurable: true
  3988. });
  3989. // Methods
  3990. Engine.prototype.resetDrawCalls = function () {
  3991. this._drawCalls = 0;
  3992. };
  3993. Engine.prototype.setDepthFunctionToGreater = function () {
  3994. this._depthCullingState.depthFunc = this._gl.GREATER;
  3995. };
  3996. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3997. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3998. };
  3999. Engine.prototype.setDepthFunctionToLess = function () {
  4000. this._depthCullingState.depthFunc = this._gl.LESS;
  4001. };
  4002. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4003. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4004. };
  4005. /**
  4006. * stop executing a render loop function and remove it from the execution array
  4007. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4008. */
  4009. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4010. if (!renderFunction) {
  4011. this._activeRenderLoops = [];
  4012. return;
  4013. }
  4014. var index = this._activeRenderLoops.indexOf(renderFunction);
  4015. if (index >= 0) {
  4016. this._activeRenderLoops.splice(index, 1);
  4017. }
  4018. };
  4019. Engine.prototype._renderLoop = function () {
  4020. var _this = this;
  4021. var shouldRender = true;
  4022. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4023. shouldRender = false;
  4024. }
  4025. if (shouldRender) {
  4026. // Start new frame
  4027. this.beginFrame();
  4028. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4029. var renderFunction = this._activeRenderLoops[index];
  4030. renderFunction();
  4031. }
  4032. // Present
  4033. this.endFrame();
  4034. }
  4035. if (this._activeRenderLoops.length > 0) {
  4036. // Register new frame
  4037. BABYLON.Tools.QueueNewFrame(function () {
  4038. _this._renderLoop();
  4039. });
  4040. }
  4041. else {
  4042. this._renderingQueueLaunched = false;
  4043. }
  4044. };
  4045. /**
  4046. * Register and execute a render loop. The engine can have more than one render function.
  4047. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4048. * @example
  4049. * engine.runRenderLoop(function () {
  4050. * scene.render()
  4051. * })
  4052. */
  4053. Engine.prototype.runRenderLoop = function (renderFunction) {
  4054. var _this = this;
  4055. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4056. return;
  4057. }
  4058. this._activeRenderLoops.push(renderFunction);
  4059. if (!this._renderingQueueLaunched) {
  4060. this._renderingQueueLaunched = true;
  4061. BABYLON.Tools.QueueNewFrame(function () {
  4062. _this._renderLoop();
  4063. });
  4064. }
  4065. };
  4066. /**
  4067. * Toggle full screen mode.
  4068. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4069. */
  4070. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4071. if (this.isFullscreen) {
  4072. BABYLON.Tools.ExitFullscreen();
  4073. }
  4074. else {
  4075. this._pointerLockRequested = requestPointerLock;
  4076. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4077. }
  4078. };
  4079. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4080. this.applyStates();
  4081. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4082. if (this._depthCullingState.depthMask) {
  4083. this._gl.clearDepth(1.0);
  4084. }
  4085. var mode = 0;
  4086. if (backBuffer)
  4087. mode |= this._gl.COLOR_BUFFER_BIT;
  4088. if (depthStencil && this._depthCullingState.depthMask)
  4089. mode |= this._gl.DEPTH_BUFFER_BIT;
  4090. this._gl.clear(mode);
  4091. };
  4092. /**
  4093. * Set the WebGL's viewport
  4094. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4095. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4096. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4097. */
  4098. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4099. var width = requiredWidth || this._renderingCanvas.width;
  4100. var height = requiredHeight || this._renderingCanvas.height;
  4101. var x = viewport.x || 0;
  4102. var y = viewport.y || 0;
  4103. this._cachedViewport = viewport;
  4104. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4105. };
  4106. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4107. this._cachedViewport = null;
  4108. this._gl.viewport(x, y, width, height);
  4109. };
  4110. Engine.prototype.beginFrame = function () {
  4111. this._measureFps();
  4112. };
  4113. Engine.prototype.endFrame = function () {
  4114. //this.flushFramebuffer();
  4115. };
  4116. /**
  4117. * resize the view according to the canvas' size.
  4118. * @example
  4119. * window.addEventListener("resize", function () {
  4120. * engine.resize();
  4121. * });
  4122. */
  4123. Engine.prototype.resize = function () {
  4124. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4125. };
  4126. /**
  4127. * force a specific size of the canvas
  4128. * @param {number} width - the new canvas' width
  4129. * @param {number} height - the new canvas' height
  4130. */
  4131. Engine.prototype.setSize = function (width, height) {
  4132. this._renderingCanvas.width = width;
  4133. this._renderingCanvas.height = height;
  4134. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4135. };
  4136. Engine.prototype.bindFramebuffer = function (texture) {
  4137. this._currentRenderTarget = texture;
  4138. var gl = this._gl;
  4139. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4140. this._gl.viewport(0, 0, texture._width, texture._height);
  4141. this.wipeCaches();
  4142. };
  4143. Engine.prototype.unBindFramebuffer = function (texture) {
  4144. this._currentRenderTarget = null;
  4145. if (texture.generateMipMaps) {
  4146. var gl = this._gl;
  4147. gl.bindTexture(gl.TEXTURE_2D, texture);
  4148. gl.generateMipmap(gl.TEXTURE_2D);
  4149. gl.bindTexture(gl.TEXTURE_2D, null);
  4150. }
  4151. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4152. };
  4153. Engine.prototype.flushFramebuffer = function () {
  4154. this._gl.flush();
  4155. };
  4156. Engine.prototype.restoreDefaultFramebuffer = function () {
  4157. this._currentRenderTarget = null;
  4158. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4159. this.setViewport(this._cachedViewport);
  4160. this.wipeCaches();
  4161. };
  4162. // VBOs
  4163. Engine.prototype._resetVertexBufferBinding = function () {
  4164. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4165. this._cachedVertexBuffers = null;
  4166. };
  4167. Engine.prototype.createVertexBuffer = function (vertices) {
  4168. var vbo = this._gl.createBuffer();
  4169. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4170. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4171. this._resetVertexBufferBinding();
  4172. vbo.references = 1;
  4173. return vbo;
  4174. };
  4175. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4176. var vbo = this._gl.createBuffer();
  4177. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4178. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4179. this._resetVertexBufferBinding();
  4180. vbo.references = 1;
  4181. return vbo;
  4182. };
  4183. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4184. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4185. if (offset === undefined) {
  4186. offset = 0;
  4187. }
  4188. if (vertices instanceof Float32Array) {
  4189. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4190. }
  4191. else {
  4192. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4193. }
  4194. this._resetVertexBufferBinding();
  4195. };
  4196. Engine.prototype._resetIndexBufferBinding = function () {
  4197. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4198. this._cachedIndexBuffer = null;
  4199. };
  4200. Engine.prototype.createIndexBuffer = function (indices) {
  4201. var vbo = this._gl.createBuffer();
  4202. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4203. // Check for 32 bits indices
  4204. var arrayBuffer;
  4205. var need32Bits = false;
  4206. if (this._caps.uintIndices) {
  4207. for (var index = 0; index < indices.length; index++) {
  4208. if (indices[index] > 65535) {
  4209. need32Bits = true;
  4210. break;
  4211. }
  4212. }
  4213. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4214. }
  4215. else {
  4216. arrayBuffer = new Uint16Array(indices);
  4217. }
  4218. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4219. this._resetIndexBufferBinding();
  4220. vbo.references = 1;
  4221. vbo.is32Bits = need32Bits;
  4222. return vbo;
  4223. };
  4224. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4225. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4226. this._cachedVertexBuffers = vertexBuffer;
  4227. this._cachedEffectForVertexBuffers = effect;
  4228. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4229. var offset = 0;
  4230. for (var index = 0; index < vertexDeclaration.length; index++) {
  4231. var order = effect.getAttributeLocation(index);
  4232. if (order >= 0) {
  4233. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4234. }
  4235. offset += vertexDeclaration[index] * 4;
  4236. }
  4237. }
  4238. if (this._cachedIndexBuffer !== indexBuffer) {
  4239. this._cachedIndexBuffer = indexBuffer;
  4240. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4241. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4242. }
  4243. };
  4244. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4245. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4246. this._cachedVertexBuffers = vertexBuffers;
  4247. this._cachedEffectForVertexBuffers = effect;
  4248. var attributes = effect.getAttributesNames();
  4249. for (var index = 0; index < attributes.length; index++) {
  4250. var order = effect.getAttributeLocation(index);
  4251. if (order >= 0) {
  4252. var vertexBuffer = vertexBuffers[attributes[index]];
  4253. if (!vertexBuffer) {
  4254. continue;
  4255. }
  4256. var stride = vertexBuffer.getStrideSize();
  4257. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4258. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4259. }
  4260. }
  4261. }
  4262. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4263. this._cachedIndexBuffer = indexBuffer;
  4264. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4265. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4266. }
  4267. };
  4268. Engine.prototype._releaseBuffer = function (buffer) {
  4269. buffer.references--;
  4270. if (buffer.references === 0) {
  4271. this._gl.deleteBuffer(buffer);
  4272. return true;
  4273. }
  4274. return false;
  4275. };
  4276. Engine.prototype.createInstancesBuffer = function (capacity) {
  4277. var buffer = this._gl.createBuffer();
  4278. buffer.capacity = capacity;
  4279. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4280. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4281. return buffer;
  4282. };
  4283. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4284. this._gl.deleteBuffer(buffer);
  4285. };
  4286. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4287. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4288. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4289. for (var index = 0; index < 4; index++) {
  4290. var offsetLocation = offsetLocations[index];
  4291. this._gl.enableVertexAttribArray(offsetLocation);
  4292. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4293. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4294. }
  4295. };
  4296. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4297. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4298. for (var index = 0; index < 4; index++) {
  4299. var offsetLocation = offsetLocations[index];
  4300. this._gl.disableVertexAttribArray(offsetLocation);
  4301. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4302. }
  4303. };
  4304. Engine.prototype.applyStates = function () {
  4305. this._depthCullingState.apply(this._gl);
  4306. this._alphaState.apply(this._gl);
  4307. };
  4308. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4309. // Apply states
  4310. this.applyStates();
  4311. this._drawCalls++;
  4312. // Render
  4313. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4314. if (instancesCount) {
  4315. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4316. return;
  4317. }
  4318. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4319. };
  4320. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4321. // Apply states
  4322. this.applyStates();
  4323. this._drawCalls++;
  4324. if (instancesCount) {
  4325. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4326. return;
  4327. }
  4328. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4329. };
  4330. // Shaders
  4331. Engine.prototype._releaseEffect = function (effect) {
  4332. if (this._compiledEffects[effect._key]) {
  4333. delete this._compiledEffects[effect._key];
  4334. if (effect.getProgram()) {
  4335. this._gl.deleteProgram(effect.getProgram());
  4336. }
  4337. }
  4338. };
  4339. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4340. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4341. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4342. var name = vertex + "+" + fragment + "@" + defines;
  4343. if (this._compiledEffects[name]) {
  4344. return this._compiledEffects[name];
  4345. }
  4346. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4347. effect._key = name;
  4348. this._compiledEffects[name] = effect;
  4349. return effect;
  4350. };
  4351. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4352. if (uniformsNames === void 0) { uniformsNames = []; }
  4353. if (samplers === void 0) { samplers = []; }
  4354. if (defines === void 0) { defines = ""; }
  4355. return this.createEffect({
  4356. vertex: "particles",
  4357. fragmentElement: fragmentName
  4358. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4359. };
  4360. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4361. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4362. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4363. var shaderProgram = this._gl.createProgram();
  4364. this._gl.attachShader(shaderProgram, vertexShader);
  4365. this._gl.attachShader(shaderProgram, fragmentShader);
  4366. this._gl.linkProgram(shaderProgram);
  4367. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4368. if (!linked) {
  4369. var error = this._gl.getProgramInfoLog(shaderProgram);
  4370. if (error) {
  4371. throw new Error(error);
  4372. }
  4373. }
  4374. this._gl.deleteShader(vertexShader);
  4375. this._gl.deleteShader(fragmentShader);
  4376. return shaderProgram;
  4377. };
  4378. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4379. var results = [];
  4380. for (var index = 0; index < uniformsNames.length; index++) {
  4381. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4382. }
  4383. return results;
  4384. };
  4385. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4386. var results = [];
  4387. for (var index = 0; index < attributesNames.length; index++) {
  4388. try {
  4389. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4390. }
  4391. catch (e) {
  4392. results.push(-1);
  4393. }
  4394. }
  4395. return results;
  4396. };
  4397. Engine.prototype.enableEffect = function (effect) {
  4398. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4399. if (effect && effect.onBind) {
  4400. effect.onBind(effect);
  4401. }
  4402. return;
  4403. }
  4404. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4405. // Use program
  4406. this._gl.useProgram(effect.getProgram());
  4407. for (var i in this._vertexAttribArrays) {
  4408. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4409. continue;
  4410. }
  4411. this._vertexAttribArrays[i] = false;
  4412. this._gl.disableVertexAttribArray(i);
  4413. }
  4414. var attributesCount = effect.getAttributesCount();
  4415. for (var index = 0; index < attributesCount; index++) {
  4416. // Attributes
  4417. var order = effect.getAttributeLocation(index);
  4418. if (order >= 0) {
  4419. this._vertexAttribArrays[order] = true;
  4420. this._gl.enableVertexAttribArray(order);
  4421. }
  4422. }
  4423. this._currentEffect = effect;
  4424. if (effect.onBind) {
  4425. effect.onBind(effect);
  4426. }
  4427. };
  4428. Engine.prototype.setArray = function (uniform, array) {
  4429. if (!uniform)
  4430. return;
  4431. this._gl.uniform1fv(uniform, array);
  4432. };
  4433. Engine.prototype.setArray2 = function (uniform, array) {
  4434. if (!uniform || array.length % 2 !== 0)
  4435. return;
  4436. this._gl.uniform2fv(uniform, array);
  4437. };
  4438. Engine.prototype.setArray3 = function (uniform, array) {
  4439. if (!uniform || array.length % 3 !== 0)
  4440. return;
  4441. this._gl.uniform3fv(uniform, array);
  4442. };
  4443. Engine.prototype.setArray4 = function (uniform, array) {
  4444. if (!uniform || array.length % 4 !== 0)
  4445. return;
  4446. this._gl.uniform4fv(uniform, array);
  4447. };
  4448. Engine.prototype.setMatrices = function (uniform, matrices) {
  4449. if (!uniform)
  4450. return;
  4451. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4452. };
  4453. Engine.prototype.setMatrix = function (uniform, matrix) {
  4454. if (!uniform)
  4455. return;
  4456. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4457. };
  4458. Engine.prototype.setFloat = function (uniform, value) {
  4459. if (!uniform)
  4460. return;
  4461. this._gl.uniform1f(uniform, value);
  4462. };
  4463. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4464. if (!uniform)
  4465. return;
  4466. this._gl.uniform2f(uniform, x, y);
  4467. };
  4468. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4469. if (!uniform)
  4470. return;
  4471. this._gl.uniform3f(uniform, x, y, z);
  4472. };
  4473. Engine.prototype.setBool = function (uniform, bool) {
  4474. if (!uniform)
  4475. return;
  4476. this._gl.uniform1i(uniform, bool);
  4477. };
  4478. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4479. if (!uniform)
  4480. return;
  4481. this._gl.uniform4f(uniform, x, y, z, w);
  4482. };
  4483. Engine.prototype.setColor3 = function (uniform, color3) {
  4484. if (!uniform)
  4485. return;
  4486. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4487. };
  4488. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4489. if (!uniform)
  4490. return;
  4491. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4492. };
  4493. // States
  4494. Engine.prototype.setState = function (culling, force) {
  4495. // Culling
  4496. if (this._depthCullingState.cull !== culling || force) {
  4497. if (culling) {
  4498. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4499. this._depthCullingState.cull = true;
  4500. }
  4501. else {
  4502. this._depthCullingState.cull = false;
  4503. }
  4504. }
  4505. };
  4506. Engine.prototype.setDepthBuffer = function (enable) {
  4507. this._depthCullingState.depthTest = enable;
  4508. };
  4509. Engine.prototype.getDepthWrite = function () {
  4510. return this._depthCullingState.depthMask;
  4511. };
  4512. Engine.prototype.setDepthWrite = function (enable) {
  4513. this._depthCullingState.depthMask = enable;
  4514. };
  4515. Engine.prototype.setColorWrite = function (enable) {
  4516. this._gl.colorMask(enable, enable, enable, enable);
  4517. };
  4518. Engine.prototype.setAlphaMode = function (mode) {
  4519. switch (mode) {
  4520. case Engine.ALPHA_DISABLE:
  4521. this.setDepthWrite(true);
  4522. this._alphaState.alphaBlend = false;
  4523. break;
  4524. case Engine.ALPHA_COMBINE:
  4525. this.setDepthWrite(false);
  4526. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4527. this._alphaState.alphaBlend = true;
  4528. break;
  4529. case Engine.ALPHA_ADD:
  4530. this.setDepthWrite(false);
  4531. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4532. this._alphaState.alphaBlend = true;
  4533. break;
  4534. }
  4535. this._alphaMode = mode;
  4536. };
  4537. Engine.prototype.getAlphaMode = function () {
  4538. return this._alphaMode;
  4539. };
  4540. Engine.prototype.setAlphaTesting = function (enable) {
  4541. this._alphaTest = enable;
  4542. };
  4543. Engine.prototype.getAlphaTesting = function () {
  4544. return this._alphaTest;
  4545. };
  4546. // Textures
  4547. Engine.prototype.wipeCaches = function () {
  4548. this._activeTexturesCache = [];
  4549. this._currentEffect = null;
  4550. this._depthCullingState.reset();
  4551. this._alphaState.reset();
  4552. this._cachedVertexBuffers = null;
  4553. this._cachedIndexBuffer = null;
  4554. this._cachedEffectForVertexBuffers = null;
  4555. };
  4556. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4557. var gl = this._gl;
  4558. gl.bindTexture(gl.TEXTURE_2D, texture);
  4559. var magFilter = gl.NEAREST;
  4560. var minFilter = gl.NEAREST;
  4561. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4562. magFilter = gl.LINEAR;
  4563. minFilter = gl.LINEAR;
  4564. }
  4565. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4566. magFilter = gl.LINEAR;
  4567. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4568. }
  4569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4570. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4571. gl.bindTexture(gl.TEXTURE_2D, null);
  4572. texture.samplingMode = samplingMode;
  4573. };
  4574. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4575. var _this = this;
  4576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4577. if (onLoad === void 0) { onLoad = null; }
  4578. if (onError === void 0) { onError = null; }
  4579. if (buffer === void 0) { buffer = null; }
  4580. var texture = this._gl.createTexture();
  4581. var extension;
  4582. var fromData = false;
  4583. if (url.substr(0, 5) === "data:") {
  4584. fromData = true;
  4585. }
  4586. if (!fromData)
  4587. extension = url.substr(url.length - 4, 4).toLowerCase();
  4588. else {
  4589. var oldUrl = url;
  4590. fromData = oldUrl.split(':');
  4591. url = oldUrl;
  4592. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4593. }
  4594. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4595. var isTGA = (extension === ".tga");
  4596. scene._addPendingData(texture);
  4597. texture.url = url;
  4598. texture.noMipmap = noMipmap;
  4599. texture.references = 1;
  4600. this._loadedTexturesCache.push(texture);
  4601. var onerror = function () {
  4602. scene._removePendingData(texture);
  4603. if (onError) {
  4604. onError();
  4605. }
  4606. };
  4607. if (isTGA) {
  4608. var callback = function (arrayBuffer) {
  4609. var data = new Uint8Array(arrayBuffer);
  4610. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4611. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4612. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4613. if (onLoad) {
  4614. onLoad();
  4615. }
  4616. }, samplingMode);
  4617. };
  4618. if (!(fromData instanceof Array))
  4619. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4620. callback(arrayBuffer);
  4621. }, onerror, scene.database, true);
  4622. else
  4623. callback(buffer);
  4624. }
  4625. else if (isDDS) {
  4626. callback = function (data) {
  4627. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4628. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4629. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4630. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4631. if (onLoad) {
  4632. onLoad();
  4633. }
  4634. }, samplingMode);
  4635. };
  4636. if (!(fromData instanceof Array))
  4637. BABYLON.Tools.LoadFile(url, function (data) {
  4638. callback(data);
  4639. }, onerror, scene.database, true);
  4640. else
  4641. callback(buffer);
  4642. }
  4643. else {
  4644. var onload = function (img) {
  4645. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4646. var isPot = (img.width === potWidth && img.height === potHeight);
  4647. if (!isPot) {
  4648. _this._workingCanvas.width = potWidth;
  4649. _this._workingCanvas.height = potHeight;
  4650. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4651. _this._workingContext.imageSmoothingEnabled = false;
  4652. _this._workingContext.mozImageSmoothingEnabled = false;
  4653. _this._workingContext.oImageSmoothingEnabled = false;
  4654. _this._workingContext.webkitImageSmoothingEnabled = false;
  4655. _this._workingContext.msImageSmoothingEnabled = false;
  4656. }
  4657. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4658. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4659. _this._workingContext.imageSmoothingEnabled = true;
  4660. _this._workingContext.mozImageSmoothingEnabled = true;
  4661. _this._workingContext.oImageSmoothingEnabled = true;
  4662. _this._workingContext.webkitImageSmoothingEnabled = true;
  4663. _this._workingContext.msImageSmoothingEnabled = true;
  4664. }
  4665. }
  4666. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4667. if (onLoad) {
  4668. onLoad();
  4669. }
  4670. }, samplingMode);
  4671. };
  4672. if (!(fromData instanceof Array))
  4673. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4674. else
  4675. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4676. }
  4677. return texture;
  4678. };
  4679. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4680. var texture = this._gl.createTexture();
  4681. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4682. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4683. // Format
  4684. var internalFormat = this._gl.RGBA;
  4685. switch (format) {
  4686. case Engine.TEXTUREFORMAT_ALPHA:
  4687. internalFormat = this._gl.ALPHA;
  4688. break;
  4689. case Engine.TEXTUREFORMAT_LUMINANCE:
  4690. internalFormat = this._gl.LUMINANCE;
  4691. break;
  4692. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4693. internalFormat = this._gl.LUMINANCE_ALPHA;
  4694. break;
  4695. case Engine.TEXTUREFORMAT_RGB:
  4696. internalFormat = this._gl.RGB;
  4697. break;
  4698. case Engine.TEXTUREFORMAT_RGBA:
  4699. internalFormat = this._gl.RGBA;
  4700. break;
  4701. }
  4702. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4703. if (generateMipMaps) {
  4704. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4705. }
  4706. // Filters
  4707. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4708. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4710. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4711. this._activeTexturesCache = [];
  4712. texture._baseWidth = width;
  4713. texture._baseHeight = height;
  4714. texture._width = width;
  4715. texture._height = height;
  4716. texture.isReady = true;
  4717. texture.references = 1;
  4718. texture.samplingMode = samplingMode;
  4719. this._loadedTexturesCache.push(texture);
  4720. return texture;
  4721. };
  4722. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4723. var texture = this._gl.createTexture();
  4724. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4725. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4726. this._activeTexturesCache = [];
  4727. texture._baseWidth = width;
  4728. texture._baseHeight = height;
  4729. texture._width = width;
  4730. texture._height = height;
  4731. texture.isReady = false;
  4732. texture.generateMipMaps = generateMipMaps;
  4733. texture.references = 1;
  4734. texture.samplingMode = samplingMode;
  4735. this.updateTextureSamplingMode(samplingMode, texture);
  4736. this._loadedTexturesCache.push(texture);
  4737. return texture;
  4738. };
  4739. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  4740. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  4741. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4742. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4743. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4744. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4745. };
  4746. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4747. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4748. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4749. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4750. if (texture.generateMipMaps) {
  4751. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4752. }
  4753. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4754. this._activeTexturesCache = [];
  4755. texture.isReady = true;
  4756. };
  4757. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4758. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4759. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4760. // Scale the video if it is a NPOT using the current working canvas
  4761. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4762. if (!texture._workingCanvas) {
  4763. texture._workingCanvas = document.createElement("canvas");
  4764. texture._workingContext = texture._workingCanvas.getContext("2d");
  4765. texture._workingCanvas.width = texture._width;
  4766. texture._workingCanvas.height = texture._height;
  4767. }
  4768. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4769. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4770. }
  4771. else {
  4772. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4773. }
  4774. if (texture.generateMipMaps) {
  4775. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4776. }
  4777. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4778. this._activeTexturesCache = [];
  4779. texture.isReady = true;
  4780. };
  4781. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4782. // old version had a "generateMipMaps" arg instead of options.
  4783. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4784. // in the same way, generateDepthBuffer is defaulted to true
  4785. var generateMipMaps = false;
  4786. var generateDepthBuffer = true;
  4787. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4788. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4789. if (options !== undefined) {
  4790. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4791. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4792. type = options.type === undefined ? type : options.type;
  4793. if (options.samplingMode !== undefined) {
  4794. samplingMode = options.samplingMode;
  4795. }
  4796. if (type === Engine.TEXTURETYPE_FLOAT) {
  4797. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4798. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4799. }
  4800. }
  4801. var gl = this._gl;
  4802. var texture = gl.createTexture();
  4803. gl.bindTexture(gl.TEXTURE_2D, texture);
  4804. var width = size.width || size;
  4805. var height = size.height || size;
  4806. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4807. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4808. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4809. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4810. }
  4811. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4814. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4815. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4816. var depthBuffer;
  4817. // Create the depth buffer
  4818. if (generateDepthBuffer) {
  4819. depthBuffer = gl.createRenderbuffer();
  4820. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4821. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4822. }
  4823. // Create the framebuffer
  4824. var framebuffer = gl.createFramebuffer();
  4825. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4826. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4827. if (generateDepthBuffer) {
  4828. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4829. }
  4830. // Unbind
  4831. gl.bindTexture(gl.TEXTURE_2D, null);
  4832. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4833. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4834. texture._framebuffer = framebuffer;
  4835. if (generateDepthBuffer) {
  4836. texture._depthBuffer = depthBuffer;
  4837. }
  4838. texture._width = width;
  4839. texture._height = height;
  4840. texture.isReady = true;
  4841. texture.generateMipMaps = generateMipMaps;
  4842. texture.references = 1;
  4843. texture.samplingMode = samplingMode;
  4844. this._activeTexturesCache = [];
  4845. this._loadedTexturesCache.push(texture);
  4846. return texture;
  4847. };
  4848. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4849. var _this = this;
  4850. var gl = this._gl;
  4851. var texture = gl.createTexture();
  4852. texture.isCube = true;
  4853. texture.url = rootUrl;
  4854. texture.references = 1;
  4855. this._loadedTexturesCache.push(texture);
  4856. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4857. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4858. if (isDDS) {
  4859. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4860. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4861. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4862. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4863. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4864. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4865. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4866. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4867. }
  4868. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4872. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4873. _this._activeTexturesCache = [];
  4874. texture._width = info.width;
  4875. texture._height = info.height;
  4876. texture.isReady = true;
  4877. }, null, null, true);
  4878. }
  4879. else {
  4880. cascadeLoad(rootUrl, scene, function (imgs) {
  4881. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4882. var height = width;
  4883. _this._workingCanvas.width = width;
  4884. _this._workingCanvas.height = height;
  4885. var faces = [
  4886. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4887. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4888. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4889. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4890. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4891. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4892. ];
  4893. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4894. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4895. for (var index = 0; index < faces.length; index++) {
  4896. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4897. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4898. }
  4899. if (!noMipmap) {
  4900. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4901. }
  4902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4904. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4906. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4907. _this._activeTexturesCache = [];
  4908. texture._width = width;
  4909. texture._height = height;
  4910. texture.isReady = true;
  4911. }, extensions);
  4912. }
  4913. return texture;
  4914. };
  4915. Engine.prototype._releaseTexture = function (texture) {
  4916. var gl = this._gl;
  4917. if (texture._framebuffer) {
  4918. gl.deleteFramebuffer(texture._framebuffer);
  4919. }
  4920. if (texture._depthBuffer) {
  4921. gl.deleteRenderbuffer(texture._depthBuffer);
  4922. }
  4923. gl.deleteTexture(texture);
  4924. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4925. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4926. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4927. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4928. this._activeTexturesCache[channel] = null;
  4929. }
  4930. var index = this._loadedTexturesCache.indexOf(texture);
  4931. if (index !== -1) {
  4932. this._loadedTexturesCache.splice(index, 1);
  4933. }
  4934. };
  4935. Engine.prototype.bindSamplers = function (effect) {
  4936. this._gl.useProgram(effect.getProgram());
  4937. var samplers = effect.getSamplers();
  4938. for (var index = 0; index < samplers.length; index++) {
  4939. var uniform = effect.getUniform(samplers[index]);
  4940. this._gl.uniform1i(uniform, index);
  4941. }
  4942. this._currentEffect = null;
  4943. };
  4944. Engine.prototype._bindTexture = function (channel, texture) {
  4945. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4946. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4947. this._activeTexturesCache[channel] = null;
  4948. };
  4949. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4950. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4951. };
  4952. Engine.prototype.setTexture = function (channel, texture) {
  4953. if (channel < 0) {
  4954. return;
  4955. }
  4956. // Not ready?
  4957. if (!texture || !texture.isReady()) {
  4958. if (this._activeTexturesCache[channel] != null) {
  4959. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4960. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4961. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4962. this._activeTexturesCache[channel] = null;
  4963. }
  4964. return;
  4965. }
  4966. // Video
  4967. if (texture instanceof BABYLON.VideoTexture) {
  4968. if (texture.update()) {
  4969. this._activeTexturesCache[channel] = null;
  4970. }
  4971. }
  4972. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4973. texture.delayLoad();
  4974. return;
  4975. }
  4976. if (this._activeTexturesCache[channel] === texture) {
  4977. return;
  4978. }
  4979. this._activeTexturesCache[channel] = texture;
  4980. var internalTexture = texture.getInternalTexture();
  4981. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4982. if (internalTexture.isCube) {
  4983. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4984. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4985. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4986. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4987. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4988. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4989. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4990. }
  4991. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4992. }
  4993. else {
  4994. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4995. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4996. internalTexture._cachedWrapU = texture.wrapU;
  4997. switch (texture.wrapU) {
  4998. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4999. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5000. break;
  5001. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5002. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5003. break;
  5004. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5005. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5006. break;
  5007. }
  5008. }
  5009. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5010. internalTexture._cachedWrapV = texture.wrapV;
  5011. switch (texture.wrapV) {
  5012. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5013. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5014. break;
  5015. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5016. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5017. break;
  5018. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5019. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5020. break;
  5021. }
  5022. }
  5023. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5024. }
  5025. };
  5026. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5027. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5028. var value = texture.anisotropicFilteringLevel;
  5029. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5030. value = 1;
  5031. }
  5032. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5033. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5034. texture._cachedAnisotropicFilteringLevel = value;
  5035. }
  5036. };
  5037. Engine.prototype.readPixels = function (x, y, width, height) {
  5038. var data = new Uint8Array(height * width * 4);
  5039. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5040. return data;
  5041. };
  5042. // Dispose
  5043. Engine.prototype.dispose = function () {
  5044. this.hideLoadingUI();
  5045. this.stopRenderLoop();
  5046. while (this.scenes.length) {
  5047. this.scenes[0].dispose();
  5048. }
  5049. // Release audio engine
  5050. Engine.audioEngine.dispose();
  5051. for (var name in this._compiledEffects) {
  5052. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5053. }
  5054. for (var i in this._vertexAttribArrays) {
  5055. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5056. continue;
  5057. }
  5058. this._gl.disableVertexAttribArray(i);
  5059. }
  5060. // Events
  5061. window.removeEventListener("blur", this._onBlur);
  5062. window.removeEventListener("focus", this._onFocus);
  5063. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5064. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5065. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5066. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5067. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5068. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5069. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5070. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5071. };
  5072. // Loading screen
  5073. Engine.prototype.displayLoadingUI = function () {
  5074. var _this = this;
  5075. this._loadingDiv = document.createElement("div");
  5076. this._loadingDiv.style.opacity = "0";
  5077. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5078. // Loading text
  5079. this._loadingTextDiv = document.createElement("div");
  5080. this._loadingTextDiv.style.position = "absolute";
  5081. this._loadingTextDiv.style.left = "0";
  5082. this._loadingTextDiv.style.top = "50%";
  5083. this._loadingTextDiv.style.marginTop = "80px";
  5084. this._loadingTextDiv.style.width = "100%";
  5085. this._loadingTextDiv.style.height = "20px";
  5086. this._loadingTextDiv.style.fontFamily = "Arial";
  5087. this._loadingTextDiv.style.fontSize = "14px";
  5088. this._loadingTextDiv.style.color = "white";
  5089. this._loadingTextDiv.style.textAlign = "center";
  5090. this._loadingTextDiv.innerHTML = "Loading";
  5091. this._loadingDiv.appendChild(this._loadingTextDiv);
  5092. // Loading img
  5093. var imgBack = new Image();
  5094. 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==";
  5095. imgBack.style.position = "absolute";
  5096. imgBack.style.left = "50%";
  5097. imgBack.style.top = "50%";
  5098. imgBack.style.marginLeft = "-50px";
  5099. imgBack.style.marginTop = "-50px";
  5100. imgBack.style.transition = "transform 1.0s ease";
  5101. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5102. var deg = 360;
  5103. var onTransitionEnd = function () {
  5104. deg += 360;
  5105. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5106. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5107. };
  5108. imgBack.addEventListener("transitionend", onTransitionEnd);
  5109. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5110. this._loadingDiv.appendChild(imgBack);
  5111. // front image
  5112. var imgFront = new Image();
  5113. 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=";
  5114. imgFront.style.position = "absolute";
  5115. imgFront.style.left = "50%";
  5116. imgFront.style.top = "50%";
  5117. imgFront.style.marginLeft = "-50px";
  5118. imgFront.style.marginTop = "-50px";
  5119. this._loadingDiv.appendChild(imgFront);
  5120. // Resize
  5121. this._resizeLoadingUI = function () {
  5122. var canvasRect = _this.getRenderingCanvasClientRect();
  5123. _this._loadingDiv.style.position = "absolute";
  5124. _this._loadingDiv.style.left = canvasRect.left + "px";
  5125. _this._loadingDiv.style.top = canvasRect.top + "px";
  5126. _this._loadingDiv.style.width = canvasRect.width + "px";
  5127. _this._loadingDiv.style.height = canvasRect.height + "px";
  5128. };
  5129. this._resizeLoadingUI();
  5130. window.addEventListener("resize", this._resizeLoadingUI);
  5131. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5132. document.body.appendChild(this._loadingDiv);
  5133. setTimeout(function () {
  5134. _this._loadingDiv.style.opacity = "1";
  5135. imgBack.style.transform = "rotateZ(360deg)";
  5136. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5137. }, 0);
  5138. };
  5139. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5140. set: function (text) {
  5141. if (!this._loadingDiv) {
  5142. return;
  5143. }
  5144. this._loadingTextDiv.innerHTML = text;
  5145. },
  5146. enumerable: true,
  5147. configurable: true
  5148. });
  5149. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5150. get: function () {
  5151. return this._loadingDivBackgroundColor;
  5152. },
  5153. set: function (color) {
  5154. this._loadingDivBackgroundColor = color;
  5155. if (!this._loadingDiv) {
  5156. return;
  5157. }
  5158. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5159. },
  5160. enumerable: true,
  5161. configurable: true
  5162. });
  5163. Engine.prototype.hideLoadingUI = function () {
  5164. var _this = this;
  5165. if (!this._loadingDiv) {
  5166. return;
  5167. }
  5168. var onTransitionEnd = function () {
  5169. if (!_this._loadingDiv) {
  5170. return;
  5171. }
  5172. document.body.removeChild(_this._loadingDiv);
  5173. window.removeEventListener("resize", _this._resizeLoadingUI);
  5174. _this._loadingDiv = null;
  5175. };
  5176. this._loadingDiv.style.opacity = "0";
  5177. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5178. };
  5179. // FPS
  5180. Engine.prototype.getFps = function () {
  5181. return this.fps;
  5182. };
  5183. Engine.prototype.getDeltaTime = function () {
  5184. return this.deltaTime;
  5185. };
  5186. Engine.prototype._measureFps = function () {
  5187. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5188. var length = this.previousFramesDuration.length;
  5189. if (length >= 2) {
  5190. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5191. }
  5192. if (length >= this.fpsRange) {
  5193. if (length > this.fpsRange) {
  5194. this.previousFramesDuration.splice(0, 1);
  5195. length = this.previousFramesDuration.length;
  5196. }
  5197. var sum = 0;
  5198. for (var id = 0; id < length - 1; id++) {
  5199. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5200. }
  5201. this.fps = 1000.0 / (sum / (length - 1));
  5202. }
  5203. };
  5204. // Statics
  5205. Engine.isSupported = function () {
  5206. try {
  5207. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5208. if (navigator.isCocoonJS) {
  5209. return true;
  5210. }
  5211. var tempcanvas = document.createElement("canvas");
  5212. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5213. return gl != null && !!window.WebGLRenderingContext;
  5214. }
  5215. catch (e) {
  5216. return false;
  5217. }
  5218. };
  5219. // Const statics
  5220. Engine._ALPHA_DISABLE = 0;
  5221. Engine._ALPHA_ADD = 1;
  5222. Engine._ALPHA_COMBINE = 2;
  5223. Engine._DELAYLOADSTATE_NONE = 0;
  5224. Engine._DELAYLOADSTATE_LOADED = 1;
  5225. Engine._DELAYLOADSTATE_LOADING = 2;
  5226. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5227. Engine._TEXTUREFORMAT_ALPHA = 0;
  5228. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5229. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5230. Engine._TEXTUREFORMAT_RGB = 4;
  5231. Engine._TEXTUREFORMAT_RGBA = 4;
  5232. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5233. Engine._TEXTURETYPE_FLOAT = 1;
  5234. // Updatable statics so stick with vars here
  5235. Engine.Epsilon = 0.001;
  5236. Engine.CollisionsEpsilon = 0.001;
  5237. Engine.ShadersRepository = "Babylon/Shaders/";
  5238. return Engine;
  5239. })();
  5240. BABYLON.Engine = Engine;
  5241. })(BABYLON || (BABYLON = {}));
  5242. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5243. (function (BABYLON) {
  5244. /**
  5245. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5246. */
  5247. var Node = (function () {
  5248. /**
  5249. * @constructor
  5250. * @param {string} name - the name and id to be given to this node
  5251. * @param {BABYLON.Scene} the scene this node will be added to
  5252. */
  5253. function Node(name, scene) {
  5254. this.state = "";
  5255. this.animations = new Array();
  5256. this._childrenFlag = -1;
  5257. this._isEnabled = true;
  5258. this._isReady = true;
  5259. this._currentRenderId = -1;
  5260. this.name = name;
  5261. this.id = name;
  5262. this._scene = scene;
  5263. this._initCache();
  5264. }
  5265. Node.prototype.getScene = function () {
  5266. return this._scene;
  5267. };
  5268. Node.prototype.getEngine = function () {
  5269. return this._scene.getEngine();
  5270. };
  5271. // override it in derived class
  5272. Node.prototype.getWorldMatrix = function () {
  5273. return BABYLON.Matrix.Identity();
  5274. };
  5275. // override it in derived class if you add new variables to the cache
  5276. // and call the parent class method
  5277. Node.prototype._initCache = function () {
  5278. this._cache = {};
  5279. this._cache.parent = undefined;
  5280. };
  5281. Node.prototype.updateCache = function (force) {
  5282. if (!force && this.isSynchronized())
  5283. return;
  5284. this._cache.parent = this.parent;
  5285. this._updateCache();
  5286. };
  5287. // override it in derived class if you add new variables to the cache
  5288. // and call the parent class method if !ignoreParentClass
  5289. Node.prototype._updateCache = function (ignoreParentClass) {
  5290. };
  5291. // override it in derived class if you add new variables to the cache
  5292. Node.prototype._isSynchronized = function () {
  5293. return true;
  5294. };
  5295. Node.prototype.isSynchronizedWithParent = function () {
  5296. return this.parent ? this.parent._currentRenderId <= this._currentRenderId && this.parent.isSynchronized() : true;
  5297. };
  5298. Node.prototype.isSynchronized = function (updateCache) {
  5299. var check = this.hasNewParent();
  5300. check = check || !this.isSynchronizedWithParent();
  5301. check = check || !this._isSynchronized();
  5302. if (updateCache)
  5303. this.updateCache(true);
  5304. return !check;
  5305. };
  5306. Node.prototype.hasNewParent = function (update) {
  5307. if (this._cache.parent === this.parent)
  5308. return false;
  5309. if (update)
  5310. this._cache.parent = this.parent;
  5311. return true;
  5312. };
  5313. /**
  5314. * Is this node ready to be used/rendered
  5315. * @return {boolean} is it ready
  5316. */
  5317. Node.prototype.isReady = function () {
  5318. return this._isReady;
  5319. };
  5320. /**
  5321. * Is this node enabled.
  5322. * If the node has a parent and is enabled, the parent will be inspected as well.
  5323. * @return {boolean} whether this node (and its parent) is enabled.
  5324. * @see setEnabled
  5325. */
  5326. Node.prototype.isEnabled = function () {
  5327. if (!this._isEnabled) {
  5328. return false;
  5329. }
  5330. if (this.parent) {
  5331. return this.parent.isEnabled();
  5332. }
  5333. return true;
  5334. };
  5335. /**
  5336. * Set the enabled state of this node.
  5337. * @param {boolean} value - the new enabled state
  5338. * @see isEnabled
  5339. */
  5340. Node.prototype.setEnabled = function (value) {
  5341. this._isEnabled = value;
  5342. };
  5343. /**
  5344. * Is this node a descendant of the given node.
  5345. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5346. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5347. * @see parent
  5348. */
  5349. Node.prototype.isDescendantOf = function (ancestor) {
  5350. if (this.parent) {
  5351. if (this.parent === ancestor) {
  5352. return true;
  5353. }
  5354. return this.parent.isDescendantOf(ancestor);
  5355. }
  5356. return false;
  5357. };
  5358. Node.prototype._getDescendants = function (list, results) {
  5359. for (var index = 0; index < list.length; index++) {
  5360. var item = list[index];
  5361. if (item.isDescendantOf(this)) {
  5362. results.push(item);
  5363. }
  5364. }
  5365. };
  5366. /**
  5367. * Will return all nodes that have this node as parent.
  5368. * @return {BABYLON.Node[]} all children nodes of all types.
  5369. */
  5370. Node.prototype.getDescendants = function () {
  5371. var results = [];
  5372. this._getDescendants(this._scene.meshes, results);
  5373. this._getDescendants(this._scene.lights, results);
  5374. this._getDescendants(this._scene.cameras, results);
  5375. return results;
  5376. };
  5377. Node.prototype._setReady = function (state) {
  5378. if (state == this._isReady) {
  5379. return;
  5380. }
  5381. if (!state) {
  5382. this._isReady = false;
  5383. return;
  5384. }
  5385. this._isReady = true;
  5386. if (this.onReady) {
  5387. this.onReady(this);
  5388. }
  5389. };
  5390. return Node;
  5391. })();
  5392. BABYLON.Node = Node;
  5393. })(BABYLON || (BABYLON = {}));
  5394. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5395. (function (BABYLON) {
  5396. var BoundingSphere = (function () {
  5397. function BoundingSphere(minimum, maximum) {
  5398. this.minimum = minimum;
  5399. this.maximum = maximum;
  5400. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5401. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5402. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5403. this.radius = distance * 0.5;
  5404. this.centerWorld = BABYLON.Vector3.Zero();
  5405. this._update(BABYLON.Matrix.Identity());
  5406. }
  5407. // Methods
  5408. BoundingSphere.prototype._update = function (world) {
  5409. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5410. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5411. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5412. };
  5413. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5414. for (var i = 0; i < 6; i++) {
  5415. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5416. return false;
  5417. }
  5418. return true;
  5419. };
  5420. BoundingSphere.prototype.intersectsPoint = function (point) {
  5421. var x = this.centerWorld.x - point.x;
  5422. var y = this.centerWorld.y - point.y;
  5423. var z = this.centerWorld.z - point.z;
  5424. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5425. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5426. return false;
  5427. return true;
  5428. };
  5429. // Statics
  5430. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5431. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5432. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5433. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5434. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5435. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5436. return false;
  5437. return true;
  5438. };
  5439. return BoundingSphere;
  5440. })();
  5441. BABYLON.BoundingSphere = BoundingSphere;
  5442. })(BABYLON || (BABYLON = {}));
  5443. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5444. (function (BABYLON) {
  5445. var BoundingBox = (function () {
  5446. function BoundingBox(minimum, maximum) {
  5447. this.minimum = minimum;
  5448. this.maximum = maximum;
  5449. this.vectors = new Array();
  5450. this.vectorsWorld = new Array();
  5451. // Bounding vectors
  5452. this.vectors.push(this.minimum.clone());
  5453. this.vectors.push(this.maximum.clone());
  5454. this.vectors.push(this.minimum.clone());
  5455. this.vectors[2].x = this.maximum.x;
  5456. this.vectors.push(this.minimum.clone());
  5457. this.vectors[3].y = this.maximum.y;
  5458. this.vectors.push(this.minimum.clone());
  5459. this.vectors[4].z = this.maximum.z;
  5460. this.vectors.push(this.maximum.clone());
  5461. this.vectors[5].z = this.minimum.z;
  5462. this.vectors.push(this.maximum.clone());
  5463. this.vectors[6].x = this.minimum.x;
  5464. this.vectors.push(this.maximum.clone());
  5465. this.vectors[7].y = this.minimum.y;
  5466. // OBB
  5467. this.center = this.maximum.add(this.minimum).scale(0.5);
  5468. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5469. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5470. for (var index = 0; index < this.vectors.length; index++) {
  5471. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5472. }
  5473. this.minimumWorld = BABYLON.Vector3.Zero();
  5474. this.maximumWorld = BABYLON.Vector3.Zero();
  5475. this._update(BABYLON.Matrix.Identity());
  5476. }
  5477. // Methods
  5478. BoundingBox.prototype.getWorldMatrix = function () {
  5479. return this._worldMatrix;
  5480. };
  5481. BoundingBox.prototype._update = function (world) {
  5482. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5483. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5484. for (var index = 0; index < this.vectors.length; index++) {
  5485. var v = this.vectorsWorld[index];
  5486. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5487. if (v.x < this.minimumWorld.x)
  5488. this.minimumWorld.x = v.x;
  5489. if (v.y < this.minimumWorld.y)
  5490. this.minimumWorld.y = v.y;
  5491. if (v.z < this.minimumWorld.z)
  5492. this.minimumWorld.z = v.z;
  5493. if (v.x > this.maximumWorld.x)
  5494. this.maximumWorld.x = v.x;
  5495. if (v.y > this.maximumWorld.y)
  5496. this.maximumWorld.y = v.y;
  5497. if (v.z > this.maximumWorld.z)
  5498. this.maximumWorld.z = v.z;
  5499. }
  5500. // OBB
  5501. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5502. this.center.scaleInPlace(0.5);
  5503. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5504. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5505. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5506. this._worldMatrix = world;
  5507. };
  5508. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5509. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5510. };
  5511. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5512. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5513. };
  5514. BoundingBox.prototype.intersectsPoint = function (point) {
  5515. var delta = BABYLON.Engine.Epsilon;
  5516. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5517. return false;
  5518. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5519. return false;
  5520. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5521. return false;
  5522. return true;
  5523. };
  5524. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5525. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5526. };
  5527. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5528. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5529. return false;
  5530. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5531. return false;
  5532. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5533. return false;
  5534. return true;
  5535. };
  5536. // Statics
  5537. BoundingBox.Intersects = function (box0, box1) {
  5538. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5539. return false;
  5540. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5541. return false;
  5542. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5543. return false;
  5544. return true;
  5545. };
  5546. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5547. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5548. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5549. return (num <= (sphereRadius * sphereRadius));
  5550. };
  5551. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5552. for (var p = 0; p < 6; p++) {
  5553. for (var i = 0; i < 8; i++) {
  5554. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5555. return false;
  5556. }
  5557. }
  5558. }
  5559. return true;
  5560. };
  5561. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5562. for (var p = 0; p < 6; p++) {
  5563. var inCount = 8;
  5564. for (var i = 0; i < 8; i++) {
  5565. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5566. --inCount;
  5567. }
  5568. else {
  5569. break;
  5570. }
  5571. }
  5572. if (inCount === 0)
  5573. return false;
  5574. }
  5575. return true;
  5576. };
  5577. return BoundingBox;
  5578. })();
  5579. BABYLON.BoundingBox = BoundingBox;
  5580. })(BABYLON || (BABYLON = {}));
  5581. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5582. (function (BABYLON) {
  5583. var computeBoxExtents = function (axis, box) {
  5584. var p = BABYLON.Vector3.Dot(box.center, axis);
  5585. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5586. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5587. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5588. var r = r0 + r1 + r2;
  5589. return {
  5590. min: p - r,
  5591. max: p + r
  5592. };
  5593. };
  5594. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5595. var axisOverlap = function (axis, box0, box1) {
  5596. var result0 = computeBoxExtents(axis, box0);
  5597. var result1 = computeBoxExtents(axis, box1);
  5598. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5599. };
  5600. var BoundingInfo = (function () {
  5601. function BoundingInfo(minimum, maximum) {
  5602. this.minimum = minimum;
  5603. this.maximum = maximum;
  5604. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5605. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5606. }
  5607. // Methods
  5608. BoundingInfo.prototype._update = function (world) {
  5609. this.boundingBox._update(world);
  5610. this.boundingSphere._update(world);
  5611. };
  5612. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5613. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5614. return false;
  5615. return this.boundingBox.isInFrustum(frustumPlanes);
  5616. };
  5617. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5618. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5619. };
  5620. BoundingInfo.prototype._checkCollision = function (collider) {
  5621. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5622. };
  5623. BoundingInfo.prototype.intersectsPoint = function (point) {
  5624. if (!this.boundingSphere.centerWorld) {
  5625. return false;
  5626. }
  5627. if (!this.boundingSphere.intersectsPoint(point)) {
  5628. return false;
  5629. }
  5630. if (!this.boundingBox.intersectsPoint(point)) {
  5631. return false;
  5632. }
  5633. return true;
  5634. };
  5635. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5636. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5637. return false;
  5638. }
  5639. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5640. return false;
  5641. }
  5642. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5643. return false;
  5644. }
  5645. if (!precise) {
  5646. return true;
  5647. }
  5648. var box0 = this.boundingBox;
  5649. var box1 = boundingInfo.boundingBox;
  5650. if (!axisOverlap(box0.directions[0], box0, box1))
  5651. return false;
  5652. if (!axisOverlap(box0.directions[1], box0, box1))
  5653. return false;
  5654. if (!axisOverlap(box0.directions[2], box0, box1))
  5655. return false;
  5656. if (!axisOverlap(box1.directions[0], box0, box1))
  5657. return false;
  5658. if (!axisOverlap(box1.directions[1], box0, box1))
  5659. return false;
  5660. if (!axisOverlap(box1.directions[2], box0, box1))
  5661. return false;
  5662. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5663. return false;
  5664. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5665. return false;
  5666. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5667. return false;
  5668. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5669. return false;
  5670. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5671. return false;
  5672. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5673. return false;
  5674. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5675. return false;
  5676. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5677. return false;
  5678. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5679. return false;
  5680. return true;
  5681. };
  5682. return BoundingInfo;
  5683. })();
  5684. BABYLON.BoundingInfo = BoundingInfo;
  5685. })(BABYLON || (BABYLON = {}));
  5686. //# sourceMappingURL=babylon.boundingInfo.js.map
  5687. var BABYLON;
  5688. (function (BABYLON) {
  5689. var Light = (function (_super) {
  5690. __extends(Light, _super);
  5691. function Light(name, scene) {
  5692. _super.call(this, name, scene);
  5693. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5694. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5695. this.intensity = 1.0;
  5696. this.range = Number.MAX_VALUE;
  5697. this.includedOnlyMeshes = new Array();
  5698. this.excludedMeshes = new Array();
  5699. this._excludedMeshesIds = new Array();
  5700. this._includedOnlyMeshesIds = new Array();
  5701. scene.addLight(this);
  5702. }
  5703. Light.prototype.getShadowGenerator = function () {
  5704. return this._shadowGenerator;
  5705. };
  5706. Light.prototype.getAbsolutePosition = function () {
  5707. return BABYLON.Vector3.Zero();
  5708. };
  5709. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5710. };
  5711. Light.prototype._getWorldMatrix = function () {
  5712. return BABYLON.Matrix.Identity();
  5713. };
  5714. Light.prototype.canAffectMesh = function (mesh) {
  5715. if (!mesh) {
  5716. return true;
  5717. }
  5718. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5719. return false;
  5720. }
  5721. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5722. return false;
  5723. }
  5724. return true;
  5725. };
  5726. Light.prototype.getWorldMatrix = function () {
  5727. this._currentRenderId = this.getScene().getRenderId();
  5728. var worldMatrix = this._getWorldMatrix();
  5729. if (this.parent && this.parent.getWorldMatrix) {
  5730. if (!this._parentedWorldMatrix) {
  5731. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5732. }
  5733. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5734. return this._parentedWorldMatrix;
  5735. }
  5736. return worldMatrix;
  5737. };
  5738. Light.prototype.dispose = function () {
  5739. if (this._shadowGenerator) {
  5740. this._shadowGenerator.dispose();
  5741. this._shadowGenerator = null;
  5742. }
  5743. // Remove from scene
  5744. this.getScene().removeLight(this);
  5745. };
  5746. return Light;
  5747. })(BABYLON.Node);
  5748. BABYLON.Light = Light;
  5749. })(BABYLON || (BABYLON = {}));
  5750. //# sourceMappingURL=babylon.light.js.map
  5751. var BABYLON;
  5752. (function (BABYLON) {
  5753. var PointLight = (function (_super) {
  5754. __extends(PointLight, _super);
  5755. function PointLight(name, position, scene) {
  5756. _super.call(this, name, scene);
  5757. this.position = position;
  5758. }
  5759. PointLight.prototype.getAbsolutePosition = function () {
  5760. return this._transformedPosition ? this._transformedPosition : this.position;
  5761. };
  5762. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5763. if (this.parent && this.parent.getWorldMatrix) {
  5764. if (!this._transformedPosition) {
  5765. this._transformedPosition = BABYLON.Vector3.Zero();
  5766. }
  5767. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5768. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5769. return;
  5770. }
  5771. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5772. };
  5773. PointLight.prototype.getShadowGenerator = function () {
  5774. return null;
  5775. };
  5776. PointLight.prototype._getWorldMatrix = function () {
  5777. if (!this._worldMatrix) {
  5778. this._worldMatrix = BABYLON.Matrix.Identity();
  5779. }
  5780. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5781. return this._worldMatrix;
  5782. };
  5783. return PointLight;
  5784. })(BABYLON.Light);
  5785. BABYLON.PointLight = PointLight;
  5786. })(BABYLON || (BABYLON = {}));
  5787. //# sourceMappingURL=babylon.pointLight.js.map
  5788. var BABYLON;
  5789. (function (BABYLON) {
  5790. var SpotLight = (function (_super) {
  5791. __extends(SpotLight, _super);
  5792. function SpotLight(name, position, direction, angle, exponent, scene) {
  5793. _super.call(this, name, scene);
  5794. this.position = position;
  5795. this.direction = direction;
  5796. this.angle = angle;
  5797. this.exponent = exponent;
  5798. }
  5799. SpotLight.prototype.getAbsolutePosition = function () {
  5800. return this.transformedPosition ? this.transformedPosition : this.position;
  5801. };
  5802. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5803. var activeCamera = this.getScene().activeCamera;
  5804. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  5805. };
  5806. SpotLight.prototype.supportsVSM = function () {
  5807. return true;
  5808. };
  5809. SpotLight.prototype.needRefreshPerFrame = function () {
  5810. return false;
  5811. };
  5812. SpotLight.prototype.setDirectionToTarget = function (target) {
  5813. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5814. return this.direction;
  5815. };
  5816. SpotLight.prototype.computeTransformedPosition = function () {
  5817. if (this.parent && this.parent.getWorldMatrix) {
  5818. if (!this.transformedPosition) {
  5819. this.transformedPosition = BABYLON.Vector3.Zero();
  5820. }
  5821. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5822. return true;
  5823. }
  5824. return false;
  5825. };
  5826. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5827. var normalizeDirection;
  5828. if (this.parent && this.parent.getWorldMatrix) {
  5829. if (!this._transformedDirection) {
  5830. this._transformedDirection = BABYLON.Vector3.Zero();
  5831. }
  5832. this.computeTransformedPosition();
  5833. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5834. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5835. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5836. }
  5837. else {
  5838. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5839. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5840. }
  5841. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5842. };
  5843. SpotLight.prototype._getWorldMatrix = function () {
  5844. if (!this._worldMatrix) {
  5845. this._worldMatrix = BABYLON.Matrix.Identity();
  5846. }
  5847. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5848. return this._worldMatrix;
  5849. };
  5850. return SpotLight;
  5851. })(BABYLON.Light);
  5852. BABYLON.SpotLight = SpotLight;
  5853. })(BABYLON || (BABYLON = {}));
  5854. //# sourceMappingURL=babylon.spotLight.js.map
  5855. var BABYLON;
  5856. (function (BABYLON) {
  5857. var DirectionalLight = (function (_super) {
  5858. __extends(DirectionalLight, _super);
  5859. function DirectionalLight(name, direction, scene) {
  5860. _super.call(this, name, scene);
  5861. this.direction = direction;
  5862. this.shadowOrthoScale = 0.1;
  5863. this.position = direction.scale(-1);
  5864. }
  5865. DirectionalLight.prototype.getAbsolutePosition = function () {
  5866. return this.transformedPosition ? this.transformedPosition : this.position;
  5867. };
  5868. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5869. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5870. return this.direction;
  5871. };
  5872. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5873. var orthoLeft = Number.MAX_VALUE;
  5874. var orthoRight = Number.MIN_VALUE;
  5875. var orthoTop = Number.MIN_VALUE;
  5876. var orthoBottom = Number.MAX_VALUE;
  5877. var tempVector3 = BABYLON.Vector3.Zero();
  5878. var activeCamera = this.getScene().activeCamera;
  5879. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  5880. var mesh = renderList[meshIndex];
  5881. if (!mesh) {
  5882. continue;
  5883. }
  5884. var boundingInfo = mesh.getBoundingInfo();
  5885. if (!boundingInfo) {
  5886. continue;
  5887. }
  5888. var boundingBox = boundingInfo.boundingBox;
  5889. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  5890. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  5891. if (tempVector3.x < orthoLeft)
  5892. orthoLeft = tempVector3.x;
  5893. if (tempVector3.y < orthoBottom)
  5894. orthoBottom = tempVector3.y;
  5895. if (tempVector3.x > orthoRight)
  5896. orthoRight = tempVector3.x;
  5897. if (tempVector3.y > orthoTop)
  5898. orthoTop = tempVector3.y;
  5899. }
  5900. }
  5901. var xOffset = orthoRight - orthoLeft;
  5902. var yOffset = orthoTop - orthoBottom;
  5903. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  5904. };
  5905. DirectionalLight.prototype.supportsVSM = function () {
  5906. return true;
  5907. };
  5908. DirectionalLight.prototype.needRefreshPerFrame = function () {
  5909. return true;
  5910. };
  5911. DirectionalLight.prototype.computeTransformedPosition = function () {
  5912. if (this.parent && this.parent.getWorldMatrix) {
  5913. if (!this.transformedPosition) {
  5914. this.transformedPosition = BABYLON.Vector3.Zero();
  5915. }
  5916. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5917. return true;
  5918. }
  5919. return false;
  5920. };
  5921. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5922. if (this.parent && this.parent.getWorldMatrix) {
  5923. if (!this._transformedDirection) {
  5924. this._transformedDirection = BABYLON.Vector3.Zero();
  5925. }
  5926. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5927. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5928. return;
  5929. }
  5930. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5931. };
  5932. DirectionalLight.prototype._getWorldMatrix = function () {
  5933. if (!this._worldMatrix) {
  5934. this._worldMatrix = BABYLON.Matrix.Identity();
  5935. }
  5936. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5937. return this._worldMatrix;
  5938. };
  5939. return DirectionalLight;
  5940. })(BABYLON.Light);
  5941. BABYLON.DirectionalLight = DirectionalLight;
  5942. })(BABYLON || (BABYLON = {}));
  5943. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5944. (function (BABYLON) {
  5945. var ShadowGenerator = (function () {
  5946. function ShadowGenerator(mapSize, light) {
  5947. var _this = this;
  5948. // Members
  5949. this._filter = ShadowGenerator.FILTER_NONE;
  5950. this.blurScale = 2;
  5951. this._blurBoxOffset = 0;
  5952. this._bias = 0.00005;
  5953. this._darkness = 0;
  5954. this._transparencyShadow = false;
  5955. this._viewMatrix = BABYLON.Matrix.Zero();
  5956. this._projectionMatrix = BABYLON.Matrix.Zero();
  5957. this._transformMatrix = BABYLON.Matrix.Zero();
  5958. this._worldViewProjection = BABYLON.Matrix.Zero();
  5959. this._light = light;
  5960. this._scene = light.getScene();
  5961. this._mapSize = mapSize;
  5962. light._shadowGenerator = this;
  5963. // Render target
  5964. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5965. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5966. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5967. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5968. this._shadowMap.renderParticles = false;
  5969. this._shadowMap.onAfterUnbind = function () {
  5970. if (!_this.useBlurVarianceShadowMap) {
  5971. return;
  5972. }
  5973. if (!_this._shadowMap2) {
  5974. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  5975. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5976. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5977. _this._shadowMap2.anisotropicFilteringLevel = 16;
  5978. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  5979. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, _this._scene.getEngine());
  5980. _this._downSamplePostprocess.onApply = function (effect) {
  5981. effect.setTexture("textureSampler", _this._shadowMap);
  5982. };
  5983. _this.blurBoxOffset = 1;
  5984. }
  5985. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  5986. };
  5987. // Custom render function
  5988. var renderSubMesh = function (subMesh) {
  5989. var mesh = subMesh.getRenderingMesh();
  5990. var scene = _this._scene;
  5991. var engine = scene.getEngine();
  5992. // Culling
  5993. engine.setState(subMesh.getMaterial().backFaceCulling);
  5994. // Managing instances
  5995. var batch = mesh._getInstancesRenderList(subMesh._id);
  5996. if (batch.mustReturn) {
  5997. return;
  5998. }
  5999. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6000. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6001. engine.enableEffect(_this._effect);
  6002. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6003. var material = subMesh.getMaterial();
  6004. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6005. // Alpha test
  6006. if (material && material.needAlphaTesting()) {
  6007. var alphaTexture = material.getAlphaTestTexture();
  6008. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6009. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6010. }
  6011. // Bones
  6012. if (mesh.useBones) {
  6013. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6014. }
  6015. // Draw
  6016. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6017. }
  6018. else {
  6019. // Need to reset refresh rate of the shadowMap
  6020. _this._shadowMap.resetRefreshCounter();
  6021. }
  6022. };
  6023. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6024. var index;
  6025. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6026. renderSubMesh(opaqueSubMeshes.data[index]);
  6027. }
  6028. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6029. renderSubMesh(alphaTestSubMeshes.data[index]);
  6030. }
  6031. if (_this._transparencyShadow) {
  6032. for (index = 0; index < transparentSubMeshes.length; index++) {
  6033. renderSubMesh(transparentSubMeshes.data[index]);
  6034. }
  6035. }
  6036. };
  6037. this._shadowMap.onClear = function (engine) {
  6038. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6039. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6040. }
  6041. else {
  6042. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6043. }
  6044. };
  6045. }
  6046. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6047. // Static
  6048. get: function () {
  6049. return ShadowGenerator._FILTER_NONE;
  6050. },
  6051. enumerable: true,
  6052. configurable: true
  6053. });
  6054. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6055. get: function () {
  6056. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6057. },
  6058. enumerable: true,
  6059. configurable: true
  6060. });
  6061. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6062. get: function () {
  6063. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6064. },
  6065. enumerable: true,
  6066. configurable: true
  6067. });
  6068. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6069. get: function () {
  6070. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6071. },
  6072. enumerable: true,
  6073. configurable: true
  6074. });
  6075. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6076. get: function () {
  6077. return this._bias;
  6078. },
  6079. set: function (bias) {
  6080. this._bias = bias;
  6081. },
  6082. enumerable: true,
  6083. configurable: true
  6084. });
  6085. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6086. get: function () {
  6087. return this._blurBoxOffset;
  6088. },
  6089. set: function (value) {
  6090. var _this = this;
  6091. if (this._blurBoxOffset === value) {
  6092. return;
  6093. }
  6094. this._blurBoxOffset = value;
  6095. if (this._boxBlurPostprocess) {
  6096. this._boxBlurPostprocess.dispose();
  6097. }
  6098. 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);
  6099. this._boxBlurPostprocess.onApply = function (effect) {
  6100. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6101. };
  6102. },
  6103. enumerable: true,
  6104. configurable: true
  6105. });
  6106. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6107. get: function () {
  6108. return this._filter;
  6109. },
  6110. set: function (value) {
  6111. if (this._filter === value) {
  6112. return;
  6113. }
  6114. this._filter = value;
  6115. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6116. this._shadowMap.anisotropicFilteringLevel = 16;
  6117. this._shadowMap.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6118. }
  6119. else {
  6120. this._shadowMap.anisotropicFilteringLevel = 1;
  6121. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6122. }
  6123. },
  6124. enumerable: true,
  6125. configurable: true
  6126. });
  6127. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6128. get: function () {
  6129. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6130. },
  6131. set: function (value) {
  6132. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6133. },
  6134. enumerable: true,
  6135. configurable: true
  6136. });
  6137. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6138. get: function () {
  6139. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6140. },
  6141. set: function (value) {
  6142. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6143. },
  6144. enumerable: true,
  6145. configurable: true
  6146. });
  6147. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6148. get: function () {
  6149. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6150. },
  6151. set: function (value) {
  6152. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6153. },
  6154. enumerable: true,
  6155. configurable: true
  6156. });
  6157. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6158. var defines = [];
  6159. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6160. defines.push("#define VSM");
  6161. }
  6162. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6163. var mesh = subMesh.getMesh();
  6164. var material = subMesh.getMaterial();
  6165. // Alpha test
  6166. if (material && material.needAlphaTesting()) {
  6167. defines.push("#define ALPHATEST");
  6168. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6169. attribs.push(BABYLON.VertexBuffer.UVKind);
  6170. defines.push("#define UV1");
  6171. }
  6172. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6173. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6174. defines.push("#define UV2");
  6175. }
  6176. }
  6177. // Bones
  6178. if (mesh.useBones) {
  6179. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6180. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6181. defines.push("#define BONES");
  6182. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6183. }
  6184. // Instances
  6185. if (useInstances) {
  6186. defines.push("#define INSTANCES");
  6187. attribs.push("world0");
  6188. attribs.push("world1");
  6189. attribs.push("world2");
  6190. attribs.push("world3");
  6191. }
  6192. // Get correct effect
  6193. var join = defines.join("\n");
  6194. if (this._cachedDefines !== join) {
  6195. this._cachedDefines = join;
  6196. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6197. }
  6198. return this._effect.isReady();
  6199. };
  6200. ShadowGenerator.prototype.getShadowMap = function () {
  6201. return this._shadowMap;
  6202. };
  6203. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6204. if (this._shadowMap2) {
  6205. return this._shadowMap2;
  6206. }
  6207. return this._shadowMap;
  6208. };
  6209. ShadowGenerator.prototype.getLight = function () {
  6210. return this._light;
  6211. };
  6212. // Methods
  6213. ShadowGenerator.prototype.getTransformMatrix = function () {
  6214. var scene = this._scene;
  6215. if (this._currentRenderID === scene.getRenderId()) {
  6216. return this._transformMatrix;
  6217. }
  6218. this._currentRenderID = scene.getRenderId();
  6219. var lightPosition = this._light.position;
  6220. var lightDirection = this._light.direction;
  6221. if (this._light.computeTransformedPosition()) {
  6222. lightPosition = this._light.transformedPosition;
  6223. }
  6224. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6225. this._cachedPosition = lightPosition.clone();
  6226. this._cachedDirection = lightDirection.clone();
  6227. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6228. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6229. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6230. }
  6231. return this._transformMatrix;
  6232. };
  6233. ShadowGenerator.prototype.getDarkness = function () {
  6234. return this._darkness;
  6235. };
  6236. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6237. if (darkness >= 1.0)
  6238. this._darkness = 1.0;
  6239. else if (darkness <= 0.0)
  6240. this._darkness = 0.0;
  6241. else
  6242. this._darkness = darkness;
  6243. };
  6244. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6245. this._transparencyShadow = hasShadow;
  6246. };
  6247. ShadowGenerator.prototype._packHalf = function (depth) {
  6248. var scale = depth * 255.0;
  6249. var fract = scale - Math.floor(scale);
  6250. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6251. };
  6252. ShadowGenerator.prototype.dispose = function () {
  6253. this._shadowMap.dispose();
  6254. if (this._shadowMap2) {
  6255. this._shadowMap2.dispose();
  6256. }
  6257. if (this._downSamplePostprocess) {
  6258. this._downSamplePostprocess.dispose();
  6259. }
  6260. if (this._boxBlurPostprocess) {
  6261. this._boxBlurPostprocess.dispose();
  6262. }
  6263. };
  6264. ShadowGenerator._FILTER_NONE = 0;
  6265. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6266. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6267. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6268. return ShadowGenerator;
  6269. })();
  6270. BABYLON.ShadowGenerator = ShadowGenerator;
  6271. })(BABYLON || (BABYLON = {}));
  6272. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6273. var BABYLON;
  6274. (function (BABYLON) {
  6275. var HemisphericLight = (function (_super) {
  6276. __extends(HemisphericLight, _super);
  6277. function HemisphericLight(name, direction, scene) {
  6278. _super.call(this, name, scene);
  6279. this.direction = direction;
  6280. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6281. }
  6282. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6283. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6284. return this.direction;
  6285. };
  6286. HemisphericLight.prototype.getShadowGenerator = function () {
  6287. return null;
  6288. };
  6289. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6290. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6291. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6292. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6293. };
  6294. HemisphericLight.prototype._getWorldMatrix = function () {
  6295. if (!this._worldMatrix) {
  6296. this._worldMatrix = BABYLON.Matrix.Identity();
  6297. }
  6298. return this._worldMatrix;
  6299. };
  6300. return HemisphericLight;
  6301. })(BABYLON.Light);
  6302. BABYLON.HemisphericLight = HemisphericLight;
  6303. })(BABYLON || (BABYLON = {}));
  6304. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6305. (function (BABYLON) {
  6306. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6307. if (boxMin.x > sphereCenter.x + sphereRadius)
  6308. return false;
  6309. if (sphereCenter.x - sphereRadius > boxMax.x)
  6310. return false;
  6311. if (boxMin.y > sphereCenter.y + sphereRadius)
  6312. return false;
  6313. if (sphereCenter.y - sphereRadius > boxMax.y)
  6314. return false;
  6315. if (boxMin.z > sphereCenter.z + sphereRadius)
  6316. return false;
  6317. if (sphereCenter.z - sphereRadius > boxMax.z)
  6318. return false;
  6319. return true;
  6320. };
  6321. var getLowestRoot = function (a, b, c, maxR) {
  6322. var determinant = b * b - 4.0 * a * c;
  6323. var result = { root: 0, found: false };
  6324. if (determinant < 0)
  6325. return result;
  6326. var sqrtD = Math.sqrt(determinant);
  6327. var r1 = (-b - sqrtD) / (2.0 * a);
  6328. var r2 = (-b + sqrtD) / (2.0 * a);
  6329. if (r1 > r2) {
  6330. var temp = r2;
  6331. r2 = r1;
  6332. r1 = temp;
  6333. }
  6334. if (r1 > 0 && r1 < maxR) {
  6335. result.root = r1;
  6336. result.found = true;
  6337. return result;
  6338. }
  6339. if (r2 > 0 && r2 < maxR) {
  6340. result.root = r2;
  6341. result.found = true;
  6342. return result;
  6343. }
  6344. return result;
  6345. };
  6346. var Collider = (function () {
  6347. function Collider() {
  6348. this.radius = new BABYLON.Vector3(1, 1, 1);
  6349. this.retry = 0;
  6350. this.basePointWorld = BABYLON.Vector3.Zero();
  6351. this.velocityWorld = BABYLON.Vector3.Zero();
  6352. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6353. this._collisionPoint = BABYLON.Vector3.Zero();
  6354. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6355. this._tempVector = BABYLON.Vector3.Zero();
  6356. this._tempVector2 = BABYLON.Vector3.Zero();
  6357. this._tempVector3 = BABYLON.Vector3.Zero();
  6358. this._tempVector4 = BABYLON.Vector3.Zero();
  6359. this._edge = BABYLON.Vector3.Zero();
  6360. this._baseToVertex = BABYLON.Vector3.Zero();
  6361. this._destinationPoint = BABYLON.Vector3.Zero();
  6362. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6363. this._displacementVector = BABYLON.Vector3.Zero();
  6364. }
  6365. // Methods
  6366. Collider.prototype._initialize = function (source, dir, e) {
  6367. this.velocity = dir;
  6368. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6369. this.basePoint = source;
  6370. source.multiplyToRef(this.radius, this.basePointWorld);
  6371. dir.multiplyToRef(this.radius, this.velocityWorld);
  6372. this.velocityWorldLength = this.velocityWorld.length();
  6373. this.epsilon = e;
  6374. this.collisionFound = false;
  6375. };
  6376. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6377. pa.subtractToRef(point, this._tempVector);
  6378. pb.subtractToRef(point, this._tempVector2);
  6379. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6380. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6381. if (d < 0)
  6382. return false;
  6383. pc.subtractToRef(point, this._tempVector3);
  6384. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6385. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6386. if (d < 0)
  6387. return false;
  6388. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6389. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6390. return d >= 0;
  6391. };
  6392. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6393. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6394. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6395. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6396. return false;
  6397. }
  6398. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6399. return false;
  6400. return true;
  6401. };
  6402. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6403. var t0;
  6404. var embeddedInPlane = false;
  6405. if (!subMesh._trianglePlanes) {
  6406. subMesh._trianglePlanes = [];
  6407. }
  6408. if (!subMesh._trianglePlanes[faceIndex]) {
  6409. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6410. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6411. }
  6412. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6413. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6414. return;
  6415. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6416. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6417. if (normalDotVelocity == 0) {
  6418. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6419. return;
  6420. embeddedInPlane = true;
  6421. t0 = 0;
  6422. }
  6423. else {
  6424. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6425. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6426. if (t0 > t1) {
  6427. var temp = t1;
  6428. t1 = t0;
  6429. t0 = temp;
  6430. }
  6431. if (t0 > 1.0 || t1 < 0.0)
  6432. return;
  6433. if (t0 < 0)
  6434. t0 = 0;
  6435. if (t0 > 1.0)
  6436. t0 = 1.0;
  6437. }
  6438. this._collisionPoint.copyFromFloats(0, 0, 0);
  6439. var found = false;
  6440. var t = 1.0;
  6441. if (!embeddedInPlane) {
  6442. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6443. this.velocity.scaleToRef(t0, this._tempVector);
  6444. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6445. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6446. found = true;
  6447. t = t0;
  6448. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6449. }
  6450. }
  6451. if (!found) {
  6452. var velocitySquaredLength = this.velocity.lengthSquared();
  6453. var a = velocitySquaredLength;
  6454. this.basePoint.subtractToRef(p1, this._tempVector);
  6455. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6456. var c = this._tempVector.lengthSquared() - 1.0;
  6457. var lowestRoot = getLowestRoot(a, b, c, t);
  6458. if (lowestRoot.found) {
  6459. t = lowestRoot.root;
  6460. found = true;
  6461. this._collisionPoint.copyFrom(p1);
  6462. }
  6463. this.basePoint.subtractToRef(p2, this._tempVector);
  6464. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6465. c = this._tempVector.lengthSquared() - 1.0;
  6466. lowestRoot = getLowestRoot(a, b, c, t);
  6467. if (lowestRoot.found) {
  6468. t = lowestRoot.root;
  6469. found = true;
  6470. this._collisionPoint.copyFrom(p2);
  6471. }
  6472. this.basePoint.subtractToRef(p3, this._tempVector);
  6473. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6474. c = this._tempVector.lengthSquared() - 1.0;
  6475. lowestRoot = getLowestRoot(a, b, c, t);
  6476. if (lowestRoot.found) {
  6477. t = lowestRoot.root;
  6478. found = true;
  6479. this._collisionPoint.copyFrom(p3);
  6480. }
  6481. p2.subtractToRef(p1, this._edge);
  6482. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6483. var edgeSquaredLength = this._edge.lengthSquared();
  6484. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6485. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6486. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6487. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6488. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6489. lowestRoot = getLowestRoot(a, b, c, t);
  6490. if (lowestRoot.found) {
  6491. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6492. if (f >= 0.0 && f <= 1.0) {
  6493. t = lowestRoot.root;
  6494. found = true;
  6495. this._edge.scaleInPlace(f);
  6496. p1.addToRef(this._edge, this._collisionPoint);
  6497. }
  6498. }
  6499. p3.subtractToRef(p2, this._edge);
  6500. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6501. edgeSquaredLength = this._edge.lengthSquared();
  6502. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6503. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6504. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6505. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6506. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6507. lowestRoot = getLowestRoot(a, b, c, t);
  6508. if (lowestRoot.found) {
  6509. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6510. if (f >= 0.0 && f <= 1.0) {
  6511. t = lowestRoot.root;
  6512. found = true;
  6513. this._edge.scaleInPlace(f);
  6514. p2.addToRef(this._edge, this._collisionPoint);
  6515. }
  6516. }
  6517. p1.subtractToRef(p3, this._edge);
  6518. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6519. edgeSquaredLength = this._edge.lengthSquared();
  6520. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6521. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6522. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6523. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6524. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6525. lowestRoot = getLowestRoot(a, b, c, t);
  6526. if (lowestRoot.found) {
  6527. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6528. if (f >= 0.0 && f <= 1.0) {
  6529. t = lowestRoot.root;
  6530. found = true;
  6531. this._edge.scaleInPlace(f);
  6532. p3.addToRef(this._edge, this._collisionPoint);
  6533. }
  6534. }
  6535. }
  6536. if (found) {
  6537. var distToCollision = t * this.velocity.length();
  6538. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6539. if (!this.intersectionPoint) {
  6540. this.intersectionPoint = this._collisionPoint.clone();
  6541. }
  6542. else {
  6543. this.intersectionPoint.copyFrom(this._collisionPoint);
  6544. }
  6545. this.nearestDistance = distToCollision;
  6546. this.collisionFound = true;
  6547. this.collidedMesh = subMesh.getMesh();
  6548. }
  6549. }
  6550. };
  6551. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6552. for (var i = indexStart; i < indexEnd; i += 3) {
  6553. var p1 = pts[indices[i] - decal];
  6554. var p2 = pts[indices[i + 1] - decal];
  6555. var p3 = pts[indices[i + 2] - decal];
  6556. this._testTriangle(i, subMesh, p3, p2, p1);
  6557. }
  6558. };
  6559. Collider.prototype._getResponse = function (pos, vel) {
  6560. pos.addToRef(vel, this._destinationPoint);
  6561. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6562. this.basePoint.addToRef(vel, pos);
  6563. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6564. this._slidePlaneNormal.normalize();
  6565. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6566. pos.addInPlace(this._displacementVector);
  6567. this.intersectionPoint.addInPlace(this._displacementVector);
  6568. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6569. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6570. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6571. };
  6572. return Collider;
  6573. })();
  6574. BABYLON.Collider = Collider;
  6575. })(BABYLON || (BABYLON = {}));
  6576. //# sourceMappingURL=babylon.collider.js.map
  6577. var BABYLON;
  6578. (function (BABYLON) {
  6579. var Camera = (function (_super) {
  6580. __extends(Camera, _super);
  6581. function Camera(name, position, scene) {
  6582. _super.call(this, name, scene);
  6583. this.position = position;
  6584. // Members
  6585. this.upVector = BABYLON.Vector3.Up();
  6586. this.orthoLeft = null;
  6587. this.orthoRight = null;
  6588. this.orthoBottom = null;
  6589. this.orthoTop = null;
  6590. this.fov = 0.8;
  6591. this.minZ = 1.0;
  6592. this.maxZ = 10000.0;
  6593. this.inertia = 0.9;
  6594. this.mode = Camera.PERSPECTIVE_CAMERA;
  6595. this.isIntermediate = false;
  6596. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6597. this.subCameras = [];
  6598. this.layerMask = 0xFFFFFFFF;
  6599. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6600. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6601. this._projectionMatrix = new BABYLON.Matrix();
  6602. this._postProcesses = new Array();
  6603. this._postProcessesTakenIndices = [];
  6604. this._activeMeshes = new BABYLON.SmartArray(256);
  6605. scene.addCamera(this);
  6606. if (!scene.activeCamera) {
  6607. scene.activeCamera = this;
  6608. }
  6609. }
  6610. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6611. get: function () {
  6612. return Camera._PERSPECTIVE_CAMERA;
  6613. },
  6614. enumerable: true,
  6615. configurable: true
  6616. });
  6617. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6618. get: function () {
  6619. return Camera._ORTHOGRAPHIC_CAMERA;
  6620. },
  6621. enumerable: true,
  6622. configurable: true
  6623. });
  6624. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6625. get: function () {
  6626. return Camera._FOVMODE_VERTICAL_FIXED;
  6627. },
  6628. enumerable: true,
  6629. configurable: true
  6630. });
  6631. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6632. get: function () {
  6633. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6634. },
  6635. enumerable: true,
  6636. configurable: true
  6637. });
  6638. Camera.prototype.getActiveMeshes = function () {
  6639. return this._activeMeshes;
  6640. };
  6641. Camera.prototype.isActiveMesh = function (mesh) {
  6642. return (this._activeMeshes.indexOf(mesh) !== -1);
  6643. };
  6644. //Cache
  6645. Camera.prototype._initCache = function () {
  6646. _super.prototype._initCache.call(this);
  6647. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6648. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6649. this._cache.mode = undefined;
  6650. this._cache.minZ = undefined;
  6651. this._cache.maxZ = undefined;
  6652. this._cache.fov = undefined;
  6653. this._cache.aspectRatio = undefined;
  6654. this._cache.orthoLeft = undefined;
  6655. this._cache.orthoRight = undefined;
  6656. this._cache.orthoBottom = undefined;
  6657. this._cache.orthoTop = undefined;
  6658. this._cache.renderWidth = undefined;
  6659. this._cache.renderHeight = undefined;
  6660. };
  6661. Camera.prototype._updateCache = function (ignoreParentClass) {
  6662. if (!ignoreParentClass) {
  6663. _super.prototype._updateCache.call(this);
  6664. }
  6665. var engine = this.getEngine();
  6666. this._cache.position.copyFrom(this.position);
  6667. this._cache.upVector.copyFrom(this.upVector);
  6668. this._cache.mode = this.mode;
  6669. this._cache.minZ = this.minZ;
  6670. this._cache.maxZ = this.maxZ;
  6671. this._cache.fov = this.fov;
  6672. this._cache.aspectRatio = engine.getAspectRatio(this);
  6673. this._cache.orthoLeft = this.orthoLeft;
  6674. this._cache.orthoRight = this.orthoRight;
  6675. this._cache.orthoBottom = this.orthoBottom;
  6676. this._cache.orthoTop = this.orthoTop;
  6677. this._cache.renderWidth = engine.getRenderWidth();
  6678. this._cache.renderHeight = engine.getRenderHeight();
  6679. };
  6680. Camera.prototype._updateFromScene = function () {
  6681. this.updateCache();
  6682. this._update();
  6683. };
  6684. // Synchronized
  6685. Camera.prototype._isSynchronized = function () {
  6686. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6687. };
  6688. Camera.prototype._isSynchronizedViewMatrix = function () {
  6689. if (!_super.prototype._isSynchronized.call(this))
  6690. return false;
  6691. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6692. };
  6693. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6694. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6695. if (!check) {
  6696. return false;
  6697. }
  6698. var engine = this.getEngine();
  6699. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6700. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6701. }
  6702. else {
  6703. 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();
  6704. }
  6705. return check;
  6706. };
  6707. // Controls
  6708. Camera.prototype.attachControl = function (element) {
  6709. };
  6710. Camera.prototype.detachControl = function (element) {
  6711. };
  6712. Camera.prototype._update = function () {
  6713. };
  6714. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6715. if (insertAt === void 0) { insertAt = null; }
  6716. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6717. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6718. return 0;
  6719. }
  6720. if (insertAt == null || insertAt < 0) {
  6721. this._postProcesses.push(postProcess);
  6722. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6723. return this._postProcesses.length - 1;
  6724. }
  6725. var add = 0;
  6726. if (this._postProcesses[insertAt]) {
  6727. var start = this._postProcesses.length - 1;
  6728. for (var i = start; i >= insertAt + 1; --i) {
  6729. this._postProcesses[i + 1] = this._postProcesses[i];
  6730. }
  6731. add = 1;
  6732. }
  6733. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6734. if (this._postProcessesTakenIndices[i] < insertAt) {
  6735. continue;
  6736. }
  6737. start = this._postProcessesTakenIndices.length - 1;
  6738. for (var j = start; j >= i; --j) {
  6739. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6740. }
  6741. this._postProcessesTakenIndices[i] = insertAt;
  6742. break;
  6743. }
  6744. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6745. this._postProcessesTakenIndices.push(insertAt);
  6746. }
  6747. var result = insertAt + add;
  6748. this._postProcesses[result] = postProcess;
  6749. return result;
  6750. };
  6751. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6752. if (atIndices === void 0) { atIndices = null; }
  6753. var result = [];
  6754. if (!atIndices) {
  6755. var length = this._postProcesses.length;
  6756. for (var i = 0; i < length; i++) {
  6757. if (this._postProcesses[i] !== postProcess) {
  6758. continue;
  6759. }
  6760. delete this._postProcesses[i];
  6761. var index = this._postProcessesTakenIndices.indexOf(i);
  6762. this._postProcessesTakenIndices.splice(index, 1);
  6763. }
  6764. }
  6765. else {
  6766. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6767. for (i = 0; i < atIndices.length; i++) {
  6768. var foundPostProcess = this._postProcesses[atIndices[i]];
  6769. if (foundPostProcess !== postProcess) {
  6770. result.push(i);
  6771. continue;
  6772. }
  6773. delete this._postProcesses[atIndices[i]];
  6774. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6775. this._postProcessesTakenIndices.splice(index, 1);
  6776. }
  6777. }
  6778. return result;
  6779. };
  6780. Camera.prototype.getWorldMatrix = function () {
  6781. if (!this._worldMatrix) {
  6782. this._worldMatrix = BABYLON.Matrix.Identity();
  6783. }
  6784. var viewMatrix = this.getViewMatrix();
  6785. viewMatrix.invertToRef(this._worldMatrix);
  6786. return this._worldMatrix;
  6787. };
  6788. Camera.prototype._getViewMatrix = function () {
  6789. return BABYLON.Matrix.Identity();
  6790. };
  6791. Camera.prototype.getViewMatrix = function () {
  6792. this._computedViewMatrix = this._computeViewMatrix();
  6793. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6794. return this._computedViewMatrix;
  6795. }
  6796. if (!this._worldMatrix) {
  6797. this._worldMatrix = BABYLON.Matrix.Identity();
  6798. }
  6799. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6800. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6801. this._computedViewMatrix.invert();
  6802. this._currentRenderId = this.getScene().getRenderId();
  6803. return this._computedViewMatrix;
  6804. };
  6805. Camera.prototype._computeViewMatrix = function (force) {
  6806. if (!force && this._isSynchronizedViewMatrix()) {
  6807. return this._computedViewMatrix;
  6808. }
  6809. this._computedViewMatrix = this._getViewMatrix();
  6810. if (!this.parent || !this.parent.getWorldMatrix) {
  6811. this._currentRenderId = this.getScene().getRenderId();
  6812. }
  6813. return this._computedViewMatrix;
  6814. };
  6815. Camera.prototype.getProjectionMatrix = function (force) {
  6816. if (!force && this._isSynchronizedProjectionMatrix()) {
  6817. return this._projectionMatrix;
  6818. }
  6819. var engine = this.getEngine();
  6820. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6821. if (this.minZ <= 0) {
  6822. this.minZ = 0.1;
  6823. }
  6824. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6825. return this._projectionMatrix;
  6826. }
  6827. var halfWidth = engine.getRenderWidth() / 2.0;
  6828. var halfHeight = engine.getRenderHeight() / 2.0;
  6829. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6830. return this._projectionMatrix;
  6831. };
  6832. Camera.prototype.dispose = function () {
  6833. // Remove from scene
  6834. this.getScene().removeCamera(this);
  6835. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6836. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6837. }
  6838. };
  6839. // Statics
  6840. Camera._PERSPECTIVE_CAMERA = 0;
  6841. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6842. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6843. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6844. return Camera;
  6845. })(BABYLON.Node);
  6846. BABYLON.Camera = Camera;
  6847. })(BABYLON || (BABYLON = {}));
  6848. //# sourceMappingURL=babylon.camera.js.map
  6849. var BABYLON;
  6850. (function (BABYLON) {
  6851. var TargetCamera = (function (_super) {
  6852. __extends(TargetCamera, _super);
  6853. function TargetCamera(name, position, scene) {
  6854. _super.call(this, name, position, scene);
  6855. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6856. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6857. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6858. this.speed = 2.0;
  6859. this.noRotationConstraint = false;
  6860. this.lockedTarget = null;
  6861. this._currentTarget = BABYLON.Vector3.Zero();
  6862. this._viewMatrix = BABYLON.Matrix.Zero();
  6863. this._camMatrix = BABYLON.Matrix.Zero();
  6864. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6865. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6866. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6867. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6868. this._lookAtTemp = BABYLON.Matrix.Zero();
  6869. this._tempMatrix = BABYLON.Matrix.Zero();
  6870. }
  6871. TargetCamera.prototype._getLockedTargetPosition = function () {
  6872. if (!this.lockedTarget) {
  6873. return null;
  6874. }
  6875. return this.lockedTarget.position || this.lockedTarget;
  6876. };
  6877. // Cache
  6878. TargetCamera.prototype._initCache = function () {
  6879. _super.prototype._initCache.call(this);
  6880. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6881. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6882. };
  6883. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6884. if (!ignoreParentClass) {
  6885. _super.prototype._updateCache.call(this);
  6886. }
  6887. var lockedTargetPosition = this._getLockedTargetPosition();
  6888. if (!lockedTargetPosition) {
  6889. this._cache.lockedTarget = null;
  6890. }
  6891. else {
  6892. if (!this._cache.lockedTarget) {
  6893. this._cache.lockedTarget = lockedTargetPosition.clone();
  6894. }
  6895. else {
  6896. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6897. }
  6898. }
  6899. this._cache.rotation.copyFrom(this.rotation);
  6900. };
  6901. // Synchronized
  6902. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6903. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6904. return false;
  6905. }
  6906. var lockedTargetPosition = this._getLockedTargetPosition();
  6907. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6908. };
  6909. // Methods
  6910. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6911. var engine = this.getEngine();
  6912. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6913. };
  6914. // Target
  6915. TargetCamera.prototype.setTarget = function (target) {
  6916. this.upVector.normalize();
  6917. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6918. this._camMatrix.invert();
  6919. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6920. var vDir = target.subtract(this.position);
  6921. if (vDir.x >= 0.0) {
  6922. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6923. }
  6924. else {
  6925. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6926. }
  6927. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6928. if (isNaN(this.rotation.x)) {
  6929. this.rotation.x = 0;
  6930. }
  6931. if (isNaN(this.rotation.y)) {
  6932. this.rotation.y = 0;
  6933. }
  6934. if (isNaN(this.rotation.z)) {
  6935. this.rotation.z = 0;
  6936. }
  6937. };
  6938. TargetCamera.prototype.getTarget = function () {
  6939. return this._currentTarget;
  6940. };
  6941. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6942. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6943. };
  6944. TargetCamera.prototype._updatePosition = function () {
  6945. this.position.addInPlace(this.cameraDirection);
  6946. };
  6947. TargetCamera.prototype._update = function () {
  6948. var needToMove = this._decideIfNeedsToMove();
  6949. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6950. // Move
  6951. if (needToMove) {
  6952. this._updatePosition();
  6953. }
  6954. // Rotate
  6955. if (needToRotate) {
  6956. this.rotation.x += this.cameraRotation.x;
  6957. this.rotation.y += this.cameraRotation.y;
  6958. if (!this.noRotationConstraint) {
  6959. var limit = (Math.PI / 2) * 0.95;
  6960. if (this.rotation.x > limit)
  6961. this.rotation.x = limit;
  6962. if (this.rotation.x < -limit)
  6963. this.rotation.x = -limit;
  6964. }
  6965. }
  6966. // Inertia
  6967. if (needToMove) {
  6968. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6969. this.cameraDirection.x = 0;
  6970. }
  6971. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6972. this.cameraDirection.y = 0;
  6973. }
  6974. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6975. this.cameraDirection.z = 0;
  6976. }
  6977. this.cameraDirection.scaleInPlace(this.inertia);
  6978. }
  6979. if (needToRotate) {
  6980. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6981. this.cameraRotation.x = 0;
  6982. }
  6983. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6984. this.cameraRotation.y = 0;
  6985. }
  6986. this.cameraRotation.scaleInPlace(this.inertia);
  6987. }
  6988. };
  6989. TargetCamera.prototype._getViewMatrix = function () {
  6990. if (!this.lockedTarget) {
  6991. // Compute
  6992. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6993. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6994. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6995. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6996. this._lookAtTemp.invert();
  6997. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6998. }
  6999. else {
  7000. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7001. }
  7002. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7003. // Computing target and final matrix
  7004. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7005. }
  7006. else {
  7007. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7008. }
  7009. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7010. return this._viewMatrix;
  7011. };
  7012. return TargetCamera;
  7013. })(BABYLON.Camera);
  7014. BABYLON.TargetCamera = TargetCamera;
  7015. })(BABYLON || (BABYLON = {}));
  7016. //# sourceMappingURL=babylon.targetCamera.js.map
  7017. var BABYLON;
  7018. (function (BABYLON) {
  7019. var FollowCamera = (function (_super) {
  7020. __extends(FollowCamera, _super);
  7021. function FollowCamera(name, position, scene) {
  7022. _super.call(this, name, position, scene);
  7023. this.radius = 12;
  7024. this.rotationOffset = 0;
  7025. this.heightOffset = 4;
  7026. this.cameraAcceleration = 0.05;
  7027. this.maxCameraSpeed = 20;
  7028. }
  7029. FollowCamera.prototype.getRadians = function (degrees) {
  7030. return degrees * Math.PI / 180;
  7031. };
  7032. FollowCamera.prototype.follow = function (cameraTarget) {
  7033. if (!cameraTarget)
  7034. return;
  7035. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7036. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7037. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7038. var dx = targetX - this.position.x;
  7039. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7040. var dz = (targetZ) - this.position.z;
  7041. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7042. var vy = dy * this.cameraAcceleration;
  7043. var vz = dz * this.cameraAcceleration * 2;
  7044. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7045. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7046. }
  7047. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7048. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7049. }
  7050. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7051. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7052. }
  7053. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7054. this.setTarget(cameraTarget.position);
  7055. };
  7056. FollowCamera.prototype._update = function () {
  7057. _super.prototype._update.call(this);
  7058. this.follow(this.target);
  7059. };
  7060. return FollowCamera;
  7061. })(BABYLON.TargetCamera);
  7062. BABYLON.FollowCamera = FollowCamera;
  7063. })(BABYLON || (BABYLON = {}));
  7064. //# sourceMappingURL=babylon.followCamera.js.map
  7065. var BABYLON;
  7066. (function (BABYLON) {
  7067. var FreeCamera = (function (_super) {
  7068. __extends(FreeCamera, _super);
  7069. function FreeCamera(name, position, scene) {
  7070. _super.call(this, name, position, scene);
  7071. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7072. this.keysUp = [38];
  7073. this.keysDown = [40];
  7074. this.keysLeft = [37];
  7075. this.keysRight = [39];
  7076. this.checkCollisions = false;
  7077. this.applyGravity = false;
  7078. this.angularSensibility = 2000.0;
  7079. this._keys = [];
  7080. this._collider = new BABYLON.Collider();
  7081. this._needMoveForGravity = true;
  7082. this._oldPosition = BABYLON.Vector3.Zero();
  7083. this._diffPosition = BABYLON.Vector3.Zero();
  7084. this._newPosition = BABYLON.Vector3.Zero();
  7085. }
  7086. // Controls
  7087. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7088. var _this = this;
  7089. var previousPosition;
  7090. var engine = this.getEngine();
  7091. if (this._attachedElement) {
  7092. return;
  7093. }
  7094. this._attachedElement = element;
  7095. if (this._onMouseDown === undefined) {
  7096. this._onMouseDown = function (evt) {
  7097. previousPosition = {
  7098. x: evt.clientX,
  7099. y: evt.clientY
  7100. };
  7101. if (!noPreventDefault) {
  7102. evt.preventDefault();
  7103. }
  7104. };
  7105. this._onMouseUp = function (evt) {
  7106. previousPosition = null;
  7107. if (!noPreventDefault) {
  7108. evt.preventDefault();
  7109. }
  7110. };
  7111. this._onMouseOut = function (evt) {
  7112. previousPosition = null;
  7113. _this._keys = [];
  7114. if (!noPreventDefault) {
  7115. evt.preventDefault();
  7116. }
  7117. };
  7118. this._onMouseMove = function (evt) {
  7119. if (!previousPosition && !engine.isPointerLock) {
  7120. return;
  7121. }
  7122. var offsetX;
  7123. var offsetY;
  7124. if (!engine.isPointerLock) {
  7125. offsetX = evt.clientX - previousPosition.x;
  7126. offsetY = evt.clientY - previousPosition.y;
  7127. }
  7128. else {
  7129. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7130. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7131. }
  7132. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7133. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7134. previousPosition = {
  7135. x: evt.clientX,
  7136. y: evt.clientY
  7137. };
  7138. if (!noPreventDefault) {
  7139. evt.preventDefault();
  7140. }
  7141. };
  7142. this._onKeyDown = function (evt) {
  7143. 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) {
  7144. var index = _this._keys.indexOf(evt.keyCode);
  7145. if (index === -1) {
  7146. _this._keys.push(evt.keyCode);
  7147. }
  7148. if (!noPreventDefault) {
  7149. evt.preventDefault();
  7150. }
  7151. }
  7152. };
  7153. this._onKeyUp = function (evt) {
  7154. 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) {
  7155. var index = _this._keys.indexOf(evt.keyCode);
  7156. if (index >= 0) {
  7157. _this._keys.splice(index, 1);
  7158. }
  7159. if (!noPreventDefault) {
  7160. evt.preventDefault();
  7161. }
  7162. }
  7163. };
  7164. this._onLostFocus = function () {
  7165. _this._keys = [];
  7166. };
  7167. this._reset = function () {
  7168. _this._keys = [];
  7169. previousPosition = null;
  7170. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7171. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7172. };
  7173. }
  7174. element.addEventListener("mousedown", this._onMouseDown, false);
  7175. element.addEventListener("mouseup", this._onMouseUp, false);
  7176. element.addEventListener("mouseout", this._onMouseOut, false);
  7177. element.addEventListener("mousemove", this._onMouseMove, false);
  7178. BABYLON.Tools.RegisterTopRootEvents([
  7179. { name: "keydown", handler: this._onKeyDown },
  7180. { name: "keyup", handler: this._onKeyUp },
  7181. { name: "blur", handler: this._onLostFocus }
  7182. ]);
  7183. };
  7184. FreeCamera.prototype.detachControl = function (element) {
  7185. if (this._attachedElement != element) {
  7186. return;
  7187. }
  7188. element.removeEventListener("mousedown", this._onMouseDown);
  7189. element.removeEventListener("mouseup", this._onMouseUp);
  7190. element.removeEventListener("mouseout", this._onMouseOut);
  7191. element.removeEventListener("mousemove", this._onMouseMove);
  7192. BABYLON.Tools.UnregisterTopRootEvents([
  7193. { name: "keydown", handler: this._onKeyDown },
  7194. { name: "keyup", handler: this._onKeyUp },
  7195. { name: "blur", handler: this._onLostFocus }
  7196. ]);
  7197. this._attachedElement = null;
  7198. if (this._reset) {
  7199. this._reset();
  7200. }
  7201. };
  7202. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7203. var globalPosition;
  7204. if (this.parent) {
  7205. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7206. }
  7207. else {
  7208. globalPosition = this.position;
  7209. }
  7210. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7211. this._collider.radius = this.ellipsoid;
  7212. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7213. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7214. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7215. this.position.addInPlace(this._diffPosition);
  7216. if (this.onCollide) {
  7217. this.onCollide(this._collider.collidedMesh);
  7218. }
  7219. }
  7220. };
  7221. FreeCamera.prototype._checkInputs = function () {
  7222. if (!this._localDirection) {
  7223. this._localDirection = BABYLON.Vector3.Zero();
  7224. this._transformedDirection = BABYLON.Vector3.Zero();
  7225. }
  7226. for (var index = 0; index < this._keys.length; index++) {
  7227. var keyCode = this._keys[index];
  7228. var speed = this._computeLocalCameraSpeed();
  7229. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7230. this._localDirection.copyFromFloats(-speed, 0, 0);
  7231. }
  7232. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7233. this._localDirection.copyFromFloats(0, 0, speed);
  7234. }
  7235. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7236. this._localDirection.copyFromFloats(speed, 0, 0);
  7237. }
  7238. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7239. this._localDirection.copyFromFloats(0, 0, -speed);
  7240. }
  7241. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7242. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7243. this.cameraDirection.addInPlace(this._transformedDirection);
  7244. }
  7245. };
  7246. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7247. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7248. };
  7249. FreeCamera.prototype._updatePosition = function () {
  7250. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7251. this._collideWithWorld(this.cameraDirection);
  7252. if (this.applyGravity) {
  7253. var oldPosition = this.position;
  7254. this._collideWithWorld(this.getScene().gravity);
  7255. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7256. }
  7257. }
  7258. else {
  7259. this.position.addInPlace(this.cameraDirection);
  7260. }
  7261. };
  7262. FreeCamera.prototype._update = function () {
  7263. this._checkInputs();
  7264. _super.prototype._update.call(this);
  7265. };
  7266. return FreeCamera;
  7267. })(BABYLON.TargetCamera);
  7268. BABYLON.FreeCamera = FreeCamera;
  7269. })(BABYLON || (BABYLON = {}));
  7270. //# sourceMappingURL=babylon.freeCamera.js.map
  7271. var BABYLON;
  7272. (function (BABYLON) {
  7273. // We're mainly based on the logic defined into the FreeCamera code
  7274. var TouchCamera = (function (_super) {
  7275. __extends(TouchCamera, _super);
  7276. function TouchCamera(name, position, scene) {
  7277. _super.call(this, name, position, scene);
  7278. this._offsetX = null;
  7279. this._offsetY = null;
  7280. this._pointerCount = 0;
  7281. this._pointerPressed = [];
  7282. this.angularSensibility = 200000.0;
  7283. this.moveSensibility = 500.0;
  7284. }
  7285. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7286. var _this = this;
  7287. var previousPosition;
  7288. if (this._attachedCanvas) {
  7289. return;
  7290. }
  7291. this._attachedCanvas = canvas;
  7292. if (this._onPointerDown === undefined) {
  7293. this._onPointerDown = function (evt) {
  7294. if (!noPreventDefault) {
  7295. evt.preventDefault();
  7296. }
  7297. _this._pointerPressed.push(evt.pointerId);
  7298. if (_this._pointerPressed.length !== 1) {
  7299. return;
  7300. }
  7301. previousPosition = {
  7302. x: evt.clientX,
  7303. y: evt.clientY
  7304. };
  7305. };
  7306. this._onPointerUp = function (evt) {
  7307. if (!noPreventDefault) {
  7308. evt.preventDefault();
  7309. }
  7310. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7311. if (index === -1) {
  7312. return;
  7313. }
  7314. _this._pointerPressed.splice(index, 1);
  7315. if (index != 0) {
  7316. return;
  7317. }
  7318. previousPosition = null;
  7319. _this._offsetX = null;
  7320. _this._offsetY = null;
  7321. };
  7322. this._onPointerMove = function (evt) {
  7323. if (!noPreventDefault) {
  7324. evt.preventDefault();
  7325. }
  7326. if (!previousPosition) {
  7327. return;
  7328. }
  7329. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7330. if (index != 0) {
  7331. return;
  7332. }
  7333. _this._offsetX = evt.clientX - previousPosition.x;
  7334. _this._offsetY = -(evt.clientY - previousPosition.y);
  7335. };
  7336. this._onLostFocus = function () {
  7337. _this._offsetX = null;
  7338. _this._offsetY = null;
  7339. };
  7340. }
  7341. canvas.addEventListener("pointerdown", this._onPointerDown);
  7342. canvas.addEventListener("pointerup", this._onPointerUp);
  7343. canvas.addEventListener("pointerout", this._onPointerUp);
  7344. canvas.addEventListener("pointermove", this._onPointerMove);
  7345. BABYLON.Tools.RegisterTopRootEvents([
  7346. { name: "blur", handler: this._onLostFocus }
  7347. ]);
  7348. };
  7349. TouchCamera.prototype.detachControl = function (canvas) {
  7350. if (this._attachedCanvas != canvas) {
  7351. return;
  7352. }
  7353. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7354. canvas.removeEventListener("pointerup", this._onPointerUp);
  7355. canvas.removeEventListener("pointerout", this._onPointerUp);
  7356. canvas.removeEventListener("pointermove", this._onPointerMove);
  7357. BABYLON.Tools.UnregisterTopRootEvents([
  7358. { name: "blur", handler: this._onLostFocus }
  7359. ]);
  7360. this._attachedCanvas = null;
  7361. };
  7362. TouchCamera.prototype._checkInputs = function () {
  7363. if (!this._offsetX) {
  7364. return;
  7365. }
  7366. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7367. if (this._pointerPressed.length > 1) {
  7368. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7369. }
  7370. else {
  7371. var speed = this._computeLocalCameraSpeed();
  7372. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7373. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7374. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7375. }
  7376. };
  7377. return TouchCamera;
  7378. })(BABYLON.FreeCamera);
  7379. BABYLON.TouchCamera = TouchCamera;
  7380. })(BABYLON || (BABYLON = {}));
  7381. //# sourceMappingURL=babylon.touchCamera.js.map
  7382. var BABYLON;
  7383. (function (BABYLON) {
  7384. // We're mainly based on the logic defined into the FreeCamera code
  7385. var DeviceOrientationCamera = (function (_super) {
  7386. __extends(DeviceOrientationCamera, _super);
  7387. function DeviceOrientationCamera(name, position, scene) {
  7388. var _this = this;
  7389. _super.call(this, name, position, scene);
  7390. this._offsetX = null;
  7391. this._offsetY = null;
  7392. this._orientationGamma = 0;
  7393. this._orientationBeta = 0;
  7394. this._initialOrientationGamma = 0;
  7395. this._initialOrientationBeta = 0;
  7396. this.angularSensibility = 10000.0;
  7397. this.moveSensibility = 50.0;
  7398. window.addEventListener("resize", function () {
  7399. _this._initialOrientationGamma = null;
  7400. }, false);
  7401. }
  7402. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7403. var _this = this;
  7404. if (this._attachedCanvas) {
  7405. return;
  7406. }
  7407. this._attachedCanvas = canvas;
  7408. if (!this._orientationChanged) {
  7409. this._orientationChanged = function (evt) {
  7410. if (!_this._initialOrientationGamma) {
  7411. _this._initialOrientationGamma = evt.gamma;
  7412. _this._initialOrientationBeta = evt.beta;
  7413. }
  7414. _this._orientationGamma = evt.gamma;
  7415. _this._orientationBeta = evt.beta;
  7416. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7417. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7418. };
  7419. }
  7420. window.addEventListener("deviceorientation", this._orientationChanged);
  7421. };
  7422. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7423. if (this._attachedCanvas != canvas) {
  7424. return;
  7425. }
  7426. window.removeEventListener("deviceorientation", this._orientationChanged);
  7427. this._attachedCanvas = null;
  7428. this._orientationGamma = 0;
  7429. this._orientationBeta = 0;
  7430. this._initialOrientationGamma = 0;
  7431. this._initialOrientationBeta = 0;
  7432. };
  7433. DeviceOrientationCamera.prototype._checkInputs = function () {
  7434. if (!this._offsetX) {
  7435. return;
  7436. }
  7437. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7438. var speed = this._computeLocalCameraSpeed();
  7439. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7440. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7441. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7442. };
  7443. return DeviceOrientationCamera;
  7444. })(BABYLON.FreeCamera);
  7445. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7446. })(BABYLON || (BABYLON = {}));
  7447. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7448. var BABYLON;
  7449. (function (BABYLON) {
  7450. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7451. var ArcRotateCamera = (function (_super) {
  7452. __extends(ArcRotateCamera, _super);
  7453. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7454. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7455. this.alpha = alpha;
  7456. this.beta = beta;
  7457. this.radius = radius;
  7458. this.target = target;
  7459. this.inertialAlphaOffset = 0;
  7460. this.inertialBetaOffset = 0;
  7461. this.inertialRadiusOffset = 0;
  7462. this.lowerAlphaLimit = null;
  7463. this.upperAlphaLimit = null;
  7464. this.lowerBetaLimit = 0.01;
  7465. this.upperBetaLimit = Math.PI;
  7466. this.lowerRadiusLimit = null;
  7467. this.upperRadiusLimit = null;
  7468. this.angularSensibility = 1000.0;
  7469. this.wheelPrecision = 3.0;
  7470. this.keysUp = [38];
  7471. this.keysDown = [40];
  7472. this.keysLeft = [37];
  7473. this.keysRight = [39];
  7474. this.zoomOnFactor = 1;
  7475. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7476. this._keys = [];
  7477. this._viewMatrix = new BABYLON.Matrix();
  7478. this.checkCollisions = false;
  7479. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7480. this._collider = new BABYLON.Collider();
  7481. this._previousPosition = BABYLON.Vector3.Zero();
  7482. this._collisionVelocity = BABYLON.Vector3.Zero();
  7483. this._newPosition = BABYLON.Vector3.Zero();
  7484. // Pinch
  7485. // value for pinch step scaling
  7486. // set to 20 by default
  7487. this.pinchPrecision = 20;
  7488. this.getViewMatrix();
  7489. }
  7490. ArcRotateCamera.prototype._getTargetPosition = function () {
  7491. return this.target.position || this.target;
  7492. };
  7493. // Cache
  7494. ArcRotateCamera.prototype._initCache = function () {
  7495. _super.prototype._initCache.call(this);
  7496. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7497. this._cache.alpha = undefined;
  7498. this._cache.beta = undefined;
  7499. this._cache.radius = undefined;
  7500. this._cache.targetScreenOffset = undefined;
  7501. };
  7502. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7503. if (!ignoreParentClass) {
  7504. _super.prototype._updateCache.call(this);
  7505. }
  7506. this._cache.target.copyFrom(this._getTargetPosition());
  7507. this._cache.alpha = this.alpha;
  7508. this._cache.beta = this.beta;
  7509. this._cache.radius = this.radius;
  7510. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7511. };
  7512. // Synchronized
  7513. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7514. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7515. return false;
  7516. 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);
  7517. };
  7518. // Methods
  7519. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7520. var _this = this;
  7521. var previousPosition;
  7522. var pointerId;
  7523. // to know if pinch started
  7524. var pinchStarted = false;
  7525. // two pinch point on X
  7526. // that will use for find if user action is pinch open or pinch close
  7527. var pinchPointX1, pinchPointX2;
  7528. if (this._attachedElement) {
  7529. return;
  7530. }
  7531. this._attachedElement = element;
  7532. var engine = this.getEngine();
  7533. if (this._onPointerDown === undefined) {
  7534. this._onPointerDown = function (evt) {
  7535. if (pointerId) {
  7536. return;
  7537. }
  7538. pointerId = evt.pointerId;
  7539. previousPosition = {
  7540. x: evt.clientX,
  7541. y: evt.clientY
  7542. };
  7543. if (!noPreventDefault) {
  7544. evt.preventDefault();
  7545. }
  7546. };
  7547. this._onPointerUp = function (evt) {
  7548. previousPosition = null;
  7549. pointerId = null;
  7550. if (!noPreventDefault) {
  7551. evt.preventDefault();
  7552. }
  7553. };
  7554. this._onPointerMove = function (evt) {
  7555. if (!previousPosition) {
  7556. return;
  7557. }
  7558. if (pointerId !== evt.pointerId) {
  7559. return;
  7560. }
  7561. // return pinch is started
  7562. if (pinchStarted) {
  7563. return;
  7564. }
  7565. var offsetX = evt.clientX - previousPosition.x;
  7566. var offsetY = evt.clientY - previousPosition.y;
  7567. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7568. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7569. previousPosition = {
  7570. x: evt.clientX,
  7571. y: evt.clientY
  7572. };
  7573. if (!noPreventDefault) {
  7574. evt.preventDefault();
  7575. }
  7576. };
  7577. this._onMouseMove = function (evt) {
  7578. if (!engine.isPointerLock) {
  7579. return;
  7580. }
  7581. // return pinch is started
  7582. if (pinchStarted) {
  7583. return;
  7584. }
  7585. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7586. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7587. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7588. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7589. if (!noPreventDefault) {
  7590. evt.preventDefault();
  7591. }
  7592. };
  7593. this._wheel = function (event) {
  7594. var delta = 0;
  7595. if (event.wheelDelta) {
  7596. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7597. }
  7598. else if (event.detail) {
  7599. delta = -event.detail / _this.wheelPrecision;
  7600. }
  7601. if (delta)
  7602. _this.inertialRadiusOffset += delta;
  7603. if (event.preventDefault) {
  7604. if (!noPreventDefault) {
  7605. event.preventDefault();
  7606. }
  7607. }
  7608. };
  7609. this._onKeyDown = function (evt) {
  7610. 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) {
  7611. var index = _this._keys.indexOf(evt.keyCode);
  7612. if (index === -1) {
  7613. _this._keys.push(evt.keyCode);
  7614. }
  7615. if (evt.preventDefault) {
  7616. if (!noPreventDefault) {
  7617. evt.preventDefault();
  7618. }
  7619. }
  7620. }
  7621. };
  7622. this._onKeyUp = function (evt) {
  7623. 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) {
  7624. var index = _this._keys.indexOf(evt.keyCode);
  7625. if (index >= 0) {
  7626. _this._keys.splice(index, 1);
  7627. }
  7628. if (evt.preventDefault) {
  7629. if (!noPreventDefault) {
  7630. evt.preventDefault();
  7631. }
  7632. }
  7633. }
  7634. };
  7635. this._onLostFocus = function () {
  7636. _this._keys = [];
  7637. pointerId = null;
  7638. };
  7639. this._onGestureStart = function (e) {
  7640. if (window.MSGesture === undefined) {
  7641. return;
  7642. }
  7643. if (!_this._MSGestureHandler) {
  7644. _this._MSGestureHandler = new MSGesture();
  7645. _this._MSGestureHandler.target = element;
  7646. }
  7647. _this._MSGestureHandler.addPointer(e.pointerId);
  7648. };
  7649. this._onGesture = function (e) {
  7650. _this.radius *= e.scale;
  7651. if (e.preventDefault) {
  7652. if (!noPreventDefault) {
  7653. e.stopPropagation();
  7654. e.preventDefault();
  7655. }
  7656. }
  7657. };
  7658. this._reset = function () {
  7659. _this._keys = [];
  7660. _this.inertialAlphaOffset = 0;
  7661. _this.inertialBetaOffset = 0;
  7662. _this.inertialRadiusOffset = 0;
  7663. previousPosition = null;
  7664. pointerId = null;
  7665. };
  7666. this._touchStart = function (event) {
  7667. if (event.touches.length === 2) {
  7668. //-- start pinch if two fingers on the screen
  7669. pinchStarted = true;
  7670. _this._pinchStart(event);
  7671. }
  7672. };
  7673. this._touchMove = function (event) {
  7674. if (pinchStarted) {
  7675. //-- make scaling
  7676. _this._pinchMove(event);
  7677. }
  7678. };
  7679. this._touchEnd = function (event) {
  7680. if (pinchStarted) {
  7681. //-- end of pinch
  7682. _this._pinchEnd(event);
  7683. }
  7684. };
  7685. this._pinchStart = function (event) {
  7686. // save origin touch point
  7687. pinchPointX1 = event.touches[0].clientX;
  7688. pinchPointX2 = event.touches[1].clientX;
  7689. // block the camera
  7690. // if not it rotate around target during pinch
  7691. pinchStarted = true;
  7692. };
  7693. this._pinchMove = function (event) {
  7694. // variable for new camera's radius
  7695. var delta = 0;
  7696. // variables to know if pinch open or pinch close
  7697. var direction = 1;
  7698. var distanceXOrigine, distanceXNow;
  7699. if (event.touches.length !== 2)
  7700. return;
  7701. // calculate absolute distances of the two fingers
  7702. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7703. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7704. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7705. if (distanceXNow < distanceXOrigine) {
  7706. direction = -1;
  7707. }
  7708. // calculate new radius
  7709. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7710. // set new radius
  7711. _this.inertialRadiusOffset -= delta;
  7712. // save origin touch point
  7713. pinchPointX1 = event.touches[0].clientX;
  7714. pinchPointX2 = event.touches[1].clientX;
  7715. };
  7716. this._pinchEnd = function (event) {
  7717. // cancel pinch and deblock camera rotation
  7718. pinchStarted = false;
  7719. };
  7720. }
  7721. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7722. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7723. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7724. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7725. element.addEventListener("mousemove", this._onMouseMove, false);
  7726. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7727. element.addEventListener("MSGestureChange", this._onGesture, false);
  7728. element.addEventListener('mousewheel', this._wheel, false);
  7729. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7730. // pinch
  7731. element.addEventListener('touchstart', this._touchStart, false);
  7732. element.addEventListener('touchmove', this._touchMove, false);
  7733. element.addEventListener('touchend', this._touchEnd, false);
  7734. BABYLON.Tools.RegisterTopRootEvents([
  7735. { name: "keydown", handler: this._onKeyDown },
  7736. { name: "keyup", handler: this._onKeyUp },
  7737. { name: "blur", handler: this._onLostFocus }
  7738. ]);
  7739. };
  7740. ArcRotateCamera.prototype.detachControl = function (element) {
  7741. if (this._attachedElement != element) {
  7742. return;
  7743. }
  7744. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7745. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7746. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7747. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7748. element.removeEventListener("mousemove", this._onMouseMove);
  7749. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7750. element.removeEventListener("MSGestureChange", this._onGesture);
  7751. element.removeEventListener('mousewheel', this._wheel);
  7752. element.removeEventListener('DOMMouseScroll', this._wheel);
  7753. // pinch
  7754. element.removeEventListener('touchstart', this._touchStart);
  7755. element.removeEventListener('touchmove', this._touchMove);
  7756. element.removeEventListener('touchend', this._touchEnd);
  7757. BABYLON.Tools.UnregisterTopRootEvents([
  7758. { name: "keydown", handler: this._onKeyDown },
  7759. { name: "keyup", handler: this._onKeyUp },
  7760. { name: "blur", handler: this._onLostFocus }
  7761. ]);
  7762. this._MSGestureHandler = null;
  7763. this._attachedElement = null;
  7764. if (this._reset) {
  7765. this._reset();
  7766. }
  7767. };
  7768. ArcRotateCamera.prototype._update = function () {
  7769. for (var index = 0; index < this._keys.length; index++) {
  7770. var keyCode = this._keys[index];
  7771. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7772. this.inertialAlphaOffset -= 0.01;
  7773. }
  7774. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7775. this.inertialBetaOffset -= 0.01;
  7776. }
  7777. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7778. this.inertialAlphaOffset += 0.01;
  7779. }
  7780. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7781. this.inertialBetaOffset += 0.01;
  7782. }
  7783. }
  7784. // Inertia
  7785. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7786. this.alpha += this.inertialAlphaOffset;
  7787. this.beta += this.inertialBetaOffset;
  7788. this.radius -= this.inertialRadiusOffset;
  7789. this.inertialAlphaOffset *= this.inertia;
  7790. this.inertialBetaOffset *= this.inertia;
  7791. this.inertialRadiusOffset *= this.inertia;
  7792. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7793. this.inertialAlphaOffset = 0;
  7794. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7795. this.inertialBetaOffset = 0;
  7796. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7797. this.inertialRadiusOffset = 0;
  7798. }
  7799. // Limits
  7800. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7801. this.alpha = this.lowerAlphaLimit;
  7802. }
  7803. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7804. this.alpha = this.upperAlphaLimit;
  7805. }
  7806. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7807. this.beta = this.lowerBetaLimit;
  7808. }
  7809. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7810. this.beta = this.upperBetaLimit;
  7811. }
  7812. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7813. this.radius = this.lowerRadiusLimit;
  7814. }
  7815. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7816. this.radius = this.upperRadiusLimit;
  7817. }
  7818. };
  7819. ArcRotateCamera.prototype.setPosition = function (position) {
  7820. var radiusv3 = position.subtract(this._getTargetPosition());
  7821. this.radius = radiusv3.length();
  7822. // Alpha
  7823. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7824. if (radiusv3.z < 0) {
  7825. this.alpha = 2 * Math.PI - this.alpha;
  7826. }
  7827. // Beta
  7828. this.beta = Math.acos(radiusv3.y / this.radius);
  7829. };
  7830. ArcRotateCamera.prototype._getViewMatrix = function () {
  7831. // Compute
  7832. var cosa = Math.cos(this.alpha);
  7833. var sina = Math.sin(this.alpha);
  7834. var cosb = Math.cos(this.beta);
  7835. var sinb = Math.sin(this.beta);
  7836. var target = this._getTargetPosition();
  7837. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7838. if (this.checkCollisions) {
  7839. this._collider.radius = this.collisionRadius;
  7840. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7841. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7842. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7843. this.position.copyFrom(this._previousPosition);
  7844. this.alpha = this._previousAlpha;
  7845. this.beta = this._previousBeta;
  7846. this.radius = this._previousRadius;
  7847. if (this.onCollide) {
  7848. this.onCollide(this._collider.collidedMesh);
  7849. }
  7850. }
  7851. }
  7852. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7853. this._previousAlpha = this.alpha;
  7854. this._previousBeta = this.beta;
  7855. this._previousRadius = this.radius;
  7856. this._previousPosition.copyFrom(this.position);
  7857. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7858. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7859. return this._viewMatrix;
  7860. };
  7861. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7862. meshes = meshes || this.getScene().meshes;
  7863. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7864. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7865. this.radius = distance * this.zoomOnFactor;
  7866. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7867. };
  7868. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7869. var meshesOrMinMaxVector;
  7870. var distance;
  7871. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7872. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7873. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7874. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7875. }
  7876. else {
  7877. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7878. distance = meshesOrMinMaxVectorAndDistance.distance;
  7879. }
  7880. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7881. this.maxZ = distance * 2;
  7882. };
  7883. return ArcRotateCamera;
  7884. })(BABYLON.Camera);
  7885. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7886. })(BABYLON || (BABYLON = {}));
  7887. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7888. (function (BABYLON) {
  7889. /**
  7890. * Represents a scene to be rendered by the engine.
  7891. * @see http://doc.babylonjs.com/page.php?p=21911
  7892. */
  7893. var Scene = (function () {
  7894. /**
  7895. * @constructor
  7896. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7897. */
  7898. function Scene(engine) {
  7899. // Members
  7900. this.autoClear = true;
  7901. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7902. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7903. this.forceWireframe = false;
  7904. this.forcePointsCloud = false;
  7905. this.forceShowBoundingBoxes = false;
  7906. this.animationsEnabled = true;
  7907. 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
  7908. // Fog
  7909. /**
  7910. * is fog enabled on this scene.
  7911. * @type {boolean}
  7912. */
  7913. this.fogEnabled = true;
  7914. this.fogMode = Scene.FOGMODE_NONE;
  7915. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7916. this.fogDensity = 0.1;
  7917. this.fogStart = 0;
  7918. this.fogEnd = 1000.0;
  7919. // Lights
  7920. /**
  7921. * is shadow enabled on this scene.
  7922. * @type {boolean}
  7923. */
  7924. this.shadowsEnabled = true;
  7925. /**
  7926. * is light enabled on this scene.
  7927. * @type {boolean}
  7928. */
  7929. this.lightsEnabled = true;
  7930. /**
  7931. * All of the lights added to this scene.
  7932. * @see BABYLON.Light
  7933. * @type {BABYLON.Light[]}
  7934. */
  7935. this.lights = new Array();
  7936. // Cameras
  7937. /**
  7938. * All of the cameras added to this scene.
  7939. * @see BABYLON.Camera
  7940. * @type {BABYLON.Camera[]}
  7941. */
  7942. this.cameras = new Array();
  7943. this.activeCameras = new Array();
  7944. // Meshes
  7945. /**
  7946. * All of the (abstract) meshes added to this scene.
  7947. * @see BABYLON.AbstractMesh
  7948. * @type {BABYLON.AbstractMesh[]}
  7949. */
  7950. this.meshes = new Array();
  7951. // Geometries
  7952. this._geometries = new Array();
  7953. this.materials = new Array();
  7954. this.multiMaterials = new Array();
  7955. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7956. // Textures
  7957. this.texturesEnabled = true;
  7958. this.textures = new Array();
  7959. // Particles
  7960. this.particlesEnabled = true;
  7961. this.particleSystems = new Array();
  7962. // Sprites
  7963. this.spritesEnabled = true;
  7964. this.spriteManagers = new Array();
  7965. // Layers
  7966. this.layers = new Array();
  7967. // Skeletons
  7968. this.skeletonsEnabled = true;
  7969. this.skeletons = new Array();
  7970. // Lens flares
  7971. this.lensFlaresEnabled = true;
  7972. this.lensFlareSystems = new Array();
  7973. // Collisions
  7974. this.collisionsEnabled = true;
  7975. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7976. // Postprocesses
  7977. this.postProcessesEnabled = true;
  7978. // Customs render targets
  7979. this.renderTargetsEnabled = true;
  7980. this.dumpNextRenderTargets = false;
  7981. this.customRenderTargets = new Array();
  7982. // Imported meshes
  7983. this.importedMeshesFiles = new Array();
  7984. this._actionManagers = new Array();
  7985. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7986. // Procedural textures
  7987. this.proceduralTexturesEnabled = true;
  7988. this._proceduralTextures = new Array();
  7989. this.soundTracks = new Array();
  7990. this._audioEnabled = true;
  7991. this._headphone = false;
  7992. this._totalVertices = 0;
  7993. this._activeVertices = 0;
  7994. this._activeParticles = 0;
  7995. this._lastFrameDuration = 0;
  7996. this._evaluateActiveMeshesDuration = 0;
  7997. this._renderTargetsDuration = 0;
  7998. this._particlesDuration = 0;
  7999. this._renderDuration = 0;
  8000. this._spritesDuration = 0;
  8001. this._animationRatio = 0;
  8002. this._renderId = 0;
  8003. this._executeWhenReadyTimeoutId = -1;
  8004. this._toBeDisposed = new BABYLON.SmartArray(256);
  8005. this._onReadyCallbacks = new Array();
  8006. this._pendingData = []; //ANY
  8007. this._onBeforeRenderCallbacks = new Array();
  8008. this._onAfterRenderCallbacks = new Array();
  8009. this._activeMeshes = new BABYLON.SmartArray(256);
  8010. this._processedMaterials = new BABYLON.SmartArray(256);
  8011. this._renderTargets = new BABYLON.SmartArray(256);
  8012. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8013. this._activeSkeletons = new BABYLON.SmartArray(32);
  8014. this._activeBones = 0;
  8015. this._activeAnimatables = new Array();
  8016. this._transformMatrix = BABYLON.Matrix.Zero();
  8017. this._scaledPosition = BABYLON.Vector3.Zero();
  8018. this._scaledVelocity = BABYLON.Vector3.Zero();
  8019. this._engine = engine;
  8020. engine.scenes.push(this);
  8021. this._renderingManager = new BABYLON.RenderingManager(this);
  8022. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8023. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8024. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8025. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8026. this.attachControl();
  8027. this._debugLayer = new BABYLON.DebugLayer(this);
  8028. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8029. //simplification queue
  8030. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8031. }
  8032. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8033. get: function () {
  8034. return Scene._FOGMODE_NONE;
  8035. },
  8036. enumerable: true,
  8037. configurable: true
  8038. });
  8039. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8040. get: function () {
  8041. return Scene._FOGMODE_EXP;
  8042. },
  8043. enumerable: true,
  8044. configurable: true
  8045. });
  8046. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8047. get: function () {
  8048. return Scene._FOGMODE_EXP2;
  8049. },
  8050. enumerable: true,
  8051. configurable: true
  8052. });
  8053. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8054. get: function () {
  8055. return Scene._FOGMODE_LINEAR;
  8056. },
  8057. enumerable: true,
  8058. configurable: true
  8059. });
  8060. Object.defineProperty(Scene.prototype, "debugLayer", {
  8061. // Properties
  8062. get: function () {
  8063. return this._debugLayer;
  8064. },
  8065. enumerable: true,
  8066. configurable: true
  8067. });
  8068. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8069. /**
  8070. * The mesh that is currently under the pointer.
  8071. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8072. */
  8073. get: function () {
  8074. return this._meshUnderPointer;
  8075. },
  8076. enumerable: true,
  8077. configurable: true
  8078. });
  8079. Object.defineProperty(Scene.prototype, "pointerX", {
  8080. /**
  8081. * Current on-screen X position of the pointer
  8082. * @return {number} X position of the pointer
  8083. */
  8084. get: function () {
  8085. return this._pointerX;
  8086. },
  8087. enumerable: true,
  8088. configurable: true
  8089. });
  8090. Object.defineProperty(Scene.prototype, "pointerY", {
  8091. /**
  8092. * Current on-screen Y position of the pointer
  8093. * @return {number} Y position of the pointer
  8094. */
  8095. get: function () {
  8096. return this._pointerY;
  8097. },
  8098. enumerable: true,
  8099. configurable: true
  8100. });
  8101. Scene.prototype.getCachedMaterial = function () {
  8102. return this._cachedMaterial;
  8103. };
  8104. Scene.prototype.getBoundingBoxRenderer = function () {
  8105. return this._boundingBoxRenderer;
  8106. };
  8107. Scene.prototype.getOutlineRenderer = function () {
  8108. return this._outlineRenderer;
  8109. };
  8110. Scene.prototype.getEngine = function () {
  8111. return this._engine;
  8112. };
  8113. Scene.prototype.getTotalVertices = function () {
  8114. return this._totalVertices;
  8115. };
  8116. Scene.prototype.getActiveVertices = function () {
  8117. return this._activeVertices;
  8118. };
  8119. Scene.prototype.getActiveParticles = function () {
  8120. return this._activeParticles;
  8121. };
  8122. Scene.prototype.getActiveBones = function () {
  8123. return this._activeBones;
  8124. };
  8125. // Stats
  8126. Scene.prototype.getLastFrameDuration = function () {
  8127. return this._lastFrameDuration;
  8128. };
  8129. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8130. return this._evaluateActiveMeshesDuration;
  8131. };
  8132. Scene.prototype.getActiveMeshes = function () {
  8133. return this._activeMeshes;
  8134. };
  8135. Scene.prototype.getRenderTargetsDuration = function () {
  8136. return this._renderTargetsDuration;
  8137. };
  8138. Scene.prototype.getRenderDuration = function () {
  8139. return this._renderDuration;
  8140. };
  8141. Scene.prototype.getParticlesDuration = function () {
  8142. return this._particlesDuration;
  8143. };
  8144. Scene.prototype.getSpritesDuration = function () {
  8145. return this._spritesDuration;
  8146. };
  8147. Scene.prototype.getAnimationRatio = function () {
  8148. return this._animationRatio;
  8149. };
  8150. Scene.prototype.getRenderId = function () {
  8151. return this._renderId;
  8152. };
  8153. Scene.prototype.incrementRenderId = function () {
  8154. this._renderId++;
  8155. };
  8156. Scene.prototype._updatePointerPosition = function (evt) {
  8157. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8158. this._pointerX = evt.clientX - canvasRect.left;
  8159. this._pointerY = evt.clientY - canvasRect.top;
  8160. if (this.cameraToUseForPointers) {
  8161. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8162. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8163. }
  8164. };
  8165. // Pointers handling
  8166. Scene.prototype.attachControl = function () {
  8167. var _this = this;
  8168. this._onPointerMove = function (evt) {
  8169. var canvas = _this._engine.getRenderingCanvas();
  8170. _this._updatePointerPosition(evt);
  8171. 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);
  8172. if (pickResult.hit) {
  8173. _this._meshUnderPointer = pickResult.pickedMesh;
  8174. _this.setPointerOverMesh(pickResult.pickedMesh);
  8175. canvas.style.cursor = "pointer";
  8176. }
  8177. else {
  8178. _this.setPointerOverMesh(null);
  8179. canvas.style.cursor = "";
  8180. _this._meshUnderPointer = null;
  8181. }
  8182. };
  8183. this._onPointerDown = function (evt) {
  8184. var predicate = null;
  8185. if (!_this.onPointerDown) {
  8186. predicate = function (mesh) {
  8187. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8188. };
  8189. }
  8190. _this._updatePointerPosition(evt);
  8191. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8192. if (pickResult.hit) {
  8193. if (pickResult.pickedMesh.actionManager) {
  8194. switch (evt.button) {
  8195. case 0:
  8196. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8197. break;
  8198. case 1:
  8199. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8200. break;
  8201. case 2:
  8202. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8203. break;
  8204. }
  8205. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8206. }
  8207. }
  8208. if (_this.onPointerDown) {
  8209. _this.onPointerDown(evt, pickResult);
  8210. }
  8211. };
  8212. this._onKeyDown = function (evt) {
  8213. if (_this.actionManager) {
  8214. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8215. }
  8216. };
  8217. this._onKeyUp = function (evt) {
  8218. if (_this.actionManager) {
  8219. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8220. }
  8221. };
  8222. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8223. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8224. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8225. BABYLON.Tools.RegisterTopRootEvents([
  8226. { name: "keydown", handler: this._onKeyDown },
  8227. { name: "keyup", handler: this._onKeyUp }
  8228. ]);
  8229. };
  8230. Scene.prototype.detachControl = function () {
  8231. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8232. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8233. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8234. BABYLON.Tools.UnregisterTopRootEvents([
  8235. { name: "keydown", handler: this._onKeyDown },
  8236. { name: "keyup", handler: this._onKeyUp }
  8237. ]);
  8238. };
  8239. // Ready
  8240. Scene.prototype.isReady = function () {
  8241. if (this._pendingData.length > 0) {
  8242. return false;
  8243. }
  8244. for (var index = 0; index < this._geometries.length; index++) {
  8245. var geometry = this._geometries[index];
  8246. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8247. return false;
  8248. }
  8249. }
  8250. for (index = 0; index < this.meshes.length; index++) {
  8251. var mesh = this.meshes[index];
  8252. if (!mesh.isReady()) {
  8253. return false;
  8254. }
  8255. var mat = mesh.material;
  8256. if (mat) {
  8257. if (!mat.isReady(mesh)) {
  8258. return false;
  8259. }
  8260. }
  8261. }
  8262. return true;
  8263. };
  8264. Scene.prototype.resetCachedMaterial = function () {
  8265. this._cachedMaterial = null;
  8266. };
  8267. Scene.prototype.registerBeforeRender = function (func) {
  8268. this._onBeforeRenderCallbacks.push(func);
  8269. };
  8270. Scene.prototype.unregisterBeforeRender = function (func) {
  8271. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8272. if (index > -1) {
  8273. this._onBeforeRenderCallbacks.splice(index, 1);
  8274. }
  8275. };
  8276. Scene.prototype.registerAfterRender = function (func) {
  8277. this._onAfterRenderCallbacks.push(func);
  8278. };
  8279. Scene.prototype.unregisterAfterRender = function (func) {
  8280. var index = this._onAfterRenderCallbacks.indexOf(func);
  8281. if (index > -1) {
  8282. this._onAfterRenderCallbacks.splice(index, 1);
  8283. }
  8284. };
  8285. Scene.prototype._addPendingData = function (data) {
  8286. this._pendingData.push(data);
  8287. };
  8288. Scene.prototype._removePendingData = function (data) {
  8289. var index = this._pendingData.indexOf(data);
  8290. if (index !== -1) {
  8291. this._pendingData.splice(index, 1);
  8292. }
  8293. };
  8294. Scene.prototype.getWaitingItemsCount = function () {
  8295. return this._pendingData.length;
  8296. };
  8297. /**
  8298. * Registers a function to be executed when the scene is ready.
  8299. * @param {Function} func - the function to be executed.
  8300. */
  8301. Scene.prototype.executeWhenReady = function (func) {
  8302. var _this = this;
  8303. this._onReadyCallbacks.push(func);
  8304. if (this._executeWhenReadyTimeoutId !== -1) {
  8305. return;
  8306. }
  8307. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8308. _this._checkIsReady();
  8309. }, 150);
  8310. };
  8311. Scene.prototype._checkIsReady = function () {
  8312. var _this = this;
  8313. if (this.isReady()) {
  8314. this._onReadyCallbacks.forEach(function (func) {
  8315. func();
  8316. });
  8317. this._onReadyCallbacks = [];
  8318. this._executeWhenReadyTimeoutId = -1;
  8319. return;
  8320. }
  8321. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8322. _this._checkIsReady();
  8323. }, 150);
  8324. };
  8325. // Animations
  8326. /**
  8327. * Will start the animation sequence of a given target
  8328. * @param target - the target
  8329. * @param {number} from - from which frame should animation start
  8330. * @param {number} to - till which frame should animation run.
  8331. * @param {boolean} [loop] - should the animation loop
  8332. * @param {number} [speedRatio] - the speed in which to run the animation
  8333. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8334. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8335. * @return {BABYLON.Animatable} the animatable object created for this animation
  8336. * @see BABYLON.Animatable
  8337. * @see http://doc.babylonjs.com/page.php?p=22081
  8338. */
  8339. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8340. if (speedRatio === undefined) {
  8341. speedRatio = 1.0;
  8342. }
  8343. this.stopAnimation(target);
  8344. if (!animatable) {
  8345. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8346. }
  8347. // Local animations
  8348. if (target.animations) {
  8349. animatable.appendAnimations(target, target.animations);
  8350. }
  8351. // Children animations
  8352. if (target.getAnimatables) {
  8353. var animatables = target.getAnimatables();
  8354. for (var index = 0; index < animatables.length; index++) {
  8355. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8356. }
  8357. }
  8358. return animatable;
  8359. };
  8360. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8361. if (speedRatio === undefined) {
  8362. speedRatio = 1.0;
  8363. }
  8364. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8365. return animatable;
  8366. };
  8367. Scene.prototype.getAnimatableByTarget = function (target) {
  8368. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8369. if (this._activeAnimatables[index].target === target) {
  8370. return this._activeAnimatables[index];
  8371. }
  8372. }
  8373. return null;
  8374. };
  8375. /**
  8376. * Will stop the animation of the given target
  8377. * @param target - the target
  8378. * @see beginAnimation
  8379. */
  8380. Scene.prototype.stopAnimation = function (target) {
  8381. var animatable = this.getAnimatableByTarget(target);
  8382. if (animatable) {
  8383. animatable.stop();
  8384. }
  8385. };
  8386. Scene.prototype._animate = function () {
  8387. if (!this.animationsEnabled) {
  8388. return;
  8389. }
  8390. if (!this._animationStartDate) {
  8391. this._animationStartDate = BABYLON.Tools.Now;
  8392. }
  8393. // Getting time
  8394. var now = BABYLON.Tools.Now;
  8395. var delay = now - this._animationStartDate;
  8396. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8397. if (!this._activeAnimatables[index]._animate(delay)) {
  8398. this._activeAnimatables.splice(index, 1);
  8399. index--;
  8400. }
  8401. }
  8402. };
  8403. // Matrix
  8404. Scene.prototype.getViewMatrix = function () {
  8405. return this._viewMatrix;
  8406. };
  8407. Scene.prototype.getProjectionMatrix = function () {
  8408. return this._projectionMatrix;
  8409. };
  8410. Scene.prototype.getTransformMatrix = function () {
  8411. return this._transformMatrix;
  8412. };
  8413. Scene.prototype.setTransformMatrix = function (view, projection) {
  8414. this._viewMatrix = view;
  8415. this._projectionMatrix = projection;
  8416. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8417. };
  8418. // Methods
  8419. Scene.prototype.addMesh = function (newMesh) {
  8420. var position = this.meshes.push(newMesh);
  8421. if (this.onNewMeshAdded) {
  8422. this.onNewMeshAdded(newMesh, position, this);
  8423. }
  8424. };
  8425. Scene.prototype.removeMesh = function (toRemove) {
  8426. var index = this.meshes.indexOf(toRemove);
  8427. if (index !== -1) {
  8428. // Remove from the scene if mesh found
  8429. this.meshes.splice(index, 1);
  8430. }
  8431. if (this.onMeshRemoved) {
  8432. this.onMeshRemoved(toRemove);
  8433. }
  8434. return index;
  8435. };
  8436. Scene.prototype.removeLight = function (toRemove) {
  8437. var index = this.lights.indexOf(toRemove);
  8438. if (index !== -1) {
  8439. // Remove from the scene if mesh found
  8440. this.lights.splice(index, 1);
  8441. }
  8442. if (this.onLightRemoved) {
  8443. this.onLightRemoved(toRemove);
  8444. }
  8445. return index;
  8446. };
  8447. Scene.prototype.removeCamera = function (toRemove) {
  8448. var index = this.cameras.indexOf(toRemove);
  8449. if (index !== -1) {
  8450. // Remove from the scene if mesh found
  8451. this.cameras.splice(index, 1);
  8452. }
  8453. if (this.onCameraRemoved) {
  8454. this.onCameraRemoved(toRemove);
  8455. }
  8456. return index;
  8457. };
  8458. Scene.prototype.addLight = function (newLight) {
  8459. var position = this.lights.push(newLight);
  8460. if (this.onNewLightAdded) {
  8461. this.onNewLightAdded(newLight, position, this);
  8462. }
  8463. };
  8464. Scene.prototype.addCamera = function (newCamera) {
  8465. var position = this.cameras.push(newCamera);
  8466. if (this.onNewCameraAdded) {
  8467. this.onNewCameraAdded(newCamera, position, this);
  8468. }
  8469. };
  8470. /**
  8471. * sets the active camera of the scene using its ID
  8472. * @param {string} id - the camera's ID
  8473. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8474. * @see activeCamera
  8475. */
  8476. Scene.prototype.setActiveCameraByID = function (id) {
  8477. var camera = this.getCameraByID(id);
  8478. if (camera) {
  8479. this.activeCamera = camera;
  8480. return camera;
  8481. }
  8482. return null;
  8483. };
  8484. /**
  8485. * sets the active camera of the scene using its name
  8486. * @param {string} name - the camera's name
  8487. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8488. * @see activeCamera
  8489. */
  8490. Scene.prototype.setActiveCameraByName = function (name) {
  8491. var camera = this.getCameraByName(name);
  8492. if (camera) {
  8493. this.activeCamera = camera;
  8494. return camera;
  8495. }
  8496. return null;
  8497. };
  8498. /**
  8499. * get a material using its id
  8500. * @param {string} the material's ID
  8501. * @return {BABYLON.Material|null} the material or null if none found.
  8502. */
  8503. Scene.prototype.getMaterialByID = function (id) {
  8504. for (var index = 0; index < this.materials.length; index++) {
  8505. if (this.materials[index].id === id) {
  8506. return this.materials[index];
  8507. }
  8508. }
  8509. return null;
  8510. };
  8511. /**
  8512. * get a material using its name
  8513. * @param {string} the material's name
  8514. * @return {BABYLON.Material|null} the material or null if none found.
  8515. */
  8516. Scene.prototype.getMaterialByName = function (name) {
  8517. for (var index = 0; index < this.materials.length; index++) {
  8518. if (this.materials[index].name === name) {
  8519. return this.materials[index];
  8520. }
  8521. }
  8522. return null;
  8523. };
  8524. Scene.prototype.getCameraByID = function (id) {
  8525. for (var index = 0; index < this.cameras.length; index++) {
  8526. if (this.cameras[index].id === id) {
  8527. return this.cameras[index];
  8528. }
  8529. }
  8530. return null;
  8531. };
  8532. /**
  8533. * get a camera using its name
  8534. * @param {string} the camera's name
  8535. * @return {BABYLON.Camera|null} the camera or null if none found.
  8536. */
  8537. Scene.prototype.getCameraByName = function (name) {
  8538. for (var index = 0; index < this.cameras.length; index++) {
  8539. if (this.cameras[index].name === name) {
  8540. return this.cameras[index];
  8541. }
  8542. }
  8543. return null;
  8544. };
  8545. /**
  8546. * get a light node using its name
  8547. * @param {string} the light's name
  8548. * @return {BABYLON.Light|null} the light or null if none found.
  8549. */
  8550. Scene.prototype.getLightByName = function (name) {
  8551. for (var index = 0; index < this.lights.length; index++) {
  8552. if (this.lights[index].name === name) {
  8553. return this.lights[index];
  8554. }
  8555. }
  8556. return null;
  8557. };
  8558. /**
  8559. * get a light node using its ID
  8560. * @param {string} the light's id
  8561. * @return {BABYLON.Light|null} the light or null if none found.
  8562. */
  8563. Scene.prototype.getLightByID = function (id) {
  8564. for (var index = 0; index < this.lights.length; index++) {
  8565. if (this.lights[index].id === id) {
  8566. return this.lights[index];
  8567. }
  8568. }
  8569. return null;
  8570. };
  8571. /**
  8572. * get a geometry using its ID
  8573. * @param {string} the geometry's id
  8574. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8575. */
  8576. Scene.prototype.getGeometryByID = function (id) {
  8577. for (var index = 0; index < this._geometries.length; index++) {
  8578. if (this._geometries[index].id === id) {
  8579. return this._geometries[index];
  8580. }
  8581. }
  8582. return null;
  8583. };
  8584. /**
  8585. * add a new geometry to this scene.
  8586. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8587. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8588. * @return {boolean} was the geometry added or not
  8589. */
  8590. Scene.prototype.pushGeometry = function (geometry, force) {
  8591. if (!force && this.getGeometryByID(geometry.id)) {
  8592. return false;
  8593. }
  8594. this._geometries.push(geometry);
  8595. return true;
  8596. };
  8597. Scene.prototype.getGeometries = function () {
  8598. return this._geometries;
  8599. };
  8600. /**
  8601. * Get a the first added mesh found of a given ID
  8602. * @param {string} id - the id to search for
  8603. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8604. */
  8605. Scene.prototype.getMeshByID = function (id) {
  8606. for (var index = 0; index < this.meshes.length; index++) {
  8607. if (this.meshes[index].id === id) {
  8608. return this.meshes[index];
  8609. }
  8610. }
  8611. return null;
  8612. };
  8613. /**
  8614. * Get a the last added mesh found of a given ID
  8615. * @param {string} id - the id to search for
  8616. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8617. */
  8618. Scene.prototype.getLastMeshByID = function (id) {
  8619. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8620. if (this.meshes[index].id === id) {
  8621. return this.meshes[index];
  8622. }
  8623. }
  8624. return null;
  8625. };
  8626. /**
  8627. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8628. * @param {string} id - the id to search for
  8629. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8630. */
  8631. Scene.prototype.getLastEntryByID = function (id) {
  8632. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8633. if (this.meshes[index].id === id) {
  8634. return this.meshes[index];
  8635. }
  8636. }
  8637. for (index = this.cameras.length - 1; index >= 0; index--) {
  8638. if (this.cameras[index].id === id) {
  8639. return this.cameras[index];
  8640. }
  8641. }
  8642. for (index = this.lights.length - 1; index >= 0; index--) {
  8643. if (this.lights[index].id === id) {
  8644. return this.lights[index];
  8645. }
  8646. }
  8647. return null;
  8648. };
  8649. Scene.prototype.getNodeByName = function (name) {
  8650. var mesh = this.getMeshByName(name);
  8651. if (mesh) {
  8652. return mesh;
  8653. }
  8654. var light = this.getLightByName(name);
  8655. if (light) {
  8656. return light;
  8657. }
  8658. return this.getCameraByName(name);
  8659. };
  8660. Scene.prototype.getMeshByName = function (name) {
  8661. for (var index = 0; index < this.meshes.length; index++) {
  8662. if (this.meshes[index].name === name) {
  8663. return this.meshes[index];
  8664. }
  8665. }
  8666. return null;
  8667. };
  8668. Scene.prototype.getSoundByName = function (name) {
  8669. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8670. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8671. return this.mainSoundTrack.soundCollection[index];
  8672. }
  8673. }
  8674. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8675. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8676. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8677. return this.soundTracks[sdIndex].soundCollection[index];
  8678. }
  8679. }
  8680. }
  8681. return null;
  8682. };
  8683. Scene.prototype.getLastSkeletonByID = function (id) {
  8684. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8685. if (this.skeletons[index].id === id) {
  8686. return this.skeletons[index];
  8687. }
  8688. }
  8689. return null;
  8690. };
  8691. Scene.prototype.getSkeletonById = function (id) {
  8692. for (var index = 0; index < this.skeletons.length; index++) {
  8693. if (this.skeletons[index].id === id) {
  8694. return this.skeletons[index];
  8695. }
  8696. }
  8697. return null;
  8698. };
  8699. Scene.prototype.getSkeletonByName = function (name) {
  8700. for (var index = 0; index < this.skeletons.length; index++) {
  8701. if (this.skeletons[index].name === name) {
  8702. return this.skeletons[index];
  8703. }
  8704. }
  8705. return null;
  8706. };
  8707. Scene.prototype.isActiveMesh = function (mesh) {
  8708. return (this._activeMeshes.indexOf(mesh) !== -1);
  8709. };
  8710. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8711. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8712. var material = subMesh.getMaterial();
  8713. if (mesh.showSubMeshesBoundingBox) {
  8714. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8715. }
  8716. if (material) {
  8717. // Render targets
  8718. if (material.getRenderTargetTextures) {
  8719. if (this._processedMaterials.indexOf(material) === -1) {
  8720. this._processedMaterials.push(material);
  8721. this._renderTargets.concat(material.getRenderTargetTextures());
  8722. }
  8723. }
  8724. // Dispatch
  8725. this._activeVertices += subMesh.indexCount;
  8726. this._renderingManager.dispatch(subMesh);
  8727. }
  8728. }
  8729. };
  8730. Scene.prototype._evaluateActiveMeshes = function () {
  8731. this.activeCamera._activeMeshes.reset();
  8732. this._activeMeshes.reset();
  8733. this._renderingManager.reset();
  8734. this._processedMaterials.reset();
  8735. this._activeParticleSystems.reset();
  8736. this._activeSkeletons.reset();
  8737. this._boundingBoxRenderer.reset();
  8738. if (!this._frustumPlanes) {
  8739. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8740. }
  8741. else {
  8742. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8743. }
  8744. // Meshes
  8745. var meshes;
  8746. var len;
  8747. if (this._selectionOctree) {
  8748. var selection = this._selectionOctree.select(this._frustumPlanes);
  8749. meshes = selection.data;
  8750. len = selection.length;
  8751. }
  8752. else {
  8753. len = this.meshes.length;
  8754. meshes = this.meshes;
  8755. }
  8756. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8757. var mesh = meshes[meshIndex];
  8758. if (mesh.isBlocked) {
  8759. continue;
  8760. }
  8761. this._totalVertices += mesh.getTotalVertices();
  8762. if (!mesh.isReady()) {
  8763. continue;
  8764. }
  8765. mesh.computeWorldMatrix();
  8766. // Intersections
  8767. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8768. this._meshesForIntersections.pushNoDuplicate(mesh);
  8769. }
  8770. // Switch to current LOD
  8771. var meshLOD = mesh.getLOD(this.activeCamera);
  8772. if (!meshLOD) {
  8773. continue;
  8774. }
  8775. mesh._preActivate();
  8776. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8777. this._activeMeshes.push(mesh);
  8778. this.activeCamera._activeMeshes.push(mesh);
  8779. mesh._activate(this._renderId);
  8780. this._activeMesh(meshLOD);
  8781. }
  8782. }
  8783. // Particle systems
  8784. var beforeParticlesDate = BABYLON.Tools.Now;
  8785. if (this.particlesEnabled) {
  8786. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8787. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8788. var particleSystem = this.particleSystems[particleIndex];
  8789. if (!particleSystem.isStarted()) {
  8790. continue;
  8791. }
  8792. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8793. this._activeParticleSystems.push(particleSystem);
  8794. particleSystem.animate();
  8795. }
  8796. }
  8797. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8798. }
  8799. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8800. };
  8801. Scene.prototype._activeMesh = function (mesh) {
  8802. if (mesh.skeleton && this.skeletonsEnabled) {
  8803. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8804. }
  8805. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8806. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8807. }
  8808. if (mesh && mesh.subMeshes) {
  8809. // Submeshes Octrees
  8810. var len;
  8811. var subMeshes;
  8812. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8813. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8814. len = intersections.length;
  8815. subMeshes = intersections.data;
  8816. }
  8817. else {
  8818. subMeshes = mesh.subMeshes;
  8819. len = subMeshes.length;
  8820. }
  8821. for (var subIndex = 0; subIndex < len; subIndex++) {
  8822. var subMesh = subMeshes[subIndex];
  8823. this._evaluateSubMesh(subMesh, mesh);
  8824. }
  8825. }
  8826. };
  8827. Scene.prototype.updateTransformMatrix = function (force) {
  8828. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8829. };
  8830. Scene.prototype._renderForCamera = function (camera) {
  8831. var engine = this._engine;
  8832. this.activeCamera = camera;
  8833. if (!this.activeCamera)
  8834. throw new Error("Active camera not set");
  8835. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8836. // Viewport
  8837. engine.setViewport(this.activeCamera.viewport);
  8838. // Camera
  8839. this._renderId++;
  8840. this.updateTransformMatrix();
  8841. if (this.beforeCameraRender) {
  8842. this.beforeCameraRender(this.activeCamera);
  8843. }
  8844. // Meshes
  8845. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8846. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8847. this._evaluateActiveMeshes();
  8848. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8849. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8850. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8851. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8852. skeleton.prepare();
  8853. }
  8854. // Render targets
  8855. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8856. if (this.renderTargetsEnabled) {
  8857. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8858. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8859. var renderTarget = this._renderTargets.data[renderIndex];
  8860. if (renderTarget._shouldRender()) {
  8861. this._renderId++;
  8862. renderTarget.render(false, this.dumpNextRenderTargets);
  8863. }
  8864. }
  8865. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8866. this._renderId++;
  8867. }
  8868. if (this._renderTargets.length > 0) {
  8869. engine.restoreDefaultFramebuffer();
  8870. }
  8871. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8872. // Prepare Frame
  8873. this.postProcessManager._prepareFrame();
  8874. var beforeRenderDate = BABYLON.Tools.Now;
  8875. // Backgrounds
  8876. if (this.layers.length) {
  8877. engine.setDepthBuffer(false);
  8878. var layerIndex;
  8879. var layer;
  8880. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8881. layer = this.layers[layerIndex];
  8882. if (layer.isBackground) {
  8883. layer.render();
  8884. }
  8885. }
  8886. engine.setDepthBuffer(true);
  8887. }
  8888. // Render
  8889. BABYLON.Tools.StartPerformanceCounter("Main render");
  8890. this._renderingManager.render(null, null, true, true);
  8891. BABYLON.Tools.EndPerformanceCounter("Main render");
  8892. // Bounding boxes
  8893. this._boundingBoxRenderer.render();
  8894. // Lens flares
  8895. if (this.lensFlaresEnabled) {
  8896. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8897. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8898. this.lensFlareSystems[lensFlareSystemIndex].render();
  8899. }
  8900. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8901. }
  8902. // Foregrounds
  8903. if (this.layers.length) {
  8904. engine.setDepthBuffer(false);
  8905. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8906. layer = this.layers[layerIndex];
  8907. if (!layer.isBackground) {
  8908. layer.render();
  8909. }
  8910. }
  8911. engine.setDepthBuffer(true);
  8912. }
  8913. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8914. // Finalize frame
  8915. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8916. // Update camera
  8917. this.activeCamera._updateFromScene();
  8918. // Reset some special arrays
  8919. this._renderTargets.reset();
  8920. if (this.afterCameraRender) {
  8921. this.afterCameraRender(this.activeCamera);
  8922. }
  8923. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8924. };
  8925. Scene.prototype._processSubCameras = function (camera) {
  8926. if (camera.subCameras.length === 0) {
  8927. this._renderForCamera(camera);
  8928. return;
  8929. }
  8930. for (var index = 0; index < camera.subCameras.length; index++) {
  8931. this._renderForCamera(camera.subCameras[index]);
  8932. }
  8933. this.activeCamera = camera;
  8934. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8935. // Update camera
  8936. this.activeCamera._updateFromScene();
  8937. };
  8938. Scene.prototype._checkIntersections = function () {
  8939. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8940. var sourceMesh = this._meshesForIntersections.data[index];
  8941. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8942. var action = sourceMesh.actionManager.actions[actionIndex];
  8943. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8944. var parameters = action.getTriggerParameter();
  8945. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8946. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8947. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8948. if (areIntersecting && currentIntersectionInProgress === -1) {
  8949. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8950. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8951. sourceMesh._intersectionsInProgress.push(otherMesh);
  8952. }
  8953. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8954. sourceMesh._intersectionsInProgress.push(otherMesh);
  8955. }
  8956. }
  8957. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8958. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8959. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8960. if (indexOfOther > -1) {
  8961. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8962. }
  8963. }
  8964. }
  8965. }
  8966. }
  8967. };
  8968. Scene.prototype.render = function () {
  8969. var startDate = BABYLON.Tools.Now;
  8970. this._particlesDuration = 0;
  8971. this._spritesDuration = 0;
  8972. this._activeParticles = 0;
  8973. this._renderDuration = 0;
  8974. this._renderTargetsDuration = 0;
  8975. this._evaluateActiveMeshesDuration = 0;
  8976. this._totalVertices = 0;
  8977. this._activeVertices = 0;
  8978. this._activeBones = 0;
  8979. this.getEngine().resetDrawCalls();
  8980. this._meshesForIntersections.reset();
  8981. this.resetCachedMaterial();
  8982. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8983. // Actions
  8984. if (this.actionManager) {
  8985. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8986. }
  8987. //Simplification Queue
  8988. if (!this.simplificationQueue.running) {
  8989. this.simplificationQueue.executeNext();
  8990. }
  8991. // Before render
  8992. if (this.beforeRender) {
  8993. this.beforeRender();
  8994. }
  8995. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8996. this._onBeforeRenderCallbacks[callbackIndex]();
  8997. }
  8998. // Animations
  8999. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9000. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9001. this._animate();
  9002. // Physics
  9003. if (this._physicsEngine) {
  9004. BABYLON.Tools.StartPerformanceCounter("Physics");
  9005. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9006. BABYLON.Tools.EndPerformanceCounter("Physics");
  9007. }
  9008. // Customs render targets
  9009. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9010. var engine = this.getEngine();
  9011. var currentActiveCamera = this.activeCamera;
  9012. if (this.renderTargetsEnabled) {
  9013. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9014. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9015. var renderTarget = this.customRenderTargets[customIndex];
  9016. if (renderTarget._shouldRender()) {
  9017. this._renderId++;
  9018. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9019. if (!this.activeCamera)
  9020. throw new Error("Active camera not set");
  9021. // Viewport
  9022. engine.setViewport(this.activeCamera.viewport);
  9023. // Camera
  9024. this.updateTransformMatrix();
  9025. renderTarget.render(false, this.dumpNextRenderTargets);
  9026. }
  9027. }
  9028. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9029. this._renderId++;
  9030. }
  9031. if (this.customRenderTargets.length > 0) {
  9032. engine.restoreDefaultFramebuffer();
  9033. }
  9034. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9035. this.activeCamera = currentActiveCamera;
  9036. // Procedural textures
  9037. if (this.proceduralTexturesEnabled) {
  9038. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9039. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9040. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9041. if (proceduralTexture._shouldRender()) {
  9042. proceduralTexture.render();
  9043. }
  9044. }
  9045. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9046. }
  9047. // Clear
  9048. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9049. // Shadows
  9050. if (this.shadowsEnabled) {
  9051. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9052. var light = this.lights[lightIndex];
  9053. var shadowGenerator = light.getShadowGenerator();
  9054. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9055. this._renderTargets.push(shadowGenerator.getShadowMap());
  9056. }
  9057. }
  9058. }
  9059. // Depth renderer
  9060. if (this._depthRenderer) {
  9061. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9062. }
  9063. // RenderPipeline
  9064. this.postProcessRenderPipelineManager.update();
  9065. // Multi-cameras?
  9066. if (this.activeCameras.length > 0) {
  9067. var currentRenderId = this._renderId;
  9068. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9069. this._renderId = currentRenderId;
  9070. this._processSubCameras(this.activeCameras[cameraIndex]);
  9071. }
  9072. }
  9073. else {
  9074. if (!this.activeCamera) {
  9075. throw new Error("No camera defined");
  9076. }
  9077. this._processSubCameras(this.activeCamera);
  9078. }
  9079. // Intersection checks
  9080. this._checkIntersections();
  9081. // Update the audio listener attached to the camera
  9082. this._updateAudioParameters();
  9083. // After render
  9084. if (this.afterRender) {
  9085. this.afterRender();
  9086. }
  9087. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9088. this._onAfterRenderCallbacks[callbackIndex]();
  9089. }
  9090. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9091. this._toBeDisposed.data[index].dispose();
  9092. this._toBeDisposed[index] = null;
  9093. }
  9094. this._toBeDisposed.reset();
  9095. if (this.dumpNextRenderTargets) {
  9096. this.dumpNextRenderTargets = false;
  9097. }
  9098. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9099. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9100. };
  9101. Scene.prototype._updateAudioParameters = function () {
  9102. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9103. return;
  9104. }
  9105. var listeningCamera;
  9106. var audioEngine = BABYLON.Engine.audioEngine;
  9107. if (this.activeCameras.length > 0) {
  9108. listeningCamera = this.activeCameras[0];
  9109. }
  9110. else {
  9111. listeningCamera = this.activeCamera;
  9112. }
  9113. if (listeningCamera && audioEngine.canUseWebAudio) {
  9114. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9115. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9116. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9117. cameraDirection.normalize();
  9118. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9119. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9120. var sound = this.mainSoundTrack.soundCollection[i];
  9121. if (sound.useCustomAttenuation) {
  9122. sound.updateDistanceFromListener();
  9123. }
  9124. }
  9125. for (i = 0; i < this.soundTracks.length; i++) {
  9126. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9127. sound = this.soundTracks[i].soundCollection[j];
  9128. if (sound.useCustomAttenuation) {
  9129. sound.updateDistanceFromListener();
  9130. }
  9131. }
  9132. }
  9133. }
  9134. };
  9135. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9136. // Audio
  9137. get: function () {
  9138. return this._audioEnabled;
  9139. },
  9140. set: function (value) {
  9141. this._audioEnabled = value;
  9142. if (this._audioEnabled) {
  9143. this._enableAudio();
  9144. }
  9145. else {
  9146. this._disableAudio();
  9147. }
  9148. },
  9149. enumerable: true,
  9150. configurable: true
  9151. });
  9152. Scene.prototype._disableAudio = function () {
  9153. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9154. this.mainSoundTrack.soundCollection[i].pause();
  9155. }
  9156. for (i = 0; i < this.soundTracks.length; i++) {
  9157. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9158. this.soundTracks[i].soundCollection[j].pause();
  9159. }
  9160. }
  9161. };
  9162. Scene.prototype._enableAudio = function () {
  9163. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9164. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9165. this.mainSoundTrack.soundCollection[i].play();
  9166. }
  9167. }
  9168. for (i = 0; i < this.soundTracks.length; i++) {
  9169. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9170. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9171. this.soundTracks[i].soundCollection[j].play();
  9172. }
  9173. }
  9174. }
  9175. };
  9176. Object.defineProperty(Scene.prototype, "headphone", {
  9177. get: function () {
  9178. return this._headphone;
  9179. },
  9180. set: function (value) {
  9181. this._headphone = value;
  9182. if (this._headphone) {
  9183. this._switchAudioModeForHeadphones();
  9184. }
  9185. else {
  9186. this._switchAudioModeForNormalSpeakers();
  9187. }
  9188. },
  9189. enumerable: true,
  9190. configurable: true
  9191. });
  9192. Scene.prototype._switchAudioModeForHeadphones = function () {
  9193. this.mainSoundTrack.switchPanningModelToHRTF();
  9194. for (var i = 0; i < this.soundTracks.length; i++) {
  9195. this.soundTracks[i].switchPanningModelToHRTF();
  9196. }
  9197. };
  9198. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9199. this.mainSoundTrack.switchPanningModelToEqualPower();
  9200. for (var i = 0; i < this.soundTracks.length; i++) {
  9201. this.soundTracks[i].switchPanningModelToEqualPower();
  9202. }
  9203. };
  9204. Scene.prototype.enableDepthRenderer = function () {
  9205. if (this._depthRenderer) {
  9206. return this._depthRenderer;
  9207. }
  9208. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9209. return this._depthRenderer;
  9210. };
  9211. Scene.prototype.disableDepthRenderer = function () {
  9212. if (!this._depthRenderer) {
  9213. return;
  9214. }
  9215. this._depthRenderer.dispose();
  9216. this._depthRenderer = null;
  9217. };
  9218. Scene.prototype.dispose = function () {
  9219. this.beforeRender = null;
  9220. this.afterRender = null;
  9221. this.skeletons = [];
  9222. this._boundingBoxRenderer.dispose();
  9223. if (this._depthRenderer) {
  9224. this._depthRenderer.dispose();
  9225. }
  9226. // Debug layer
  9227. this.debugLayer.hide();
  9228. // Events
  9229. if (this.onDispose) {
  9230. this.onDispose();
  9231. }
  9232. this._onBeforeRenderCallbacks = [];
  9233. this._onAfterRenderCallbacks = [];
  9234. this.detachControl();
  9235. // Release sounds & sounds tracks
  9236. this.disposeSounds();
  9237. // Detach cameras
  9238. var canvas = this._engine.getRenderingCanvas();
  9239. var index;
  9240. for (index = 0; index < this.cameras.length; index++) {
  9241. this.cameras[index].detachControl(canvas);
  9242. }
  9243. while (this.lights.length) {
  9244. this.lights[0].dispose();
  9245. }
  9246. while (this.meshes.length) {
  9247. this.meshes[0].dispose(true);
  9248. }
  9249. while (this.cameras.length) {
  9250. this.cameras[0].dispose();
  9251. }
  9252. while (this.materials.length) {
  9253. this.materials[0].dispose();
  9254. }
  9255. while (this.particleSystems.length) {
  9256. this.particleSystems[0].dispose();
  9257. }
  9258. while (this.spriteManagers.length) {
  9259. this.spriteManagers[0].dispose();
  9260. }
  9261. while (this.layers.length) {
  9262. this.layers[0].dispose();
  9263. }
  9264. while (this.textures.length) {
  9265. this.textures[0].dispose();
  9266. }
  9267. // Post-processes
  9268. this.postProcessManager.dispose();
  9269. // Physics
  9270. if (this._physicsEngine) {
  9271. this.disablePhysicsEngine();
  9272. }
  9273. // Remove from engine
  9274. index = this._engine.scenes.indexOf(this);
  9275. if (index > -1) {
  9276. this._engine.scenes.splice(index, 1);
  9277. }
  9278. this._engine.wipeCaches();
  9279. };
  9280. // Release sounds & sounds tracks
  9281. Scene.prototype.disposeSounds = function () {
  9282. this.mainSoundTrack.dispose();
  9283. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9284. this.soundTracks[scIndex].dispose();
  9285. }
  9286. };
  9287. // Collisions
  9288. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9289. if (excludedMesh === void 0) { excludedMesh = null; }
  9290. position.divideToRef(collider.radius, this._scaledPosition);
  9291. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9292. collider.retry = 0;
  9293. collider.initialVelocity = this._scaledVelocity;
  9294. collider.initialPosition = this._scaledPosition;
  9295. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9296. finalPosition.multiplyInPlace(collider.radius);
  9297. };
  9298. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9299. if (excludedMesh === void 0) { excludedMesh = null; }
  9300. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9301. if (collider.retry >= maximumRetry) {
  9302. finalPosition.copyFrom(position);
  9303. return;
  9304. }
  9305. collider._initialize(position, velocity, closeDistance);
  9306. for (var index = 0; index < this.meshes.length; index++) {
  9307. var mesh = this.meshes[index];
  9308. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9309. mesh._checkCollision(collider);
  9310. }
  9311. }
  9312. if (!collider.collisionFound) {
  9313. position.addToRef(velocity, finalPosition);
  9314. return;
  9315. }
  9316. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9317. collider._getResponse(position, velocity);
  9318. }
  9319. if (velocity.length() <= closeDistance) {
  9320. finalPosition.copyFrom(position);
  9321. return;
  9322. }
  9323. collider.retry++;
  9324. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9325. };
  9326. // Octrees
  9327. Scene.prototype.getWorldExtends = function () {
  9328. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9329. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9330. for (var index = 0; index < this.meshes.length; index++) {
  9331. var mesh = this.meshes[index];
  9332. mesh.computeWorldMatrix(true);
  9333. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9334. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9335. BABYLON.Tools.CheckExtends(minBox, min, max);
  9336. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9337. }
  9338. return {
  9339. min: min,
  9340. max: max
  9341. };
  9342. };
  9343. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9344. if (maxCapacity === void 0) { maxCapacity = 64; }
  9345. if (maxDepth === void 0) { maxDepth = 2; }
  9346. if (!this._selectionOctree) {
  9347. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9348. }
  9349. var worldExtends = this.getWorldExtends();
  9350. // Update octree
  9351. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9352. return this._selectionOctree;
  9353. };
  9354. // Picking
  9355. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9356. var engine = this._engine;
  9357. if (!camera) {
  9358. if (!this.activeCamera)
  9359. throw new Error("Active camera not set");
  9360. camera = this.activeCamera;
  9361. }
  9362. var cameraViewport = camera.viewport;
  9363. var viewport = cameraViewport.toGlobal(engine);
  9364. // Moving coordinates to local viewport world
  9365. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9366. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9367. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9368. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9369. };
  9370. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9371. var pickingInfo = null;
  9372. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9373. var mesh = this.meshes[meshIndex];
  9374. if (predicate) {
  9375. if (!predicate(mesh)) {
  9376. continue;
  9377. }
  9378. }
  9379. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9380. continue;
  9381. }
  9382. var world = mesh.getWorldMatrix();
  9383. var ray = rayFunction(world);
  9384. var result = mesh.intersects(ray, fastCheck);
  9385. if (!result || !result.hit)
  9386. continue;
  9387. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9388. continue;
  9389. pickingInfo = result;
  9390. if (fastCheck) {
  9391. break;
  9392. }
  9393. }
  9394. return pickingInfo || new BABYLON.PickingInfo();
  9395. };
  9396. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9397. var _this = this;
  9398. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9399. /// <param name="x">X position on screen</param>
  9400. /// <param name="y">Y position on screen</param>
  9401. /// <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>
  9402. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9403. /// <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>
  9404. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9405. };
  9406. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9407. var _this = this;
  9408. return this._internalPick(function (world) {
  9409. if (!_this._pickWithRayInverseMatrix) {
  9410. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9411. }
  9412. world.invertToRef(_this._pickWithRayInverseMatrix);
  9413. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9414. }, predicate, fastCheck);
  9415. };
  9416. Scene.prototype.setPointerOverMesh = function (mesh) {
  9417. if (this._pointerOverMesh === mesh) {
  9418. return;
  9419. }
  9420. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9421. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9422. }
  9423. this._pointerOverMesh = mesh;
  9424. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9425. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9426. }
  9427. };
  9428. Scene.prototype.getPointerOverMesh = function () {
  9429. return this._pointerOverMesh;
  9430. };
  9431. // Physics
  9432. Scene.prototype.getPhysicsEngine = function () {
  9433. return this._physicsEngine;
  9434. };
  9435. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9436. if (this._physicsEngine) {
  9437. return true;
  9438. }
  9439. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9440. if (!this._physicsEngine.isSupported()) {
  9441. this._physicsEngine = null;
  9442. return false;
  9443. }
  9444. this._physicsEngine._initialize(gravity);
  9445. return true;
  9446. };
  9447. Scene.prototype.disablePhysicsEngine = function () {
  9448. if (!this._physicsEngine) {
  9449. return;
  9450. }
  9451. this._physicsEngine.dispose();
  9452. this._physicsEngine = undefined;
  9453. };
  9454. Scene.prototype.isPhysicsEnabled = function () {
  9455. return this._physicsEngine !== undefined;
  9456. };
  9457. Scene.prototype.setGravity = function (gravity) {
  9458. if (!this._physicsEngine) {
  9459. return;
  9460. }
  9461. this._physicsEngine._setGravity(gravity);
  9462. };
  9463. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9464. if (parts.parts) {
  9465. options = parts;
  9466. parts = parts.parts;
  9467. }
  9468. if (!this._physicsEngine) {
  9469. return null;
  9470. }
  9471. for (var index = 0; index < parts.length; index++) {
  9472. var mesh = parts[index].mesh;
  9473. mesh._physicImpostor = parts[index].impostor;
  9474. mesh._physicsMass = options.mass / parts.length;
  9475. mesh._physicsFriction = options.friction;
  9476. mesh._physicRestitution = options.restitution;
  9477. }
  9478. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9479. };
  9480. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9481. for (var index = 0; index < compound.parts.length; index++) {
  9482. var mesh = compound.parts[index].mesh;
  9483. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9484. this._physicsEngine._unregisterMesh(mesh);
  9485. }
  9486. };
  9487. // Misc.
  9488. Scene.prototype.createDefaultCameraOrLight = function () {
  9489. // Light
  9490. if (this.lights.length === 0) {
  9491. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9492. }
  9493. // Camera
  9494. if (!this.activeCamera) {
  9495. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9496. // Compute position
  9497. var worldExtends = this.getWorldExtends();
  9498. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9499. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9500. camera.setTarget(worldCenter);
  9501. this.activeCamera = camera;
  9502. }
  9503. };
  9504. // Tags
  9505. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9506. if (tagsQuery === undefined) {
  9507. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9508. return list;
  9509. }
  9510. var listByTags = [];
  9511. forEach = forEach || (function (item) {
  9512. return;
  9513. });
  9514. for (var i in list) {
  9515. var item = list[i];
  9516. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9517. listByTags.push(item);
  9518. forEach(item);
  9519. }
  9520. }
  9521. return listByTags;
  9522. };
  9523. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9524. return this._getByTags(this.meshes, tagsQuery, forEach);
  9525. };
  9526. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9527. return this._getByTags(this.cameras, tagsQuery, forEach);
  9528. };
  9529. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9530. return this._getByTags(this.lights, tagsQuery, forEach);
  9531. };
  9532. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9533. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9534. };
  9535. // Statics
  9536. Scene._FOGMODE_NONE = 0;
  9537. Scene._FOGMODE_EXP = 1;
  9538. Scene._FOGMODE_EXP2 = 2;
  9539. Scene._FOGMODE_LINEAR = 3;
  9540. Scene.MinDeltaTime = 1.0;
  9541. Scene.MaxDeltaTime = 1000.0;
  9542. return Scene;
  9543. })();
  9544. BABYLON.Scene = Scene;
  9545. })(BABYLON || (BABYLON = {}));
  9546. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9547. (function (BABYLON) {
  9548. var VertexBuffer = (function () {
  9549. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9550. if (engine instanceof BABYLON.Mesh) {
  9551. this._engine = engine.getScene().getEngine();
  9552. }
  9553. else {
  9554. this._engine = engine;
  9555. }
  9556. this._updatable = updatable;
  9557. this._data = data;
  9558. if (!postponeInternalCreation) {
  9559. this.create();
  9560. }
  9561. this._kind = kind;
  9562. if (stride) {
  9563. this._strideSize = stride;
  9564. return;
  9565. }
  9566. switch (kind) {
  9567. case VertexBuffer.PositionKind:
  9568. this._strideSize = 3;
  9569. break;
  9570. case VertexBuffer.NormalKind:
  9571. this._strideSize = 3;
  9572. break;
  9573. case VertexBuffer.UVKind:
  9574. this._strideSize = 2;
  9575. break;
  9576. case VertexBuffer.UV2Kind:
  9577. this._strideSize = 2;
  9578. break;
  9579. case VertexBuffer.ColorKind:
  9580. this._strideSize = 4;
  9581. break;
  9582. case VertexBuffer.MatricesIndicesKind:
  9583. this._strideSize = 4;
  9584. break;
  9585. case VertexBuffer.MatricesWeightsKind:
  9586. this._strideSize = 4;
  9587. break;
  9588. }
  9589. }
  9590. // Properties
  9591. VertexBuffer.prototype.isUpdatable = function () {
  9592. return this._updatable;
  9593. };
  9594. VertexBuffer.prototype.getData = function () {
  9595. return this._data;
  9596. };
  9597. VertexBuffer.prototype.getBuffer = function () {
  9598. return this._buffer;
  9599. };
  9600. VertexBuffer.prototype.getStrideSize = function () {
  9601. return this._strideSize;
  9602. };
  9603. // Methods
  9604. VertexBuffer.prototype.create = function (data) {
  9605. if (!data && this._buffer) {
  9606. return; // nothing to do
  9607. }
  9608. data = data || this._data;
  9609. if (!this._buffer) {
  9610. if (this._updatable) {
  9611. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9612. }
  9613. else {
  9614. this._buffer = this._engine.createVertexBuffer(data);
  9615. }
  9616. }
  9617. if (this._updatable) {
  9618. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9619. this._data = data;
  9620. }
  9621. };
  9622. VertexBuffer.prototype.update = function (data) {
  9623. this.create(data);
  9624. };
  9625. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9626. if (!this._buffer) {
  9627. return;
  9628. }
  9629. if (this._updatable) {
  9630. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9631. this._data = null;
  9632. }
  9633. };
  9634. VertexBuffer.prototype.dispose = function () {
  9635. if (!this._buffer) {
  9636. return;
  9637. }
  9638. if (this._engine._releaseBuffer(this._buffer)) {
  9639. this._buffer = null;
  9640. }
  9641. };
  9642. Object.defineProperty(VertexBuffer, "PositionKind", {
  9643. get: function () {
  9644. return VertexBuffer._PositionKind;
  9645. },
  9646. enumerable: true,
  9647. configurable: true
  9648. });
  9649. Object.defineProperty(VertexBuffer, "NormalKind", {
  9650. get: function () {
  9651. return VertexBuffer._NormalKind;
  9652. },
  9653. enumerable: true,
  9654. configurable: true
  9655. });
  9656. Object.defineProperty(VertexBuffer, "UVKind", {
  9657. get: function () {
  9658. return VertexBuffer._UVKind;
  9659. },
  9660. enumerable: true,
  9661. configurable: true
  9662. });
  9663. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9664. get: function () {
  9665. return VertexBuffer._UV2Kind;
  9666. },
  9667. enumerable: true,
  9668. configurable: true
  9669. });
  9670. Object.defineProperty(VertexBuffer, "ColorKind", {
  9671. get: function () {
  9672. return VertexBuffer._ColorKind;
  9673. },
  9674. enumerable: true,
  9675. configurable: true
  9676. });
  9677. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9678. get: function () {
  9679. return VertexBuffer._MatricesIndicesKind;
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9685. get: function () {
  9686. return VertexBuffer._MatricesWeightsKind;
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. // Enums
  9692. VertexBuffer._PositionKind = "position";
  9693. VertexBuffer._NormalKind = "normal";
  9694. VertexBuffer._UVKind = "uv";
  9695. VertexBuffer._UV2Kind = "uv2";
  9696. VertexBuffer._ColorKind = "color";
  9697. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9698. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9699. return VertexBuffer;
  9700. })();
  9701. BABYLON.VertexBuffer = VertexBuffer;
  9702. })(BABYLON || (BABYLON = {}));
  9703. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9704. var BABYLON;
  9705. (function (BABYLON) {
  9706. var AbstractMesh = (function (_super) {
  9707. __extends(AbstractMesh, _super);
  9708. function AbstractMesh(name, scene) {
  9709. _super.call(this, name, scene);
  9710. // Properties
  9711. this.definedFacingForward = true; // orientation for POV movement & rotation
  9712. this.position = new BABYLON.Vector3(0, 0, 0);
  9713. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9714. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9715. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9716. this.visibility = 1.0;
  9717. this.alphaIndex = Number.MAX_VALUE;
  9718. this.infiniteDistance = false;
  9719. this.isVisible = true;
  9720. this.isPickable = true;
  9721. this.showBoundingBox = false;
  9722. this.showSubMeshesBoundingBox = false;
  9723. this.onDispose = null;
  9724. this.checkCollisions = false;
  9725. this.isBlocker = false;
  9726. this.renderingGroupId = 0;
  9727. this.receiveShadows = false;
  9728. this.renderOutline = false;
  9729. this.outlineColor = BABYLON.Color3.Red();
  9730. this.outlineWidth = 0.02;
  9731. this.renderOverlay = false;
  9732. this.overlayColor = BABYLON.Color3.Red();
  9733. this.overlayAlpha = 0.5;
  9734. this.hasVertexAlpha = false;
  9735. this.useVertexColors = true;
  9736. this.applyFog = true;
  9737. this.useOctreeForRenderingSelection = true;
  9738. this.useOctreeForPicking = true;
  9739. this.useOctreeForCollisions = true;
  9740. this.layerMask = 0xFFFFFFFF;
  9741. // Physics
  9742. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9743. // Collisions
  9744. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9745. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9746. this._collider = new BABYLON.Collider();
  9747. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9748. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9749. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9750. // Cache
  9751. this._localScaling = BABYLON.Matrix.Zero();
  9752. this._localRotation = BABYLON.Matrix.Zero();
  9753. this._localTranslation = BABYLON.Matrix.Zero();
  9754. this._localBillboard = BABYLON.Matrix.Zero();
  9755. this._localPivotScaling = BABYLON.Matrix.Zero();
  9756. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9757. this._localWorld = BABYLON.Matrix.Zero();
  9758. this._worldMatrix = BABYLON.Matrix.Zero();
  9759. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9760. this._absolutePosition = BABYLON.Vector3.Zero();
  9761. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9762. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9763. this._isDirty = false;
  9764. this._pivotMatrix = BABYLON.Matrix.Identity();
  9765. this._isDisposed = false;
  9766. this._renderId = 0;
  9767. this._intersectionsInProgress = new Array();
  9768. this._onAfterWorldMatrixUpdate = new Array();
  9769. scene.addMesh(this);
  9770. }
  9771. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9772. get: function () {
  9773. return AbstractMesh._BILLBOARDMODE_NONE;
  9774. },
  9775. enumerable: true,
  9776. configurable: true
  9777. });
  9778. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9779. get: function () {
  9780. return AbstractMesh._BILLBOARDMODE_X;
  9781. },
  9782. enumerable: true,
  9783. configurable: true
  9784. });
  9785. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9786. get: function () {
  9787. return AbstractMesh._BILLBOARDMODE_Y;
  9788. },
  9789. enumerable: true,
  9790. configurable: true
  9791. });
  9792. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9793. get: function () {
  9794. return AbstractMesh._BILLBOARDMODE_Z;
  9795. },
  9796. enumerable: true,
  9797. configurable: true
  9798. });
  9799. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9800. get: function () {
  9801. return AbstractMesh._BILLBOARDMODE_ALL;
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9807. // Methods
  9808. get: function () {
  9809. return false;
  9810. },
  9811. enumerable: true,
  9812. configurable: true
  9813. });
  9814. AbstractMesh.prototype.getLOD = function (camera) {
  9815. return this;
  9816. };
  9817. AbstractMesh.prototype.getTotalVertices = function () {
  9818. return 0;
  9819. };
  9820. AbstractMesh.prototype.getIndices = function () {
  9821. return null;
  9822. };
  9823. AbstractMesh.prototype.getVerticesData = function (kind) {
  9824. return null;
  9825. };
  9826. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9827. return false;
  9828. };
  9829. AbstractMesh.prototype.getBoundingInfo = function () {
  9830. if (this._masterMesh) {
  9831. return this._masterMesh.getBoundingInfo();
  9832. }
  9833. if (!this._boundingInfo) {
  9834. this._updateBoundingInfo();
  9835. }
  9836. return this._boundingInfo;
  9837. };
  9838. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9839. get: function () {
  9840. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. AbstractMesh.prototype._preActivate = function () {
  9846. };
  9847. AbstractMesh.prototype._activate = function (renderId) {
  9848. this._renderId = renderId;
  9849. };
  9850. AbstractMesh.prototype.getWorldMatrix = function () {
  9851. if (this._masterMesh) {
  9852. return this._masterMesh.getWorldMatrix();
  9853. }
  9854. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9855. this.computeWorldMatrix();
  9856. }
  9857. return this._worldMatrix;
  9858. };
  9859. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9860. get: function () {
  9861. return this._worldMatrix;
  9862. },
  9863. enumerable: true,
  9864. configurable: true
  9865. });
  9866. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9867. get: function () {
  9868. return this._absolutePosition;
  9869. },
  9870. enumerable: true,
  9871. configurable: true
  9872. });
  9873. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9874. if (!this.rotationQuaternion) {
  9875. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9876. this.rotation = BABYLON.Vector3.Zero();
  9877. }
  9878. if (!space || space === 0 /* LOCAL */) {
  9879. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9880. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9881. }
  9882. else {
  9883. if (this.parent) {
  9884. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9885. invertParentWorldMatrix.invert();
  9886. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9887. }
  9888. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9889. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9890. }
  9891. };
  9892. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9893. var displacementVector = axis.scale(distance);
  9894. if (!space || space === 0 /* LOCAL */) {
  9895. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9896. this.setPositionWithLocalVector(tempV3);
  9897. }
  9898. else {
  9899. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9900. }
  9901. };
  9902. AbstractMesh.prototype.getAbsolutePosition = function () {
  9903. this.computeWorldMatrix();
  9904. return this._absolutePosition;
  9905. };
  9906. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9907. if (!absolutePosition) {
  9908. return;
  9909. }
  9910. var absolutePositionX;
  9911. var absolutePositionY;
  9912. var absolutePositionZ;
  9913. if (absolutePosition.x === undefined) {
  9914. if (arguments.length < 3) {
  9915. return;
  9916. }
  9917. absolutePositionX = arguments[0];
  9918. absolutePositionY = arguments[1];
  9919. absolutePositionZ = arguments[2];
  9920. }
  9921. else {
  9922. absolutePositionX = absolutePosition.x;
  9923. absolutePositionY = absolutePosition.y;
  9924. absolutePositionZ = absolutePosition.z;
  9925. }
  9926. if (this.parent) {
  9927. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9928. invertParentWorldMatrix.invert();
  9929. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9930. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9931. }
  9932. else {
  9933. this.position.x = absolutePositionX;
  9934. this.position.y = absolutePositionY;
  9935. this.position.z = absolutePositionZ;
  9936. }
  9937. };
  9938. // ================================== Point of View Movement =================================
  9939. /**
  9940. * Perform relative position change from the point of view of behind the front of the mesh.
  9941. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9942. * Supports definition of mesh facing forward or backward.
  9943. * @param {number} amountRight
  9944. * @param {number} amountUp
  9945. * @param {number} amountForward
  9946. */
  9947. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9948. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9949. };
  9950. /**
  9951. * Calculate relative position change from the point of view of behind the front of the mesh.
  9952. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9953. * Supports definition of mesh facing forward or backward.
  9954. * @param {number} amountRight
  9955. * @param {number} amountUp
  9956. * @param {number} amountForward
  9957. */
  9958. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9959. var rotMatrix = new BABYLON.Matrix();
  9960. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9961. rotQuaternion.toRotationMatrix(rotMatrix);
  9962. var translationDelta = BABYLON.Vector3.Zero();
  9963. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9964. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9965. return translationDelta;
  9966. };
  9967. // ================================== Point of View Rotation =================================
  9968. /**
  9969. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9970. * Supports definition of mesh facing forward or backward.
  9971. * @param {number} flipBack
  9972. * @param {number} twirlClockwise
  9973. * @param {number} tiltRight
  9974. */
  9975. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9976. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9977. };
  9978. /**
  9979. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9980. * Supports definition of mesh facing forward or backward.
  9981. * @param {number} flipBack
  9982. * @param {number} twirlClockwise
  9983. * @param {number} tiltRight
  9984. */
  9985. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9986. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9987. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9988. };
  9989. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9990. this._pivotMatrix = matrix;
  9991. this._cache.pivotMatrixUpdated = true;
  9992. };
  9993. AbstractMesh.prototype.getPivotMatrix = function () {
  9994. return this._pivotMatrix;
  9995. };
  9996. AbstractMesh.prototype._isSynchronized = function () {
  9997. if (this._isDirty) {
  9998. return false;
  9999. }
  10000. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10001. return false;
  10002. if (this._cache.pivotMatrixUpdated) {
  10003. return false;
  10004. }
  10005. if (this.infiniteDistance) {
  10006. return false;
  10007. }
  10008. if (!this._cache.position.equals(this.position))
  10009. return false;
  10010. if (this.rotationQuaternion) {
  10011. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10012. return false;
  10013. }
  10014. else {
  10015. if (!this._cache.rotation.equals(this.rotation))
  10016. return false;
  10017. }
  10018. if (!this._cache.scaling.equals(this.scaling))
  10019. return false;
  10020. return true;
  10021. };
  10022. AbstractMesh.prototype._initCache = function () {
  10023. _super.prototype._initCache.call(this);
  10024. this._cache.localMatrixUpdated = false;
  10025. this._cache.position = BABYLON.Vector3.Zero();
  10026. this._cache.scaling = BABYLON.Vector3.Zero();
  10027. this._cache.rotation = BABYLON.Vector3.Zero();
  10028. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10029. };
  10030. AbstractMesh.prototype.markAsDirty = function (property) {
  10031. if (property === "rotation") {
  10032. this.rotationQuaternion = null;
  10033. }
  10034. this._currentRenderId = Number.MAX_VALUE;
  10035. this._isDirty = true;
  10036. };
  10037. AbstractMesh.prototype._updateBoundingInfo = function () {
  10038. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10039. this._boundingInfo._update(this.worldMatrixFromCache);
  10040. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10041. };
  10042. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10043. if (!this.subMeshes) {
  10044. return;
  10045. }
  10046. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10047. var subMesh = this.subMeshes[subIndex];
  10048. subMesh.updateBoundingInfo(matrix);
  10049. }
  10050. };
  10051. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10052. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10053. return this._worldMatrix;
  10054. }
  10055. this._cache.position.copyFrom(this.position);
  10056. this._cache.scaling.copyFrom(this.scaling);
  10057. this._cache.pivotMatrixUpdated = false;
  10058. this._currentRenderId = this.getScene().getRenderId();
  10059. this._isDirty = false;
  10060. // Scaling
  10061. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10062. // Rotation
  10063. if (this.rotationQuaternion) {
  10064. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10065. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10066. }
  10067. else {
  10068. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10069. this._cache.rotation.copyFrom(this.rotation);
  10070. }
  10071. // Translation
  10072. if (this.infiniteDistance && !this.parent) {
  10073. var camera = this.getScene().activeCamera;
  10074. var cameraWorldMatrix = camera.getWorldMatrix();
  10075. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10076. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10077. }
  10078. else {
  10079. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10080. }
  10081. // Composing transformations
  10082. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10083. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10084. // Billboarding
  10085. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10086. var localPosition = this.position.clone();
  10087. var zero = this.getScene().activeCamera.position.clone();
  10088. if (this.parent && this.parent.position) {
  10089. localPosition.addInPlace(this.parent.position);
  10090. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10091. }
  10092. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10093. zero = this.getScene().activeCamera.position;
  10094. }
  10095. else {
  10096. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10097. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10098. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10099. zero.y = localPosition.y + 0.001;
  10100. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10101. zero.z = localPosition.z + 0.001;
  10102. }
  10103. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10104. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10105. this._localBillboard.invert();
  10106. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10107. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10108. }
  10109. // Local world
  10110. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10111. // Parent
  10112. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10113. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10114. }
  10115. else {
  10116. this._worldMatrix.copyFrom(this._localWorld);
  10117. }
  10118. // Bounding info
  10119. this._updateBoundingInfo();
  10120. // Absolute position
  10121. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10122. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10123. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10124. }
  10125. return this._worldMatrix;
  10126. };
  10127. /**
  10128. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10129. * @param func: callback function to add
  10130. */
  10131. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10132. this._onAfterWorldMatrixUpdate.push(func);
  10133. };
  10134. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10135. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10136. if (index > -1) {
  10137. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10138. }
  10139. };
  10140. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10141. this.computeWorldMatrix();
  10142. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10143. };
  10144. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10145. this.computeWorldMatrix();
  10146. var invLocalWorldMatrix = this._localWorld.clone();
  10147. invLocalWorldMatrix.invert();
  10148. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10149. };
  10150. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10151. this.computeWorldMatrix();
  10152. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10153. };
  10154. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10155. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10156. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10157. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10158. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10159. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10160. /// <returns>Mesh oriented towards targetMesh</returns>
  10161. yawCor = yawCor || 0; // default to zero if undefined
  10162. pitchCor = pitchCor || 0;
  10163. rollCor = rollCor || 0;
  10164. var dv = targetPoint.subtract(this.position);
  10165. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10166. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10167. var pitch = Math.atan2(dv.y, len);
  10168. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10169. };
  10170. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10171. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10172. return false;
  10173. }
  10174. return true;
  10175. };
  10176. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10177. if (!camera) {
  10178. camera = this.getScene().activeCamera;
  10179. }
  10180. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10181. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10182. return false;
  10183. }
  10184. return true;
  10185. };
  10186. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10187. if (!this._boundingInfo || !mesh._boundingInfo) {
  10188. return false;
  10189. }
  10190. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10191. };
  10192. AbstractMesh.prototype.intersectsPoint = function (point) {
  10193. if (!this._boundingInfo) {
  10194. return false;
  10195. }
  10196. return this._boundingInfo.intersectsPoint(point);
  10197. };
  10198. // Physics
  10199. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10200. var physicsEngine = this.getScene().getPhysicsEngine();
  10201. if (!physicsEngine) {
  10202. return;
  10203. }
  10204. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10205. if (impostor.impostor) {
  10206. // Old API
  10207. options = impostor;
  10208. impostor = impostor.impostor;
  10209. }
  10210. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10211. physicsEngine._unregisterMesh(this);
  10212. return;
  10213. }
  10214. if (!options) {
  10215. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10216. }
  10217. else {
  10218. if (!options.mass && options.mass !== 0)
  10219. options.mass = 0;
  10220. if (!options.friction && options.friction !== 0)
  10221. options.friction = 0.2;
  10222. if (!options.restitution && options.restitution !== 0)
  10223. options.restitution = 0.2;
  10224. }
  10225. this._physicImpostor = impostor;
  10226. this._physicsMass = options.mass;
  10227. this._physicsFriction = options.friction;
  10228. this._physicRestitution = options.restitution;
  10229. return physicsEngine._registerMesh(this, impostor, options);
  10230. };
  10231. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10232. if (!this._physicImpostor) {
  10233. return BABYLON.PhysicsEngine.NoImpostor;
  10234. }
  10235. return this._physicImpostor;
  10236. };
  10237. AbstractMesh.prototype.getPhysicsMass = function () {
  10238. if (!this._physicsMass) {
  10239. return 0;
  10240. }
  10241. return this._physicsMass;
  10242. };
  10243. AbstractMesh.prototype.getPhysicsFriction = function () {
  10244. if (!this._physicsFriction) {
  10245. return 0;
  10246. }
  10247. return this._physicsFriction;
  10248. };
  10249. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10250. if (!this._physicRestitution) {
  10251. return 0;
  10252. }
  10253. return this._physicRestitution;
  10254. };
  10255. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10256. if (!camera) {
  10257. camera = this.getScene().activeCamera;
  10258. }
  10259. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10260. };
  10261. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10262. if (!camera) {
  10263. camera = this.getScene().activeCamera;
  10264. }
  10265. return this.absolutePosition.subtract(camera.position).length();
  10266. };
  10267. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10268. if (!this._physicImpostor) {
  10269. return;
  10270. }
  10271. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10272. };
  10273. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10274. if (!this._physicImpostor) {
  10275. return;
  10276. }
  10277. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10278. };
  10279. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10280. if (!this._physicImpostor) {
  10281. return;
  10282. }
  10283. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10284. };
  10285. // Collisions
  10286. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10287. var globalPosition = this.getAbsolutePosition();
  10288. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10289. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10290. this._collider.radius = this.ellipsoid;
  10291. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10292. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10293. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10294. this.position.addInPlace(this._diffPositionForCollisions);
  10295. }
  10296. };
  10297. // Submeshes octree
  10298. /**
  10299. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10300. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10301. */
  10302. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10303. if (maxCapacity === void 0) { maxCapacity = 64; }
  10304. if (maxDepth === void 0) { maxDepth = 2; }
  10305. if (!this._submeshesOctree) {
  10306. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10307. }
  10308. this.computeWorldMatrix(true);
  10309. // Update octree
  10310. var bbox = this.getBoundingInfo().boundingBox;
  10311. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10312. return this._submeshesOctree;
  10313. };
  10314. // Collisions
  10315. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10316. this._generatePointsArray();
  10317. // Transformation
  10318. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10319. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10320. subMesh._lastColliderWorldVertices = [];
  10321. subMesh._trianglePlanes = [];
  10322. var start = subMesh.verticesStart;
  10323. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10324. for (var i = start; i < end; i++) {
  10325. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10326. }
  10327. }
  10328. // Collide
  10329. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10330. };
  10331. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10332. var subMeshes;
  10333. var len;
  10334. // Octrees
  10335. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10336. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10337. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10338. len = intersections.length;
  10339. subMeshes = intersections.data;
  10340. }
  10341. else {
  10342. subMeshes = this.subMeshes;
  10343. len = subMeshes.length;
  10344. }
  10345. for (var index = 0; index < len; index++) {
  10346. var subMesh = subMeshes[index];
  10347. // Bounding test
  10348. if (len > 1 && !subMesh._checkCollision(collider))
  10349. continue;
  10350. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10351. }
  10352. };
  10353. AbstractMesh.prototype._checkCollision = function (collider) {
  10354. // Bounding box test
  10355. if (!this._boundingInfo._checkCollision(collider))
  10356. return;
  10357. // Transformation matrix
  10358. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10359. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10360. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10361. };
  10362. // Picking
  10363. AbstractMesh.prototype._generatePointsArray = function () {
  10364. return false;
  10365. };
  10366. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10367. var pickingInfo = new BABYLON.PickingInfo();
  10368. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10369. return pickingInfo;
  10370. }
  10371. if (!this._generatePointsArray()) {
  10372. return pickingInfo;
  10373. }
  10374. var intersectInfo = null;
  10375. // Octrees
  10376. var subMeshes;
  10377. var len;
  10378. if (this._submeshesOctree && this.useOctreeForPicking) {
  10379. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10380. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10381. len = intersections.length;
  10382. subMeshes = intersections.data;
  10383. }
  10384. else {
  10385. subMeshes = this.subMeshes;
  10386. len = subMeshes.length;
  10387. }
  10388. for (var index = 0; index < len; index++) {
  10389. var subMesh = subMeshes[index];
  10390. // Bounding test
  10391. if (len > 1 && !subMesh.canIntersects(ray))
  10392. continue;
  10393. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10394. if (currentIntersectInfo) {
  10395. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10396. intersectInfo = currentIntersectInfo;
  10397. intersectInfo.subMeshId = index;
  10398. if (fastCheck) {
  10399. break;
  10400. }
  10401. }
  10402. }
  10403. }
  10404. if (intersectInfo) {
  10405. // Get picked point
  10406. var world = this.getWorldMatrix();
  10407. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10408. var direction = ray.direction.clone();
  10409. direction = direction.scale(intersectInfo.distance);
  10410. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10411. var pickedPoint = worldOrigin.add(worldDirection);
  10412. // Return result
  10413. pickingInfo.hit = true;
  10414. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10415. pickingInfo.pickedPoint = pickedPoint;
  10416. pickingInfo.pickedMesh = this;
  10417. pickingInfo.bu = intersectInfo.bu;
  10418. pickingInfo.bv = intersectInfo.bv;
  10419. pickingInfo.faceId = intersectInfo.faceId;
  10420. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10421. return pickingInfo;
  10422. }
  10423. return pickingInfo;
  10424. };
  10425. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10426. return null;
  10427. };
  10428. AbstractMesh.prototype.releaseSubMeshes = function () {
  10429. if (this.subMeshes) {
  10430. while (this.subMeshes.length) {
  10431. this.subMeshes[0].dispose();
  10432. }
  10433. }
  10434. else {
  10435. this.subMeshes = new Array();
  10436. }
  10437. };
  10438. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10439. var index;
  10440. // Physics
  10441. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10442. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10443. }
  10444. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10445. var other = this._intersectionsInProgress[index];
  10446. var pos = other._intersectionsInProgress.indexOf(this);
  10447. other._intersectionsInProgress.splice(pos, 1);
  10448. }
  10449. this._intersectionsInProgress = [];
  10450. // SubMeshes
  10451. this.releaseSubMeshes();
  10452. // Remove from scene
  10453. this.getScene().removeMesh(this);
  10454. if (!doNotRecurse) {
  10455. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10456. if (this.getScene().particleSystems[index].emitter === this) {
  10457. this.getScene().particleSystems[index].dispose();
  10458. index--;
  10459. }
  10460. }
  10461. // Children
  10462. var objects = this.getScene().meshes.slice(0);
  10463. for (index = 0; index < objects.length; index++) {
  10464. if (objects[index].parent === this) {
  10465. objects[index].dispose();
  10466. }
  10467. }
  10468. }
  10469. else {
  10470. for (index = 0; index < this.getScene().meshes.length; index++) {
  10471. var obj = this.getScene().meshes[index];
  10472. if (obj.parent === this) {
  10473. obj.parent = null;
  10474. obj.computeWorldMatrix(true);
  10475. }
  10476. }
  10477. }
  10478. this._onAfterWorldMatrixUpdate = [];
  10479. this._isDisposed = true;
  10480. // Callback
  10481. if (this.onDispose) {
  10482. this.onDispose();
  10483. }
  10484. };
  10485. // Statics
  10486. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10487. AbstractMesh._BILLBOARDMODE_X = 1;
  10488. AbstractMesh._BILLBOARDMODE_Y = 2;
  10489. AbstractMesh._BILLBOARDMODE_Z = 4;
  10490. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10491. return AbstractMesh;
  10492. })(BABYLON.Node);
  10493. BABYLON.AbstractMesh = AbstractMesh;
  10494. })(BABYLON || (BABYLON = {}));
  10495. //# sourceMappingURL=babylon.abstractMesh.js.map
  10496. var BABYLON;
  10497. (function (BABYLON) {
  10498. var _InstancesBatch = (function () {
  10499. function _InstancesBatch() {
  10500. this.mustReturn = false;
  10501. this.visibleInstances = new Array();
  10502. this.renderSelf = new Array();
  10503. }
  10504. return _InstancesBatch;
  10505. })();
  10506. BABYLON._InstancesBatch = _InstancesBatch;
  10507. var Mesh = (function (_super) {
  10508. __extends(Mesh, _super);
  10509. /**
  10510. * @constructor
  10511. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10512. * @param {Scene} scene - The scene to add this mesh to.
  10513. * @param {Node} parent - The parent of this mesh, if it has one
  10514. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10515. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10516. * When false, achieved by calling a clone(), also passing False.
  10517. * This will make creation of children, recursive.
  10518. */
  10519. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10520. if (parent === void 0) { parent = null; }
  10521. _super.call(this, name, scene);
  10522. // Members
  10523. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10524. this.instances = new Array();
  10525. this._LODLevels = new Array();
  10526. this._onBeforeRenderCallbacks = new Array();
  10527. this._onAfterRenderCallbacks = new Array();
  10528. this._visibleInstances = {};
  10529. this._renderIdForInstances = new Array();
  10530. this._batchCache = new _InstancesBatch();
  10531. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10532. if (source) {
  10533. // Geometry
  10534. if (source._geometry) {
  10535. source._geometry.applyToMesh(this);
  10536. }
  10537. // Deep copy
  10538. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10539. // Material
  10540. this.material = source.material;
  10541. if (!doNotCloneChildren) {
  10542. for (var index = 0; index < scene.meshes.length; index++) {
  10543. var mesh = scene.meshes[index];
  10544. if (mesh.parent === source) {
  10545. // doNotCloneChildren is always going to be False
  10546. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10547. }
  10548. }
  10549. }
  10550. for (index = 0; index < scene.particleSystems.length; index++) {
  10551. var system = scene.particleSystems[index];
  10552. if (system.emitter === source) {
  10553. system.clone(system.name, this);
  10554. }
  10555. }
  10556. this.computeWorldMatrix(true);
  10557. }
  10558. // Parent
  10559. if (parent !== null) {
  10560. this.parent = parent;
  10561. }
  10562. }
  10563. Object.defineProperty(Mesh, "FRONTSIDE", {
  10564. get: function () {
  10565. return Mesh._FRONTSIDE;
  10566. },
  10567. enumerable: true,
  10568. configurable: true
  10569. });
  10570. Object.defineProperty(Mesh, "BACKSIDE", {
  10571. get: function () {
  10572. return Mesh._BACKSIDE;
  10573. },
  10574. enumerable: true,
  10575. configurable: true
  10576. });
  10577. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10578. get: function () {
  10579. return Mesh._DOUBLESIDE;
  10580. },
  10581. enumerable: true,
  10582. configurable: true
  10583. });
  10584. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10585. get: function () {
  10586. return Mesh._DEFAULTSIDE;
  10587. },
  10588. enumerable: true,
  10589. configurable: true
  10590. });
  10591. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10592. // Methods
  10593. get: function () {
  10594. return this._LODLevels.length > 0;
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. Mesh.prototype._sortLODLevels = function () {
  10600. this._LODLevels.sort(function (a, b) {
  10601. if (a.distance < b.distance) {
  10602. return 1;
  10603. }
  10604. if (a.distance > b.distance) {
  10605. return -1;
  10606. }
  10607. return 0;
  10608. });
  10609. };
  10610. /**
  10611. * Add a mesh as LOD level triggered at the given distance.
  10612. * @param {number} distance - the distance from the center of the object to show this level
  10613. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10614. * @return {BABYLON.Mesh} this mesh (for chaining)
  10615. */
  10616. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10617. if (mesh && mesh._masterMesh) {
  10618. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10619. return this;
  10620. }
  10621. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10622. this._LODLevels.push(level);
  10623. if (mesh) {
  10624. mesh._masterMesh = this;
  10625. }
  10626. this._sortLODLevels();
  10627. return this;
  10628. };
  10629. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10630. for (var index = 0; index < this._LODLevels.length; index++) {
  10631. var level = this._LODLevels[index];
  10632. if (level.distance === distance) {
  10633. return level.mesh;
  10634. }
  10635. }
  10636. return null;
  10637. };
  10638. /**
  10639. * Remove a mesh from the LOD array
  10640. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10641. * @return {BABYLON.Mesh} this mesh (for chaining)
  10642. */
  10643. Mesh.prototype.removeLODLevel = function (mesh) {
  10644. for (var index = 0; index < this._LODLevels.length; index++) {
  10645. if (this._LODLevels[index].mesh === mesh) {
  10646. this._LODLevels.splice(index, 1);
  10647. if (mesh) {
  10648. mesh._masterMesh = null;
  10649. }
  10650. }
  10651. }
  10652. this._sortLODLevels();
  10653. return this;
  10654. };
  10655. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10656. if (!this._LODLevels || this._LODLevels.length === 0) {
  10657. return this;
  10658. }
  10659. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10660. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10661. return this;
  10662. }
  10663. for (var index = 0; index < this._LODLevels.length; index++) {
  10664. var level = this._LODLevels[index];
  10665. if (level.distance < distanceToCamera) {
  10666. if (level.mesh) {
  10667. level.mesh._preActivate();
  10668. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10669. }
  10670. return level.mesh;
  10671. }
  10672. }
  10673. return this;
  10674. };
  10675. Object.defineProperty(Mesh.prototype, "geometry", {
  10676. get: function () {
  10677. return this._geometry;
  10678. },
  10679. enumerable: true,
  10680. configurable: true
  10681. });
  10682. Mesh.prototype.getTotalVertices = function () {
  10683. if (!this._geometry) {
  10684. return 0;
  10685. }
  10686. return this._geometry.getTotalVertices();
  10687. };
  10688. Mesh.prototype.getVerticesData = function (kind) {
  10689. if (!this._geometry) {
  10690. return null;
  10691. }
  10692. return this._geometry.getVerticesData(kind);
  10693. };
  10694. Mesh.prototype.getVertexBuffer = function (kind) {
  10695. if (!this._geometry) {
  10696. return undefined;
  10697. }
  10698. return this._geometry.getVertexBuffer(kind);
  10699. };
  10700. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10701. if (!this._geometry) {
  10702. if (this._delayInfo) {
  10703. return this._delayInfo.indexOf(kind) !== -1;
  10704. }
  10705. return false;
  10706. }
  10707. return this._geometry.isVerticesDataPresent(kind);
  10708. };
  10709. Mesh.prototype.getVerticesDataKinds = function () {
  10710. if (!this._geometry) {
  10711. var result = [];
  10712. if (this._delayInfo) {
  10713. for (var kind in this._delayInfo) {
  10714. result.push(kind);
  10715. }
  10716. }
  10717. return result;
  10718. }
  10719. return this._geometry.getVerticesDataKinds();
  10720. };
  10721. Mesh.prototype.getTotalIndices = function () {
  10722. if (!this._geometry) {
  10723. return 0;
  10724. }
  10725. return this._geometry.getTotalIndices();
  10726. };
  10727. Mesh.prototype.getIndices = function () {
  10728. if (!this._geometry) {
  10729. return [];
  10730. }
  10731. return this._geometry.getIndices();
  10732. };
  10733. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10734. get: function () {
  10735. return this._masterMesh !== null && this._masterMesh !== undefined;
  10736. },
  10737. enumerable: true,
  10738. configurable: true
  10739. });
  10740. Mesh.prototype.isReady = function () {
  10741. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10742. return false;
  10743. }
  10744. return _super.prototype.isReady.call(this);
  10745. };
  10746. Mesh.prototype.isDisposed = function () {
  10747. return this._isDisposed;
  10748. };
  10749. // Methods
  10750. Mesh.prototype._preActivate = function () {
  10751. var sceneRenderId = this.getScene().getRenderId();
  10752. if (this._preActivateId === sceneRenderId) {
  10753. return;
  10754. }
  10755. this._preActivateId = sceneRenderId;
  10756. this._visibleInstances = null;
  10757. };
  10758. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10759. if (!this._visibleInstances) {
  10760. this._visibleInstances = {};
  10761. this._visibleInstances.defaultRenderId = renderId;
  10762. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10763. }
  10764. if (!this._visibleInstances[renderId]) {
  10765. this._visibleInstances[renderId] = new Array();
  10766. }
  10767. this._visibleInstances[renderId].push(instance);
  10768. };
  10769. Mesh.prototype.refreshBoundingInfo = function () {
  10770. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10771. if (data) {
  10772. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10773. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10774. }
  10775. if (this.subMeshes) {
  10776. for (var index = 0; index < this.subMeshes.length; index++) {
  10777. this.subMeshes[index].refreshBoundingInfo();
  10778. }
  10779. }
  10780. this._updateBoundingInfo();
  10781. };
  10782. Mesh.prototype._createGlobalSubMesh = function () {
  10783. var totalVertices = this.getTotalVertices();
  10784. if (!totalVertices || !this.getIndices()) {
  10785. return null;
  10786. }
  10787. this.releaseSubMeshes();
  10788. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10789. };
  10790. Mesh.prototype.subdivide = function (count) {
  10791. if (count < 1) {
  10792. return;
  10793. }
  10794. var totalIndices = this.getTotalIndices();
  10795. var subdivisionSize = (totalIndices / count) | 0;
  10796. var offset = 0;
  10797. while (subdivisionSize % 3 !== 0) {
  10798. subdivisionSize++;
  10799. }
  10800. this.releaseSubMeshes();
  10801. for (var index = 0; index < count; index++) {
  10802. if (offset >= totalIndices) {
  10803. break;
  10804. }
  10805. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10806. offset += subdivisionSize;
  10807. }
  10808. this.synchronizeInstances();
  10809. };
  10810. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10811. if (kind instanceof Array) {
  10812. var temp = data;
  10813. data = kind;
  10814. kind = temp;
  10815. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10816. }
  10817. if (!this._geometry) {
  10818. var vertexData = new BABYLON.VertexData();
  10819. vertexData.set(data, kind);
  10820. var scene = this.getScene();
  10821. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10822. }
  10823. else {
  10824. this._geometry.setVerticesData(kind, data, updatable, stride);
  10825. }
  10826. };
  10827. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10828. if (!this._geometry) {
  10829. return;
  10830. }
  10831. if (!makeItUnique) {
  10832. this._geometry.updateVerticesData(kind, data, updateExtends);
  10833. }
  10834. else {
  10835. this.makeGeometryUnique();
  10836. this.updateVerticesData(kind, data, updateExtends, false);
  10837. }
  10838. };
  10839. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10840. if (!this._geometry) {
  10841. return;
  10842. }
  10843. if (!makeItUnique) {
  10844. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10845. }
  10846. else {
  10847. this.makeGeometryUnique();
  10848. this.updateVerticesDataDirectly(kind, data, offset, false);
  10849. }
  10850. };
  10851. Mesh.prototype.makeGeometryUnique = function () {
  10852. if (!this._geometry) {
  10853. return;
  10854. }
  10855. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10856. geometry.applyToMesh(this);
  10857. };
  10858. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10859. if (!this._geometry) {
  10860. var vertexData = new BABYLON.VertexData();
  10861. vertexData.indices = indices;
  10862. var scene = this.getScene();
  10863. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10864. }
  10865. else {
  10866. this._geometry.setIndices(indices, totalVertices);
  10867. }
  10868. };
  10869. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10870. var engine = this.getScene().getEngine();
  10871. // Wireframe
  10872. var indexToBind;
  10873. switch (fillMode) {
  10874. case BABYLON.Material.PointFillMode:
  10875. indexToBind = null;
  10876. break;
  10877. case BABYLON.Material.WireFrameFillMode:
  10878. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10879. break;
  10880. default:
  10881. case BABYLON.Material.TriangleFillMode:
  10882. indexToBind = this._geometry.getIndexBuffer();
  10883. break;
  10884. }
  10885. // VBOs
  10886. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10887. };
  10888. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10889. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10890. return;
  10891. }
  10892. var engine = this.getScene().getEngine();
  10893. switch (fillMode) {
  10894. case BABYLON.Material.PointFillMode:
  10895. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10896. break;
  10897. case BABYLON.Material.WireFrameFillMode:
  10898. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10899. break;
  10900. default:
  10901. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10902. }
  10903. };
  10904. Mesh.prototype.registerBeforeRender = function (func) {
  10905. this._onBeforeRenderCallbacks.push(func);
  10906. };
  10907. Mesh.prototype.unregisterBeforeRender = function (func) {
  10908. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10909. if (index > -1) {
  10910. this._onBeforeRenderCallbacks.splice(index, 1);
  10911. }
  10912. };
  10913. Mesh.prototype.registerAfterRender = function (func) {
  10914. this._onAfterRenderCallbacks.push(func);
  10915. };
  10916. Mesh.prototype.unregisterAfterRender = function (func) {
  10917. var index = this._onAfterRenderCallbacks.indexOf(func);
  10918. if (index > -1) {
  10919. this._onAfterRenderCallbacks.splice(index, 1);
  10920. }
  10921. };
  10922. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10923. var scene = this.getScene();
  10924. this._batchCache.mustReturn = false;
  10925. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10926. this._batchCache.visibleInstances[subMeshId] = null;
  10927. if (this._visibleInstances) {
  10928. var currentRenderId = scene.getRenderId();
  10929. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10930. var selfRenderId = this._renderId;
  10931. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10932. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10933. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10934. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10935. }
  10936. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10937. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10938. this._batchCache.mustReturn = true;
  10939. return this._batchCache;
  10940. }
  10941. if (currentRenderId !== selfRenderId) {
  10942. this._batchCache.renderSelf[subMeshId] = false;
  10943. }
  10944. }
  10945. this._renderIdForInstances[subMeshId] = currentRenderId;
  10946. }
  10947. return this._batchCache;
  10948. };
  10949. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10950. var visibleInstances = batch.visibleInstances[subMesh._id];
  10951. var matricesCount = visibleInstances.length + 1;
  10952. var bufferSize = matricesCount * 16 * 4;
  10953. while (this._instancesBufferSize < bufferSize) {
  10954. this._instancesBufferSize *= 2;
  10955. }
  10956. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10957. if (this._worldMatricesInstancesBuffer) {
  10958. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10959. }
  10960. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10961. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10962. }
  10963. var offset = 0;
  10964. var instancesCount = 0;
  10965. var world = this.getWorldMatrix();
  10966. if (batch.renderSelf[subMesh._id]) {
  10967. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10968. offset += 16;
  10969. instancesCount++;
  10970. }
  10971. if (visibleInstances) {
  10972. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10973. var instance = visibleInstances[instanceIndex];
  10974. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10975. offset += 16;
  10976. instancesCount++;
  10977. }
  10978. }
  10979. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10980. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10981. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10982. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10983. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10984. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10985. this._draw(subMesh, fillMode, instancesCount);
  10986. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10987. };
  10988. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10989. var scene = this.getScene();
  10990. var engine = scene.getEngine();
  10991. if (hardwareInstancedRendering) {
  10992. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10993. }
  10994. else {
  10995. if (batch.renderSelf[subMesh._id]) {
  10996. // Draw
  10997. if (onBeforeDraw) {
  10998. onBeforeDraw(false, this.getWorldMatrix());
  10999. }
  11000. this._draw(subMesh, fillMode);
  11001. }
  11002. if (batch.visibleInstances[subMesh._id]) {
  11003. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11004. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11005. // World
  11006. var world = instance.getWorldMatrix();
  11007. if (onBeforeDraw) {
  11008. onBeforeDraw(true, world);
  11009. }
  11010. // Draw
  11011. this._draw(subMesh, fillMode);
  11012. }
  11013. }
  11014. }
  11015. };
  11016. Mesh.prototype.render = function (subMesh) {
  11017. var scene = this.getScene();
  11018. // Managing instances
  11019. var batch = this._getInstancesRenderList(subMesh._id);
  11020. if (batch.mustReturn) {
  11021. return;
  11022. }
  11023. // Checking geometry state
  11024. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11025. return;
  11026. }
  11027. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11028. this._onBeforeRenderCallbacks[callbackIndex](this);
  11029. }
  11030. var engine = scene.getEngine();
  11031. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11032. // Material
  11033. var effectiveMaterial = subMesh.getMaterial();
  11034. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11035. return;
  11036. }
  11037. // Outline - step 1
  11038. var savedDepthWrite = engine.getDepthWrite();
  11039. if (this.renderOutline) {
  11040. engine.setDepthWrite(false);
  11041. scene.getOutlineRenderer().render(subMesh, batch);
  11042. engine.setDepthWrite(savedDepthWrite);
  11043. }
  11044. effectiveMaterial._preBind();
  11045. var effect = effectiveMaterial.getEffect();
  11046. // Bind
  11047. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11048. this._bind(subMesh, effect, fillMode);
  11049. var world = this.getWorldMatrix();
  11050. effectiveMaterial.bind(world, this);
  11051. // Draw
  11052. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11053. if (isInstance) {
  11054. effectiveMaterial.bindOnlyWorldMatrix(world);
  11055. }
  11056. });
  11057. // Unbind
  11058. effectiveMaterial.unbind();
  11059. // Outline - step 2
  11060. if (this.renderOutline && savedDepthWrite) {
  11061. engine.setDepthWrite(true);
  11062. engine.setColorWrite(false);
  11063. scene.getOutlineRenderer().render(subMesh, batch);
  11064. engine.setColorWrite(true);
  11065. }
  11066. // Overlay
  11067. if (this.renderOverlay) {
  11068. var currentMode = engine.getAlphaMode();
  11069. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11070. scene.getOutlineRenderer().render(subMesh, batch, true);
  11071. engine.setAlphaMode(currentMode);
  11072. }
  11073. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11074. this._onAfterRenderCallbacks[callbackIndex](this);
  11075. }
  11076. };
  11077. Mesh.prototype.getEmittedParticleSystems = function () {
  11078. var results = new Array();
  11079. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11080. var particleSystem = this.getScene().particleSystems[index];
  11081. if (particleSystem.emitter === this) {
  11082. results.push(particleSystem);
  11083. }
  11084. }
  11085. return results;
  11086. };
  11087. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11088. var results = new Array();
  11089. var descendants = this.getDescendants();
  11090. descendants.push(this);
  11091. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11092. var particleSystem = this.getScene().particleSystems[index];
  11093. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11094. results.push(particleSystem);
  11095. }
  11096. }
  11097. return results;
  11098. };
  11099. Mesh.prototype.getChildren = function () {
  11100. var results = [];
  11101. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11102. var mesh = this.getScene().meshes[index];
  11103. if (mesh.parent === this) {
  11104. results.push(mesh);
  11105. }
  11106. }
  11107. return results;
  11108. };
  11109. Mesh.prototype._checkDelayState = function () {
  11110. var _this = this;
  11111. var that = this;
  11112. var scene = this.getScene();
  11113. if (this._geometry) {
  11114. this._geometry.load(scene);
  11115. }
  11116. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11117. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11118. scene._addPendingData(that);
  11119. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11120. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11121. if (data instanceof ArrayBuffer) {
  11122. _this._delayLoadingFunction(data, _this);
  11123. }
  11124. else {
  11125. _this._delayLoadingFunction(JSON.parse(data), _this);
  11126. }
  11127. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11128. scene._removePendingData(_this);
  11129. }, function () {
  11130. }, scene.database, getBinaryData);
  11131. }
  11132. };
  11133. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11134. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11135. return false;
  11136. }
  11137. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11138. return false;
  11139. }
  11140. this._checkDelayState();
  11141. return true;
  11142. };
  11143. Mesh.prototype.setMaterialByID = function (id) {
  11144. var materials = this.getScene().materials;
  11145. for (var index = 0; index < materials.length; index++) {
  11146. if (materials[index].id === id) {
  11147. this.material = materials[index];
  11148. return;
  11149. }
  11150. }
  11151. // Multi
  11152. var multiMaterials = this.getScene().multiMaterials;
  11153. for (index = 0; index < multiMaterials.length; index++) {
  11154. if (multiMaterials[index].id === id) {
  11155. this.material = multiMaterials[index];
  11156. return;
  11157. }
  11158. }
  11159. };
  11160. Mesh.prototype.getAnimatables = function () {
  11161. var results = [];
  11162. if (this.material) {
  11163. results.push(this.material);
  11164. }
  11165. if (this.skeleton) {
  11166. results.push(this.skeleton);
  11167. }
  11168. return results;
  11169. };
  11170. // Geometry
  11171. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11172. // Position
  11173. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11174. return;
  11175. }
  11176. this._resetPointsArrayCache();
  11177. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11178. var temp = [];
  11179. for (var index = 0; index < data.length; index += 3) {
  11180. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11181. }
  11182. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11183. // Normals
  11184. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11185. return;
  11186. }
  11187. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11188. for (index = 0; index < data.length; index += 3) {
  11189. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11190. }
  11191. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11192. };
  11193. // Cache
  11194. Mesh.prototype._resetPointsArrayCache = function () {
  11195. this._positions = null;
  11196. };
  11197. Mesh.prototype._generatePointsArray = function () {
  11198. if (this._positions)
  11199. return true;
  11200. this._positions = [];
  11201. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11202. if (!data) {
  11203. return false;
  11204. }
  11205. for (var index = 0; index < data.length; index += 3) {
  11206. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11207. }
  11208. return true;
  11209. };
  11210. // Clone
  11211. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11212. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11213. };
  11214. // Dispose
  11215. Mesh.prototype.dispose = function (doNotRecurse) {
  11216. if (this._geometry) {
  11217. this._geometry.releaseForMesh(this, true);
  11218. }
  11219. // Instances
  11220. if (this._worldMatricesInstancesBuffer) {
  11221. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11222. this._worldMatricesInstancesBuffer = null;
  11223. }
  11224. while (this.instances.length) {
  11225. this.instances[0].dispose();
  11226. }
  11227. _super.prototype.dispose.call(this, doNotRecurse);
  11228. };
  11229. // Geometric tools
  11230. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11231. var _this = this;
  11232. var scene = this.getScene();
  11233. var onload = function (img) {
  11234. // Getting height map data
  11235. var canvas = document.createElement("canvas");
  11236. var context = canvas.getContext("2d");
  11237. var heightMapWidth = img.width;
  11238. var heightMapHeight = img.height;
  11239. canvas.width = heightMapWidth;
  11240. canvas.height = heightMapHeight;
  11241. context.drawImage(img, 0, 0);
  11242. // Create VertexData from map data
  11243. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11244. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11245. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11246. //execute success callback, if set
  11247. if (onSuccess) {
  11248. onSuccess(_this);
  11249. }
  11250. };
  11251. BABYLON.Tools.LoadImage(url, onload, function () {
  11252. }, scene.database);
  11253. };
  11254. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11255. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11256. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11257. return;
  11258. }
  11259. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11260. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11261. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11262. var position = BABYLON.Vector3.Zero();
  11263. var normal = BABYLON.Vector3.Zero();
  11264. var uv = BABYLON.Vector2.Zero();
  11265. for (var index = 0; index < positions.length; index += 3) {
  11266. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11267. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11268. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11269. // Compute height
  11270. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11271. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11272. var pos = (u + v * heightMapWidth) * 4;
  11273. var r = buffer[pos] / 255.0;
  11274. var g = buffer[pos + 1] / 255.0;
  11275. var b = buffer[pos + 2] / 255.0;
  11276. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11277. normal.normalize();
  11278. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11279. position = position.add(normal);
  11280. position.toArray(positions, index);
  11281. }
  11282. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11283. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11284. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11285. };
  11286. Mesh.prototype.convertToFlatShadedMesh = function () {
  11287. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11288. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11289. var kinds = this.getVerticesDataKinds();
  11290. var vbs = [];
  11291. var data = [];
  11292. var newdata = [];
  11293. var updatableNormals = false;
  11294. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11295. var kind = kinds[kindIndex];
  11296. var vertexBuffer = this.getVertexBuffer(kind);
  11297. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11298. updatableNormals = vertexBuffer.isUpdatable();
  11299. kinds.splice(kindIndex, 1);
  11300. kindIndex--;
  11301. continue;
  11302. }
  11303. vbs[kind] = vertexBuffer;
  11304. data[kind] = vbs[kind].getData();
  11305. newdata[kind] = [];
  11306. }
  11307. // Save previous submeshes
  11308. var previousSubmeshes = this.subMeshes.slice(0);
  11309. var indices = this.getIndices();
  11310. var totalIndices = this.getTotalIndices();
  11311. for (var index = 0; index < totalIndices; index++) {
  11312. var vertexIndex = indices[index];
  11313. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11314. kind = kinds[kindIndex];
  11315. var stride = vbs[kind].getStrideSize();
  11316. for (var offset = 0; offset < stride; offset++) {
  11317. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11318. }
  11319. }
  11320. }
  11321. // Updating faces & normal
  11322. var normals = [];
  11323. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11324. for (index = 0; index < totalIndices; index += 3) {
  11325. indices[index] = index;
  11326. indices[index + 1] = index + 1;
  11327. indices[index + 2] = index + 2;
  11328. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11329. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11330. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11331. var p1p2 = p1.subtract(p2);
  11332. var p3p2 = p3.subtract(p2);
  11333. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11334. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11335. normals.push(normal.x);
  11336. normals.push(normal.y);
  11337. normals.push(normal.z);
  11338. }
  11339. }
  11340. this.setIndices(indices);
  11341. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11342. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11343. kind = kinds[kindIndex];
  11344. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11345. }
  11346. // Updating submeshes
  11347. this.releaseSubMeshes();
  11348. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11349. var previousOne = previousSubmeshes[submeshIndex];
  11350. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11351. }
  11352. this.synchronizeInstances();
  11353. };
  11354. // Instances
  11355. Mesh.prototype.createInstance = function (name) {
  11356. return new BABYLON.InstancedMesh(name, this);
  11357. };
  11358. Mesh.prototype.synchronizeInstances = function () {
  11359. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11360. var instance = this.instances[instanceIndex];
  11361. instance._syncSubMeshes();
  11362. }
  11363. };
  11364. /**
  11365. * Simplify the mesh according to the given array of settings.
  11366. * Function will return immediately and will simplify async.
  11367. * @param settings a collection of simplification settings.
  11368. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11369. * @param type the type of simplification to run.
  11370. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11371. */
  11372. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11373. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11374. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11375. this.getScene().simplificationQueue.addTask({
  11376. settings: settings,
  11377. parallelProcessing: parallelProcessing,
  11378. mesh: this,
  11379. simplificationType: simplificationType,
  11380. successCallback: successCallback
  11381. });
  11382. };
  11383. /**
  11384. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11385. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11386. * This should be used together with the simplification to avoid disappearing triangles.
  11387. * @param successCallback an optional success callback to be called after the optimization finished.
  11388. */
  11389. Mesh.prototype.optimizeIndices = function (successCallback) {
  11390. var _this = this;
  11391. var indices = this.getIndices();
  11392. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11393. var vectorPositions = [];
  11394. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11395. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11396. }
  11397. var dupes = [];
  11398. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11399. var realPos = vectorPositions.length - 1 - iteration;
  11400. var testedPosition = vectorPositions[realPos];
  11401. for (var j = 0; j < realPos; ++j) {
  11402. var againstPosition = vectorPositions[j];
  11403. if (testedPosition.equals(againstPosition)) {
  11404. dupes[realPos] = j;
  11405. break;
  11406. }
  11407. }
  11408. }, function () {
  11409. for (var i = 0; i < indices.length; ++i) {
  11410. indices[i] = dupes[indices[i]] || indices[i];
  11411. }
  11412. //indices are now reordered
  11413. var originalSubMeshes = _this.subMeshes.slice(0);
  11414. _this.setIndices(indices);
  11415. _this.subMeshes = originalSubMeshes;
  11416. if (successCallback) {
  11417. successCallback(_this);
  11418. }
  11419. });
  11420. };
  11421. // Statics
  11422. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11423. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11424. var ribbon = new Mesh(name, scene);
  11425. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11426. vertexData.applyToMesh(ribbon, updatable);
  11427. return ribbon;
  11428. };
  11429. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11430. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11431. var box = new Mesh(name, scene);
  11432. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11433. vertexData.applyToMesh(box, updatable);
  11434. return box;
  11435. };
  11436. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11437. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11438. var sphere = new Mesh(name, scene);
  11439. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11440. vertexData.applyToMesh(sphere, updatable);
  11441. return sphere;
  11442. };
  11443. // Cylinder and cone (Code inspired by SharpDX.org)
  11444. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11445. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11446. // subdivisions is a new parameter, we need to support old signature
  11447. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11448. if (scene !== undefined) {
  11449. updatable = scene;
  11450. }
  11451. scene = subdivisions;
  11452. subdivisions = 1;
  11453. }
  11454. var cylinder = new Mesh(name, scene);
  11455. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11456. vertexData.applyToMesh(cylinder, updatable);
  11457. return cylinder;
  11458. };
  11459. // Torus (Code from SharpDX.org)
  11460. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11461. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11462. var torus = new Mesh(name, scene);
  11463. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11464. vertexData.applyToMesh(torus, updatable);
  11465. return torus;
  11466. };
  11467. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11468. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11469. var torusKnot = new Mesh(name, scene);
  11470. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11471. vertexData.applyToMesh(torusKnot, updatable);
  11472. return torusKnot;
  11473. };
  11474. // Lines
  11475. Mesh.CreateLines = function (name, points, scene, updatable) {
  11476. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11477. var vertexData = BABYLON.VertexData.CreateLines(points);
  11478. vertexData.applyToMesh(lines, updatable);
  11479. return lines;
  11480. };
  11481. // Extrusion
  11482. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11483. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11484. scale = scale || 1;
  11485. rotation = rotation || 0;
  11486. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11487. return extruded;
  11488. };
  11489. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11490. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11491. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11492. return extrudedCustom;
  11493. };
  11494. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotationFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11495. var path3D = new BABYLON.Path3D(curve);
  11496. var shapePaths = [];
  11497. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11498. return extrudedGeneric;
  11499. };
  11500. // Plane & ground
  11501. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11502. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11503. var plane = new Mesh(name, scene);
  11504. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11505. vertexData.applyToMesh(plane, updatable);
  11506. return plane;
  11507. };
  11508. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11509. var ground = new BABYLON.GroundMesh(name, scene);
  11510. ground._setReady(false);
  11511. ground._subdivisions = subdivisions;
  11512. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11513. vertexData.applyToMesh(ground, updatable);
  11514. ground._setReady(true);
  11515. return ground;
  11516. };
  11517. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11518. var tiledGround = new Mesh(name, scene);
  11519. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11520. vertexData.applyToMesh(tiledGround, updatable);
  11521. return tiledGround;
  11522. };
  11523. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11524. var ground = new BABYLON.GroundMesh(name, scene);
  11525. ground._subdivisions = subdivisions;
  11526. ground._setReady(false);
  11527. var onload = function (img) {
  11528. // Getting height map data
  11529. var canvas = document.createElement("canvas");
  11530. var context = canvas.getContext("2d");
  11531. var heightMapWidth = img.width;
  11532. var heightMapHeight = img.height;
  11533. canvas.width = heightMapWidth;
  11534. canvas.height = heightMapHeight;
  11535. context.drawImage(img, 0, 0);
  11536. // Create VertexData from map data
  11537. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11538. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11539. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11540. vertexData.applyToMesh(ground, updatable);
  11541. ground._setReady(true);
  11542. //execute ready callback, if set
  11543. if (onReady) {
  11544. onReady(ground);
  11545. }
  11546. };
  11547. BABYLON.Tools.LoadImage(url, onload, function () {
  11548. }, scene.database);
  11549. return ground;
  11550. };
  11551. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11552. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11553. var path3D = new BABYLON.Path3D(path);
  11554. var tangents = path3D.getTangents();
  11555. var normals = path3D.getNormals();
  11556. var distances = path3D.getDistances();
  11557. var pi2 = Math.PI * 2;
  11558. var step = pi2 / tesselation;
  11559. var returnRadius = function (i, distance) { return radius; };
  11560. var radiusFunctionFinal = radiusFunction || returnRadius;
  11561. var circlePaths = new Array();
  11562. var circlePath;
  11563. var rad;
  11564. var normal;
  11565. var rotated;
  11566. var rotationMatrix;
  11567. for (var i = 0; i < path.length; i++) {
  11568. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11569. circlePath = Array(); // current circle array
  11570. normal = normals[i]; // current normal
  11571. for (var ang = 0; ang < pi2; ang += step) {
  11572. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11573. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11574. circlePath.push(rotated);
  11575. }
  11576. circlePaths.push(circlePath);
  11577. }
  11578. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11579. return tube;
  11580. };
  11581. // Tools
  11582. Mesh.MinMax = function (meshes) {
  11583. var minVector = null;
  11584. var maxVector = null;
  11585. for (var i in meshes) {
  11586. var mesh = meshes[i];
  11587. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11588. if (!minVector) {
  11589. minVector = boundingBox.minimumWorld;
  11590. maxVector = boundingBox.maximumWorld;
  11591. continue;
  11592. }
  11593. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11594. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11595. }
  11596. return {
  11597. min: minVector,
  11598. max: maxVector
  11599. };
  11600. };
  11601. Mesh.Center = function (meshesOrMinMaxVector) {
  11602. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11603. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11604. };
  11605. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11606. if (disposeSource === void 0) { disposeSource = true; }
  11607. var source = meshes[0];
  11608. var material = source.material;
  11609. var scene = source.getScene();
  11610. if (!allow32BitsIndices) {
  11611. var totalVertices = 0;
  11612. for (var index = 0; index < meshes.length; index++) {
  11613. totalVertices += meshes[index].getTotalVertices();
  11614. if (totalVertices > 65536) {
  11615. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11616. return null;
  11617. }
  11618. }
  11619. }
  11620. // Merge
  11621. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11622. vertexData.transform(source.getWorldMatrix());
  11623. for (index = 1; index < meshes.length; index++) {
  11624. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11625. otherVertexData.transform(meshes[index].getWorldMatrix());
  11626. vertexData.merge(otherVertexData);
  11627. }
  11628. var newMesh = new Mesh(source.name + "_merged", scene);
  11629. vertexData.applyToMesh(newMesh);
  11630. // Setting properties
  11631. newMesh.material = material;
  11632. newMesh.checkCollisions = source.checkCollisions;
  11633. // Cleaning
  11634. if (disposeSource) {
  11635. for (index = 0; index < meshes.length; index++) {
  11636. meshes[index].dispose();
  11637. }
  11638. }
  11639. return newMesh;
  11640. };
  11641. // Consts
  11642. Mesh._FRONTSIDE = 0;
  11643. Mesh._BACKSIDE = 1;
  11644. Mesh._DOUBLESIDE = 2;
  11645. Mesh._DEFAULTSIDE = 0;
  11646. return Mesh;
  11647. })(BABYLON.AbstractMesh);
  11648. BABYLON.Mesh = Mesh;
  11649. })(BABYLON || (BABYLON = {}));
  11650. //# sourceMappingURL=babylon.mesh.js.map
  11651. var BABYLON;
  11652. (function (BABYLON) {
  11653. var GroundMesh = (function (_super) {
  11654. __extends(GroundMesh, _super);
  11655. function GroundMesh(name, scene) {
  11656. _super.call(this, name, scene);
  11657. this.generateOctree = false;
  11658. this._worldInverse = new BABYLON.Matrix();
  11659. }
  11660. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11661. get: function () {
  11662. return this._subdivisions;
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. GroundMesh.prototype.optimize = function (chunksCount) {
  11668. this.subdivide(this._subdivisions);
  11669. this.createOrUpdateSubmeshesOctree(32);
  11670. };
  11671. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11672. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11673. this.getWorldMatrix().invertToRef(this._worldInverse);
  11674. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11675. var pickInfo = this.intersects(ray);
  11676. if (pickInfo.hit) {
  11677. return pickInfo.pickedPoint.y;
  11678. }
  11679. return 0;
  11680. };
  11681. return GroundMesh;
  11682. })(BABYLON.Mesh);
  11683. BABYLON.GroundMesh = GroundMesh;
  11684. })(BABYLON || (BABYLON = {}));
  11685. //# sourceMappingURL=babylon.groundMesh.js.map
  11686. var BABYLON;
  11687. (function (BABYLON) {
  11688. /**
  11689. * Creates an instance based on a source mesh.
  11690. */
  11691. var InstancedMesh = (function (_super) {
  11692. __extends(InstancedMesh, _super);
  11693. function InstancedMesh(name, source) {
  11694. _super.call(this, name, source.getScene());
  11695. source.instances.push(this);
  11696. this._sourceMesh = source;
  11697. this.position.copyFrom(source.position);
  11698. this.rotation.copyFrom(source.rotation);
  11699. this.scaling.copyFrom(source.scaling);
  11700. if (source.rotationQuaternion) {
  11701. this.rotationQuaternion = source.rotationQuaternion.clone();
  11702. }
  11703. this.infiniteDistance = source.infiniteDistance;
  11704. this.setPivotMatrix(source.getPivotMatrix());
  11705. this.refreshBoundingInfo();
  11706. this._syncSubMeshes();
  11707. }
  11708. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11709. // Methods
  11710. get: function () {
  11711. return this._sourceMesh.receiveShadows;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(InstancedMesh.prototype, "material", {
  11717. get: function () {
  11718. return this._sourceMesh.material;
  11719. },
  11720. enumerable: true,
  11721. configurable: true
  11722. });
  11723. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11724. get: function () {
  11725. return this._sourceMesh.visibility;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11731. get: function () {
  11732. return this._sourceMesh.skeleton;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. InstancedMesh.prototype.getTotalVertices = function () {
  11738. return this._sourceMesh.getTotalVertices();
  11739. };
  11740. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11741. get: function () {
  11742. return this._sourceMesh;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. InstancedMesh.prototype.getVerticesData = function (kind) {
  11748. return this._sourceMesh.getVerticesData(kind);
  11749. };
  11750. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11751. return this._sourceMesh.isVerticesDataPresent(kind);
  11752. };
  11753. InstancedMesh.prototype.getIndices = function () {
  11754. return this._sourceMesh.getIndices();
  11755. };
  11756. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11757. get: function () {
  11758. return this._sourceMesh._positions;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11764. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11765. if (data) {
  11766. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11767. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11768. }
  11769. this._updateBoundingInfo();
  11770. };
  11771. InstancedMesh.prototype._preActivate = function () {
  11772. if (this._currentLOD) {
  11773. this._currentLOD._preActivate();
  11774. }
  11775. };
  11776. InstancedMesh.prototype._activate = function (renderId) {
  11777. if (this._currentLOD) {
  11778. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11779. }
  11780. };
  11781. InstancedMesh.prototype.getLOD = function (camera) {
  11782. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11783. if (this._currentLOD === this.sourceMesh) {
  11784. return this;
  11785. }
  11786. return this._currentLOD;
  11787. };
  11788. InstancedMesh.prototype._syncSubMeshes = function () {
  11789. this.releaseSubMeshes();
  11790. if (this._sourceMesh.subMeshes) {
  11791. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11792. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11793. }
  11794. }
  11795. };
  11796. InstancedMesh.prototype._generatePointsArray = function () {
  11797. return this._sourceMesh._generatePointsArray();
  11798. };
  11799. // Clone
  11800. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11801. var result = this._sourceMesh.createInstance(name);
  11802. // Deep copy
  11803. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11804. // Bounding info
  11805. this.refreshBoundingInfo();
  11806. // Parent
  11807. if (newParent) {
  11808. result.parent = newParent;
  11809. }
  11810. if (!doNotCloneChildren) {
  11811. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11812. var mesh = this.getScene().meshes[index];
  11813. if (mesh.parent === this) {
  11814. mesh.clone(mesh.name, result);
  11815. }
  11816. }
  11817. }
  11818. result.computeWorldMatrix(true);
  11819. return result;
  11820. };
  11821. // Dispoe
  11822. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11823. // Remove from mesh
  11824. var index = this._sourceMesh.instances.indexOf(this);
  11825. this._sourceMesh.instances.splice(index, 1);
  11826. _super.prototype.dispose.call(this, doNotRecurse);
  11827. };
  11828. return InstancedMesh;
  11829. })(BABYLON.AbstractMesh);
  11830. BABYLON.InstancedMesh = InstancedMesh;
  11831. })(BABYLON || (BABYLON = {}));
  11832. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11833. (function (BABYLON) {
  11834. var SubMesh = (function () {
  11835. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11836. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11837. this.materialIndex = materialIndex;
  11838. this.verticesStart = verticesStart;
  11839. this.verticesCount = verticesCount;
  11840. this.indexStart = indexStart;
  11841. this.indexCount = indexCount;
  11842. this._renderId = 0;
  11843. this._mesh = mesh;
  11844. this._renderingMesh = renderingMesh || mesh;
  11845. mesh.subMeshes.push(this);
  11846. this._id = mesh.subMeshes.length - 1;
  11847. if (createBoundingBox) {
  11848. this.refreshBoundingInfo();
  11849. }
  11850. }
  11851. SubMesh.prototype.getBoundingInfo = function () {
  11852. return this._boundingInfo;
  11853. };
  11854. SubMesh.prototype.getMesh = function () {
  11855. return this._mesh;
  11856. };
  11857. SubMesh.prototype.getRenderingMesh = function () {
  11858. return this._renderingMesh;
  11859. };
  11860. SubMesh.prototype.getMaterial = function () {
  11861. var rootMaterial = this._renderingMesh.material;
  11862. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11863. var multiMaterial = rootMaterial;
  11864. return multiMaterial.getSubMaterial(this.materialIndex);
  11865. }
  11866. if (!rootMaterial) {
  11867. return this._mesh.getScene().defaultMaterial;
  11868. }
  11869. return rootMaterial;
  11870. };
  11871. // Methods
  11872. SubMesh.prototype.refreshBoundingInfo = function () {
  11873. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11874. if (!data) {
  11875. this._boundingInfo = this._mesh._boundingInfo;
  11876. return;
  11877. }
  11878. var indices = this._renderingMesh.getIndices();
  11879. var extend;
  11880. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11881. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11882. }
  11883. else {
  11884. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11885. }
  11886. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11887. };
  11888. SubMesh.prototype._checkCollision = function (collider) {
  11889. return this._boundingInfo._checkCollision(collider);
  11890. };
  11891. SubMesh.prototype.updateBoundingInfo = function (world) {
  11892. if (!this._boundingInfo) {
  11893. this.refreshBoundingInfo();
  11894. }
  11895. this._boundingInfo._update(world);
  11896. };
  11897. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11898. return this._boundingInfo.isInFrustum(frustumPlanes);
  11899. };
  11900. SubMesh.prototype.render = function () {
  11901. this._renderingMesh.render(this);
  11902. };
  11903. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11904. if (!this._linesIndexBuffer) {
  11905. var linesIndices = [];
  11906. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11907. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11908. }
  11909. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11910. this.linesIndexCount = linesIndices.length;
  11911. }
  11912. return this._linesIndexBuffer;
  11913. };
  11914. SubMesh.prototype.canIntersects = function (ray) {
  11915. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11916. };
  11917. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11918. var intersectInfo = null;
  11919. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11920. var p0 = positions[indices[index]];
  11921. var p1 = positions[indices[index + 1]];
  11922. var p2 = positions[indices[index + 2]];
  11923. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11924. if (currentIntersectInfo) {
  11925. if (currentIntersectInfo.distance < 0) {
  11926. continue;
  11927. }
  11928. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11929. intersectInfo = currentIntersectInfo;
  11930. intersectInfo.faceId = index / 3;
  11931. if (fastCheck) {
  11932. break;
  11933. }
  11934. }
  11935. }
  11936. }
  11937. return intersectInfo;
  11938. };
  11939. // Clone
  11940. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11941. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11942. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11943. return result;
  11944. };
  11945. // Dispose
  11946. SubMesh.prototype.dispose = function () {
  11947. if (this._linesIndexBuffer) {
  11948. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11949. this._linesIndexBuffer = null;
  11950. }
  11951. // Remove from mesh
  11952. var index = this._mesh.subMeshes.indexOf(this);
  11953. this._mesh.subMeshes.splice(index, 1);
  11954. };
  11955. // Statics
  11956. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11957. var minVertexIndex = Number.MAX_VALUE;
  11958. var maxVertexIndex = -Number.MAX_VALUE;
  11959. renderingMesh = renderingMesh || mesh;
  11960. var indices = renderingMesh.getIndices();
  11961. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11962. var vertexIndex = indices[index];
  11963. if (vertexIndex < minVertexIndex)
  11964. minVertexIndex = vertexIndex;
  11965. if (vertexIndex > maxVertexIndex)
  11966. maxVertexIndex = vertexIndex;
  11967. }
  11968. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11969. };
  11970. return SubMesh;
  11971. })();
  11972. BABYLON.SubMesh = SubMesh;
  11973. })(BABYLON || (BABYLON = {}));
  11974. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11975. (function (BABYLON) {
  11976. var BaseTexture = (function () {
  11977. function BaseTexture(scene) {
  11978. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11979. this.hasAlpha = false;
  11980. this.getAlphaFromRGB = false;
  11981. this.level = 1;
  11982. this.isCube = false;
  11983. this.isRenderTarget = false;
  11984. this.animations = new Array();
  11985. this.coordinatesIndex = 0;
  11986. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11987. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11988. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11989. this.anisotropicFilteringLevel = 4;
  11990. this._scene = scene;
  11991. this._scene.textures.push(this);
  11992. }
  11993. BaseTexture.prototype.getScene = function () {
  11994. return this._scene;
  11995. };
  11996. BaseTexture.prototype.getTextureMatrix = function () {
  11997. return null;
  11998. };
  11999. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12000. return null;
  12001. };
  12002. BaseTexture.prototype.getInternalTexture = function () {
  12003. return this._texture;
  12004. };
  12005. BaseTexture.prototype.isReady = function () {
  12006. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12007. return true;
  12008. }
  12009. if (this._texture) {
  12010. return this._texture.isReady;
  12011. }
  12012. return false;
  12013. };
  12014. BaseTexture.prototype.getSize = function () {
  12015. if (this._texture._width) {
  12016. return { width: this._texture._width, height: this._texture._height };
  12017. }
  12018. if (this._texture._size) {
  12019. return { width: this._texture._size, height: this._texture._size };
  12020. }
  12021. return { width: 0, height: 0 };
  12022. };
  12023. BaseTexture.prototype.getBaseSize = function () {
  12024. if (!this.isReady())
  12025. return { width: 0, height: 0 };
  12026. if (this._texture._size) {
  12027. return { width: this._texture._size, height: this._texture._size };
  12028. }
  12029. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12030. };
  12031. BaseTexture.prototype.scale = function (ratio) {
  12032. };
  12033. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12034. get: function () {
  12035. return false;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12041. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12042. for (var index = 0; index < texturesCache.length; index++) {
  12043. var texturesCacheEntry = texturesCache[index];
  12044. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12045. texturesCache.splice(index, 1);
  12046. return;
  12047. }
  12048. }
  12049. };
  12050. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12051. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12052. for (var index = 0; index < texturesCache.length; index++) {
  12053. var texturesCacheEntry = texturesCache[index];
  12054. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12055. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12056. texturesCacheEntry.references++;
  12057. return texturesCacheEntry;
  12058. }
  12059. }
  12060. }
  12061. return null;
  12062. };
  12063. BaseTexture.prototype.delayLoad = function () {
  12064. };
  12065. BaseTexture.prototype.releaseInternalTexture = function () {
  12066. if (!this._texture) {
  12067. return;
  12068. }
  12069. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12070. this._texture.references--;
  12071. // Final reference ?
  12072. if (this._texture.references === 0) {
  12073. var index = texturesCache.indexOf(this._texture);
  12074. texturesCache.splice(index, 1);
  12075. this._scene.getEngine()._releaseTexture(this._texture);
  12076. delete this._texture;
  12077. }
  12078. };
  12079. BaseTexture.prototype.clone = function () {
  12080. return null;
  12081. };
  12082. BaseTexture.prototype.dispose = function () {
  12083. // Remove from scene
  12084. var index = this._scene.textures.indexOf(this);
  12085. if (index >= 0) {
  12086. this._scene.textures.splice(index, 1);
  12087. }
  12088. if (this._texture === undefined) {
  12089. return;
  12090. }
  12091. this.releaseInternalTexture();
  12092. // Callback
  12093. if (this.onDispose) {
  12094. this.onDispose();
  12095. }
  12096. };
  12097. return BaseTexture;
  12098. })();
  12099. BABYLON.BaseTexture = BaseTexture;
  12100. })(BABYLON || (BABYLON = {}));
  12101. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12102. (function (BABYLON) {
  12103. var RenderingGroup = (function () {
  12104. function RenderingGroup(index, scene) {
  12105. this.index = index;
  12106. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12107. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12108. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12109. this._scene = scene;
  12110. }
  12111. RenderingGroup.prototype.render = function (customRenderFunction) {
  12112. if (customRenderFunction) {
  12113. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12114. return true;
  12115. }
  12116. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12117. return false;
  12118. }
  12119. var engine = this._scene.getEngine();
  12120. // Opaque
  12121. var subIndex;
  12122. var submesh;
  12123. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12124. submesh = this._opaqueSubMeshes.data[subIndex];
  12125. submesh.render();
  12126. }
  12127. // Alpha test
  12128. engine.setAlphaTesting(true);
  12129. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12130. submesh = this._alphaTestSubMeshes.data[subIndex];
  12131. submesh.render();
  12132. }
  12133. engine.setAlphaTesting(false);
  12134. // Transparent
  12135. if (this._transparentSubMeshes.length) {
  12136. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12137. submesh = this._transparentSubMeshes.data[subIndex];
  12138. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12139. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12140. }
  12141. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12142. sortedArray.sort(function (a, b) {
  12143. // Alpha index first
  12144. if (a._alphaIndex > b._alphaIndex) {
  12145. return 1;
  12146. }
  12147. if (a._alphaIndex < b._alphaIndex) {
  12148. return -1;
  12149. }
  12150. // Then distance to camera
  12151. if (a._distanceToCamera < b._distanceToCamera) {
  12152. return 1;
  12153. }
  12154. if (a._distanceToCamera > b._distanceToCamera) {
  12155. return -1;
  12156. }
  12157. return 0;
  12158. });
  12159. // Rendering
  12160. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12161. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12162. submesh = sortedArray[subIndex];
  12163. submesh.render();
  12164. }
  12165. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12166. }
  12167. return true;
  12168. };
  12169. RenderingGroup.prototype.prepare = function () {
  12170. this._opaqueSubMeshes.reset();
  12171. this._transparentSubMeshes.reset();
  12172. this._alphaTestSubMeshes.reset();
  12173. };
  12174. RenderingGroup.prototype.dispatch = function (subMesh) {
  12175. var material = subMesh.getMaterial();
  12176. var mesh = subMesh.getMesh();
  12177. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12178. this._transparentSubMeshes.push(subMesh);
  12179. }
  12180. else if (material.needAlphaTesting()) {
  12181. this._alphaTestSubMeshes.push(subMesh);
  12182. }
  12183. else {
  12184. this._opaqueSubMeshes.push(subMesh); // Opaque
  12185. }
  12186. };
  12187. return RenderingGroup;
  12188. })();
  12189. BABYLON.RenderingGroup = RenderingGroup;
  12190. })(BABYLON || (BABYLON = {}));
  12191. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12192. (function (BABYLON) {
  12193. var RenderingManager = (function () {
  12194. function RenderingManager(scene) {
  12195. this._renderingGroups = new Array();
  12196. this._scene = scene;
  12197. }
  12198. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12199. if (this._scene._activeParticleSystems.length === 0) {
  12200. return;
  12201. }
  12202. // Particles
  12203. var beforeParticlesDate = BABYLON.Tools.Now;
  12204. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12205. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12206. if (particleSystem.renderingGroupId !== index) {
  12207. continue;
  12208. }
  12209. this._clearDepthBuffer();
  12210. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12211. this._scene._activeParticles += particleSystem.render();
  12212. }
  12213. }
  12214. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12215. };
  12216. RenderingManager.prototype._renderSprites = function (index) {
  12217. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12218. return;
  12219. }
  12220. // Sprites
  12221. var beforeSpritessDate = BABYLON.Tools.Now;
  12222. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12223. var spriteManager = this._scene.spriteManagers[id];
  12224. if (spriteManager.renderingGroupId === index) {
  12225. this._clearDepthBuffer();
  12226. spriteManager.render();
  12227. }
  12228. }
  12229. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12230. };
  12231. RenderingManager.prototype._clearDepthBuffer = function () {
  12232. if (this._depthBufferAlreadyCleaned) {
  12233. return;
  12234. }
  12235. this._scene.getEngine().clear(0, false, true);
  12236. this._depthBufferAlreadyCleaned = true;
  12237. };
  12238. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12239. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12240. this._depthBufferAlreadyCleaned = false;
  12241. var renderingGroup = this._renderingGroups[index];
  12242. var needToStepBack = false;
  12243. if (renderingGroup) {
  12244. this._clearDepthBuffer();
  12245. if (!renderingGroup.render(customRenderFunction)) {
  12246. this._renderingGroups.splice(index, 1);
  12247. needToStepBack = true;
  12248. }
  12249. }
  12250. if (renderSprites) {
  12251. this._renderSprites(index);
  12252. }
  12253. if (renderParticles) {
  12254. this._renderParticles(index, activeMeshes);
  12255. }
  12256. if (needToStepBack) {
  12257. index--;
  12258. }
  12259. }
  12260. };
  12261. RenderingManager.prototype.reset = function () {
  12262. for (var index in this._renderingGroups) {
  12263. var renderingGroup = this._renderingGroups[index];
  12264. renderingGroup.prepare();
  12265. }
  12266. };
  12267. RenderingManager.prototype.dispatch = function (subMesh) {
  12268. var mesh = subMesh.getMesh();
  12269. var renderingGroupId = mesh.renderingGroupId || 0;
  12270. if (!this._renderingGroups[renderingGroupId]) {
  12271. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12272. }
  12273. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12274. };
  12275. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12276. return RenderingManager;
  12277. })();
  12278. BABYLON.RenderingManager = RenderingManager;
  12279. })(BABYLON || (BABYLON = {}));
  12280. //# sourceMappingURL=babylon.renderingManager.js.map
  12281. var BABYLON;
  12282. (function (BABYLON) {
  12283. var Texture = (function (_super) {
  12284. __extends(Texture, _super);
  12285. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12286. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12287. if (onLoad === void 0) { onLoad = null; }
  12288. if (onError === void 0) { onError = null; }
  12289. if (buffer === void 0) { buffer = null; }
  12290. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12291. _super.call(this, scene);
  12292. this.uOffset = 0;
  12293. this.vOffset = 0;
  12294. this.uScale = 1.0;
  12295. this.vScale = 1.0;
  12296. this.uAng = 0;
  12297. this.vAng = 0;
  12298. this.wAng = 0;
  12299. this.name = url;
  12300. this.url = url;
  12301. this._noMipmap = noMipmap;
  12302. this._invertY = invertY;
  12303. this._samplingMode = samplingMode;
  12304. this._buffer = buffer;
  12305. this._deleteBuffer = deleteBuffer;
  12306. if (!url) {
  12307. return;
  12308. }
  12309. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12310. if (!this._texture) {
  12311. if (!scene.useDelayedTextureLoading) {
  12312. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12313. if (deleteBuffer) {
  12314. delete this._buffer;
  12315. }
  12316. }
  12317. else {
  12318. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12319. }
  12320. }
  12321. }
  12322. Texture.prototype.delayLoad = function () {
  12323. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12324. return;
  12325. }
  12326. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12327. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12328. if (!this._texture) {
  12329. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12330. if (this._deleteBuffer) {
  12331. delete this._buffer;
  12332. }
  12333. }
  12334. };
  12335. Texture.prototype.updateSamplingMode = function (samplingMode) {
  12336. if (!this._texture) {
  12337. return;
  12338. }
  12339. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  12340. };
  12341. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12342. x -= this.uOffset + 0.5;
  12343. y -= this.vOffset + 0.5;
  12344. z -= 0.5;
  12345. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12346. t.x *= this.uScale;
  12347. t.y *= this.vScale;
  12348. t.x += 0.5;
  12349. t.y += 0.5;
  12350. t.z += 0.5;
  12351. };
  12352. Texture.prototype.getTextureMatrix = function () {
  12353. 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) {
  12354. return this._cachedTextureMatrix;
  12355. }
  12356. this._cachedUOffset = this.uOffset;
  12357. this._cachedVOffset = this.vOffset;
  12358. this._cachedUScale = this.uScale;
  12359. this._cachedVScale = this.vScale;
  12360. this._cachedUAng = this.uAng;
  12361. this._cachedVAng = this.vAng;
  12362. this._cachedWAng = this.wAng;
  12363. if (!this._cachedTextureMatrix) {
  12364. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12365. this._rowGenerationMatrix = new BABYLON.Matrix();
  12366. this._t0 = BABYLON.Vector3.Zero();
  12367. this._t1 = BABYLON.Vector3.Zero();
  12368. this._t2 = BABYLON.Vector3.Zero();
  12369. }
  12370. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12371. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12372. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12373. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12374. this._t1.subtractInPlace(this._t0);
  12375. this._t2.subtractInPlace(this._t0);
  12376. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12377. this._cachedTextureMatrix.m[0] = this._t1.x;
  12378. this._cachedTextureMatrix.m[1] = this._t1.y;
  12379. this._cachedTextureMatrix.m[2] = this._t1.z;
  12380. this._cachedTextureMatrix.m[4] = this._t2.x;
  12381. this._cachedTextureMatrix.m[5] = this._t2.y;
  12382. this._cachedTextureMatrix.m[6] = this._t2.z;
  12383. this._cachedTextureMatrix.m[8] = this._t0.x;
  12384. this._cachedTextureMatrix.m[9] = this._t0.y;
  12385. this._cachedTextureMatrix.m[10] = this._t0.z;
  12386. return this._cachedTextureMatrix;
  12387. };
  12388. Texture.prototype.getReflectionTextureMatrix = function () {
  12389. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12390. return this._cachedTextureMatrix;
  12391. }
  12392. if (!this._cachedTextureMatrix) {
  12393. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12394. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12395. }
  12396. this._cachedCoordinatesMode = this.coordinatesMode;
  12397. switch (this.coordinatesMode) {
  12398. case Texture.SPHERICAL_MODE:
  12399. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12400. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12401. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12402. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12403. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12404. break;
  12405. case Texture.PLANAR_MODE:
  12406. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12407. this._cachedTextureMatrix[0] = this.uScale;
  12408. this._cachedTextureMatrix[5] = this.vScale;
  12409. this._cachedTextureMatrix[12] = this.uOffset;
  12410. this._cachedTextureMatrix[13] = this.vOffset;
  12411. break;
  12412. case Texture.PROJECTION_MODE:
  12413. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12414. this._projectionModeMatrix.m[0] = 0.5;
  12415. this._projectionModeMatrix.m[5] = -0.5;
  12416. this._projectionModeMatrix.m[10] = 0.0;
  12417. this._projectionModeMatrix.m[12] = 0.5;
  12418. this._projectionModeMatrix.m[13] = 0.5;
  12419. this._projectionModeMatrix.m[14] = 1.0;
  12420. this._projectionModeMatrix.m[15] = 1.0;
  12421. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12422. break;
  12423. default:
  12424. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12425. break;
  12426. }
  12427. return this._cachedTextureMatrix;
  12428. };
  12429. Texture.prototype.clone = function () {
  12430. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12431. // Base texture
  12432. newTexture.hasAlpha = this.hasAlpha;
  12433. newTexture.level = this.level;
  12434. newTexture.wrapU = this.wrapU;
  12435. newTexture.wrapV = this.wrapV;
  12436. newTexture.coordinatesIndex = this.coordinatesIndex;
  12437. newTexture.coordinatesMode = this.coordinatesMode;
  12438. // Texture
  12439. newTexture.uOffset = this.uOffset;
  12440. newTexture.vOffset = this.vOffset;
  12441. newTexture.uScale = this.uScale;
  12442. newTexture.vScale = this.vScale;
  12443. newTexture.uAng = this.uAng;
  12444. newTexture.vAng = this.vAng;
  12445. newTexture.wAng = this.wAng;
  12446. return newTexture;
  12447. };
  12448. // Statics
  12449. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12450. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12451. if (onLoad === void 0) { onLoad = null; }
  12452. if (onError === void 0) { onError = null; }
  12453. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12454. };
  12455. // Constants
  12456. Texture.NEAREST_SAMPLINGMODE = 1;
  12457. Texture.BILINEAR_SAMPLINGMODE = 2;
  12458. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12459. Texture.EXPLICIT_MODE = 0;
  12460. Texture.SPHERICAL_MODE = 1;
  12461. Texture.PLANAR_MODE = 2;
  12462. Texture.CUBIC_MODE = 3;
  12463. Texture.PROJECTION_MODE = 4;
  12464. Texture.SKYBOX_MODE = 5;
  12465. Texture.CLAMP_ADDRESSMODE = 0;
  12466. Texture.WRAP_ADDRESSMODE = 1;
  12467. Texture.MIRROR_ADDRESSMODE = 2;
  12468. return Texture;
  12469. })(BABYLON.BaseTexture);
  12470. BABYLON.Texture = Texture;
  12471. })(BABYLON || (BABYLON = {}));
  12472. //# sourceMappingURL=babylon.texture.js.map
  12473. var BABYLON;
  12474. (function (BABYLON) {
  12475. var CubeTexture = (function (_super) {
  12476. __extends(CubeTexture, _super);
  12477. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12478. _super.call(this, scene);
  12479. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12480. this.name = rootUrl;
  12481. this.url = rootUrl;
  12482. this._noMipmap = noMipmap;
  12483. this.hasAlpha = false;
  12484. this._texture = this._getFromCache(rootUrl, noMipmap);
  12485. if (!extensions) {
  12486. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12487. }
  12488. this._extensions = extensions;
  12489. if (!this._texture) {
  12490. if (!scene.useDelayedTextureLoading) {
  12491. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12492. }
  12493. else {
  12494. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12495. }
  12496. }
  12497. this.isCube = true;
  12498. this._textureMatrix = BABYLON.Matrix.Identity();
  12499. }
  12500. CubeTexture.prototype.clone = function () {
  12501. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12502. // Base texture
  12503. newTexture.level = this.level;
  12504. newTexture.wrapU = this.wrapU;
  12505. newTexture.wrapV = this.wrapV;
  12506. newTexture.coordinatesIndex = this.coordinatesIndex;
  12507. newTexture.coordinatesMode = this.coordinatesMode;
  12508. return newTexture;
  12509. };
  12510. // Methods
  12511. CubeTexture.prototype.delayLoad = function () {
  12512. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12513. return;
  12514. }
  12515. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12516. this._texture = this._getFromCache(this.url, this._noMipmap);
  12517. if (!this._texture) {
  12518. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12519. }
  12520. };
  12521. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12522. return this._textureMatrix;
  12523. };
  12524. return CubeTexture;
  12525. })(BABYLON.BaseTexture);
  12526. BABYLON.CubeTexture = CubeTexture;
  12527. })(BABYLON || (BABYLON = {}));
  12528. //# sourceMappingURL=babylon.cubeTexture.js.map
  12529. var BABYLON;
  12530. (function (BABYLON) {
  12531. var RenderTargetTexture = (function (_super) {
  12532. __extends(RenderTargetTexture, _super);
  12533. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12534. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12535. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12536. _super.call(this, null, scene, !generateMipMaps);
  12537. this.renderList = new Array();
  12538. this.renderParticles = true;
  12539. this.renderSprites = false;
  12540. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12541. this._currentRefreshId = -1;
  12542. this._refreshRate = 1;
  12543. this.name = name;
  12544. this.isRenderTarget = true;
  12545. this._size = size;
  12546. this._generateMipMaps = generateMipMaps;
  12547. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12548. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12549. // Rendering groups
  12550. this._renderingManager = new BABYLON.RenderingManager(scene);
  12551. }
  12552. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12553. this._currentRefreshId = -1;
  12554. };
  12555. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12556. get: function () {
  12557. return this._refreshRate;
  12558. },
  12559. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12560. set: function (value) {
  12561. this._refreshRate = value;
  12562. this.resetRefreshCounter();
  12563. },
  12564. enumerable: true,
  12565. configurable: true
  12566. });
  12567. RenderTargetTexture.prototype._shouldRender = function () {
  12568. if (this._currentRefreshId === -1) {
  12569. this._currentRefreshId = 1;
  12570. return true;
  12571. }
  12572. if (this.refreshRate === this._currentRefreshId) {
  12573. this._currentRefreshId = 1;
  12574. return true;
  12575. }
  12576. this._currentRefreshId++;
  12577. return false;
  12578. };
  12579. RenderTargetTexture.prototype.isReady = function () {
  12580. if (!this.getScene().renderTargetsEnabled) {
  12581. return false;
  12582. }
  12583. return _super.prototype.isReady.call(this);
  12584. };
  12585. RenderTargetTexture.prototype.getRenderSize = function () {
  12586. return this._size;
  12587. };
  12588. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12589. get: function () {
  12590. return true;
  12591. },
  12592. enumerable: true,
  12593. configurable: true
  12594. });
  12595. RenderTargetTexture.prototype.scale = function (ratio) {
  12596. var newSize = this._size * ratio;
  12597. this.resize(newSize, this._generateMipMaps);
  12598. };
  12599. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12600. this.releaseInternalTexture();
  12601. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12602. };
  12603. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12604. var scene = this.getScene();
  12605. var engine = scene.getEngine();
  12606. if (this._waitingRenderList) {
  12607. this.renderList = [];
  12608. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12609. var id = this._waitingRenderList[index];
  12610. this.renderList.push(scene.getMeshByID(id));
  12611. }
  12612. delete this._waitingRenderList;
  12613. }
  12614. if (this.renderList && this.renderList.length === 0) {
  12615. return;
  12616. }
  12617. // Bind
  12618. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12619. engine.bindFramebuffer(this._texture);
  12620. }
  12621. this._renderingManager.reset();
  12622. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12623. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12624. var mesh = currentRenderList[meshIndex];
  12625. if (mesh) {
  12626. if (!mesh.isReady()) {
  12627. // Reset _currentRefreshId
  12628. this.resetRefreshCounter();
  12629. continue;
  12630. }
  12631. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12632. mesh._activate(scene.getRenderId());
  12633. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12634. var subMesh = mesh.subMeshes[subIndex];
  12635. scene._activeVertices += subMesh.indexCount;
  12636. this._renderingManager.dispatch(subMesh);
  12637. }
  12638. }
  12639. }
  12640. }
  12641. if (this.onBeforeRender) {
  12642. this.onBeforeRender();
  12643. }
  12644. // Clear
  12645. if (this.onClear) {
  12646. this.onClear(engine);
  12647. }
  12648. else {
  12649. engine.clear(scene.clearColor, true, true);
  12650. }
  12651. if (!this._doNotChangeAspectRatio) {
  12652. scene.updateTransformMatrix(true);
  12653. }
  12654. // Render
  12655. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12656. if (useCameraPostProcess) {
  12657. scene.postProcessManager._finalizeFrame(false, this._texture);
  12658. }
  12659. if (!this._doNotChangeAspectRatio) {
  12660. scene.updateTransformMatrix(true);
  12661. }
  12662. if (this.onAfterRender) {
  12663. this.onAfterRender();
  12664. }
  12665. // Dump ?
  12666. if (dumpForDebug) {
  12667. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12668. }
  12669. // Unbind
  12670. engine.unBindFramebuffer(this._texture);
  12671. if (this.onAfterUnbind) {
  12672. this.onAfterUnbind();
  12673. }
  12674. };
  12675. RenderTargetTexture.prototype.clone = function () {
  12676. var textureSize = this.getSize();
  12677. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12678. // Base texture
  12679. newTexture.hasAlpha = this.hasAlpha;
  12680. newTexture.level = this.level;
  12681. // RenderTarget Texture
  12682. newTexture.coordinatesMode = this.coordinatesMode;
  12683. newTexture.renderList = this.renderList.slice(0);
  12684. return newTexture;
  12685. };
  12686. return RenderTargetTexture;
  12687. })(BABYLON.Texture);
  12688. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12689. })(BABYLON || (BABYLON = {}));
  12690. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12691. var BABYLON;
  12692. (function (BABYLON) {
  12693. var ProceduralTexture = (function (_super) {
  12694. __extends(ProceduralTexture, _super);
  12695. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12696. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12697. _super.call(this, null, scene, !generateMipMaps);
  12698. this._currentRefreshId = -1;
  12699. this._refreshRate = 1;
  12700. this._vertexDeclaration = [2];
  12701. this._vertexStrideSize = 2 * 4;
  12702. this._uniforms = new Array();
  12703. this._samplers = new Array();
  12704. this._textures = new Array();
  12705. this._floats = new Array();
  12706. this._floatsArrays = {};
  12707. this._colors3 = new Array();
  12708. this._colors4 = new Array();
  12709. this._vectors2 = new Array();
  12710. this._vectors3 = new Array();
  12711. this._matrices = new Array();
  12712. this._fallbackTextureUsed = false;
  12713. scene._proceduralTextures.push(this);
  12714. this.name = name;
  12715. this.isRenderTarget = true;
  12716. this._size = size;
  12717. this._generateMipMaps = generateMipMaps;
  12718. this.setFragment(fragment);
  12719. this._fallbackTexture = fallbackTexture;
  12720. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12721. // VBO
  12722. var vertices = [];
  12723. vertices.push(1, 1);
  12724. vertices.push(-1, 1);
  12725. vertices.push(-1, -1);
  12726. vertices.push(1, -1);
  12727. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12728. // Indices
  12729. var indices = [];
  12730. indices.push(0);
  12731. indices.push(1);
  12732. indices.push(2);
  12733. indices.push(0);
  12734. indices.push(2);
  12735. indices.push(3);
  12736. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12737. }
  12738. ProceduralTexture.prototype.reset = function () {
  12739. if (this._effect === undefined) {
  12740. return;
  12741. }
  12742. var engine = this.getScene().getEngine();
  12743. engine._releaseEffect(this._effect);
  12744. };
  12745. ProceduralTexture.prototype.isReady = function () {
  12746. var _this = this;
  12747. var engine = this.getScene().getEngine();
  12748. var shaders;
  12749. if (!this._fragment) {
  12750. return false;
  12751. }
  12752. if (this._fallbackTextureUsed) {
  12753. return true;
  12754. }
  12755. if (this._fragment.fragmentElement !== undefined) {
  12756. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12757. }
  12758. else {
  12759. shaders = { vertex: "procedural", fragment: this._fragment };
  12760. }
  12761. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12762. _this.releaseInternalTexture();
  12763. if (_this._fallbackTexture) {
  12764. _this._texture = _this._fallbackTexture._texture;
  12765. _this._texture.references++;
  12766. }
  12767. _this._fallbackTextureUsed = true;
  12768. });
  12769. return this._effect.isReady();
  12770. };
  12771. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12772. this._currentRefreshId = -1;
  12773. };
  12774. ProceduralTexture.prototype.setFragment = function (fragment) {
  12775. this._fragment = fragment;
  12776. };
  12777. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12778. get: function () {
  12779. return this._refreshRate;
  12780. },
  12781. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12782. set: function (value) {
  12783. this._refreshRate = value;
  12784. this.resetRefreshCounter();
  12785. },
  12786. enumerable: true,
  12787. configurable: true
  12788. });
  12789. ProceduralTexture.prototype._shouldRender = function () {
  12790. if (!this.isReady() || !this._texture) {
  12791. return false;
  12792. }
  12793. if (this._fallbackTextureUsed) {
  12794. return false;
  12795. }
  12796. if (this._currentRefreshId === -1) {
  12797. this._currentRefreshId = 1;
  12798. return true;
  12799. }
  12800. if (this.refreshRate === this._currentRefreshId) {
  12801. this._currentRefreshId = 1;
  12802. return true;
  12803. }
  12804. this._currentRefreshId++;
  12805. return false;
  12806. };
  12807. ProceduralTexture.prototype.getRenderSize = function () {
  12808. return this._size;
  12809. };
  12810. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12811. if (this._fallbackTextureUsed) {
  12812. return;
  12813. }
  12814. this.releaseInternalTexture();
  12815. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12816. };
  12817. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12818. if (this._uniforms.indexOf(uniformName) === -1) {
  12819. this._uniforms.push(uniformName);
  12820. }
  12821. };
  12822. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12823. if (this._samplers.indexOf(name) === -1) {
  12824. this._samplers.push(name);
  12825. }
  12826. this._textures[name] = texture;
  12827. return this;
  12828. };
  12829. ProceduralTexture.prototype.setFloat = function (name, value) {
  12830. this._checkUniform(name);
  12831. this._floats[name] = value;
  12832. return this;
  12833. };
  12834. ProceduralTexture.prototype.setFloats = function (name, value) {
  12835. this._checkUniform(name);
  12836. this._floatsArrays[name] = value;
  12837. return this;
  12838. };
  12839. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12840. this._checkUniform(name);
  12841. this._colors3[name] = value;
  12842. return this;
  12843. };
  12844. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12845. this._checkUniform(name);
  12846. this._colors4[name] = value;
  12847. return this;
  12848. };
  12849. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12850. this._checkUniform(name);
  12851. this._vectors2[name] = value;
  12852. return this;
  12853. };
  12854. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12855. this._checkUniform(name);
  12856. this._vectors3[name] = value;
  12857. return this;
  12858. };
  12859. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12860. this._checkUniform(name);
  12861. this._matrices[name] = value;
  12862. return this;
  12863. };
  12864. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12865. var scene = this.getScene();
  12866. var engine = scene.getEngine();
  12867. engine.bindFramebuffer(this._texture);
  12868. // Clear
  12869. engine.clear(scene.clearColor, true, true);
  12870. // Render
  12871. engine.enableEffect(this._effect);
  12872. engine.setState(false);
  12873. for (var name in this._textures) {
  12874. this._effect.setTexture(name, this._textures[name]);
  12875. }
  12876. for (name in this._floats) {
  12877. this._effect.setFloat(name, this._floats[name]);
  12878. }
  12879. for (name in this._floatsArrays) {
  12880. this._effect.setArray(name, this._floatsArrays[name]);
  12881. }
  12882. for (name in this._colors3) {
  12883. this._effect.setColor3(name, this._colors3[name]);
  12884. }
  12885. for (name in this._colors4) {
  12886. var color = this._colors4[name];
  12887. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12888. }
  12889. for (name in this._vectors2) {
  12890. this._effect.setVector2(name, this._vectors2[name]);
  12891. }
  12892. for (name in this._vectors3) {
  12893. this._effect.setVector3(name, this._vectors3[name]);
  12894. }
  12895. for (name in this._matrices) {
  12896. this._effect.setMatrix(name, this._matrices[name]);
  12897. }
  12898. // VBOs
  12899. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12900. // Draw order
  12901. engine.draw(true, 0, 6);
  12902. // Unbind
  12903. engine.unBindFramebuffer(this._texture);
  12904. };
  12905. ProceduralTexture.prototype.clone = function () {
  12906. var textureSize = this.getSize();
  12907. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12908. // Base texture
  12909. newTexture.hasAlpha = this.hasAlpha;
  12910. newTexture.level = this.level;
  12911. // RenderTarget Texture
  12912. newTexture.coordinatesMode = this.coordinatesMode;
  12913. return newTexture;
  12914. };
  12915. ProceduralTexture.prototype.dispose = function () {
  12916. var index = this.getScene()._proceduralTextures.indexOf(this);
  12917. if (index >= 0) {
  12918. this.getScene()._proceduralTextures.splice(index, 1);
  12919. }
  12920. _super.prototype.dispose.call(this);
  12921. };
  12922. return ProceduralTexture;
  12923. })(BABYLON.Texture);
  12924. BABYLON.ProceduralTexture = ProceduralTexture;
  12925. })(BABYLON || (BABYLON = {}));
  12926. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12927. var BABYLON;
  12928. (function (BABYLON) {
  12929. var WoodProceduralTexture = (function (_super) {
  12930. __extends(WoodProceduralTexture, _super);
  12931. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12932. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12933. this._ampScale = 100.0;
  12934. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12935. this.updateShaderUniforms();
  12936. this.refreshRate = 0;
  12937. }
  12938. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12939. this.setFloat("ampScale", this._ampScale);
  12940. this.setColor3("woodColor", this._woodColor);
  12941. };
  12942. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12943. get: function () {
  12944. return this._ampScale;
  12945. },
  12946. set: function (value) {
  12947. this._ampScale = value;
  12948. this.updateShaderUniforms();
  12949. },
  12950. enumerable: true,
  12951. configurable: true
  12952. });
  12953. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12954. get: function () {
  12955. return this._woodColor;
  12956. },
  12957. set: function (value) {
  12958. this._woodColor = value;
  12959. this.updateShaderUniforms();
  12960. },
  12961. enumerable: true,
  12962. configurable: true
  12963. });
  12964. return WoodProceduralTexture;
  12965. })(BABYLON.ProceduralTexture);
  12966. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12967. var FireProceduralTexture = (function (_super) {
  12968. __extends(FireProceduralTexture, _super);
  12969. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12970. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12971. this._time = 0.0;
  12972. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12973. this._shift = 1.6;
  12974. this._autoGenerateTime = true;
  12975. this._alphaThreshold = 0.5;
  12976. this._fireColors = FireProceduralTexture.RedFireColors;
  12977. this.updateShaderUniforms();
  12978. this.refreshRate = 1;
  12979. }
  12980. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12981. this.setFloat("time", this._time);
  12982. this.setVector2("speed", this._speed);
  12983. this.setFloat("shift", this._shift);
  12984. this.setColor3("c1", this._fireColors[0]);
  12985. this.setColor3("c2", this._fireColors[1]);
  12986. this.setColor3("c3", this._fireColors[2]);
  12987. this.setColor3("c4", this._fireColors[3]);
  12988. this.setColor3("c5", this._fireColors[4]);
  12989. this.setColor3("c6", this._fireColors[5]);
  12990. this.setFloat("alphaThreshold", this._alphaThreshold);
  12991. };
  12992. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12993. if (this._autoGenerateTime) {
  12994. this._time += this.getScene().getAnimationRatio() * 0.03;
  12995. this.updateShaderUniforms();
  12996. }
  12997. _super.prototype.render.call(this, useCameraPostProcess);
  12998. };
  12999. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13000. get: function () {
  13001. return [
  13002. new BABYLON.Color3(0.5, 0.0, 1.0),
  13003. new BABYLON.Color3(0.9, 0.0, 1.0),
  13004. new BABYLON.Color3(0.2, 0.0, 1.0),
  13005. new BABYLON.Color3(1.0, 0.9, 1.0),
  13006. new BABYLON.Color3(0.1, 0.1, 1.0),
  13007. new BABYLON.Color3(0.9, 0.9, 1.0)
  13008. ];
  13009. },
  13010. enumerable: true,
  13011. configurable: true
  13012. });
  13013. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13014. get: function () {
  13015. return [
  13016. new BABYLON.Color3(0.5, 1.0, 0.0),
  13017. new BABYLON.Color3(0.5, 1.0, 0.0),
  13018. new BABYLON.Color3(0.3, 0.4, 0.0),
  13019. new BABYLON.Color3(0.5, 1.0, 0.0),
  13020. new BABYLON.Color3(0.2, 0.0, 0.0),
  13021. new BABYLON.Color3(0.5, 1.0, 0.0)
  13022. ];
  13023. },
  13024. enumerable: true,
  13025. configurable: true
  13026. });
  13027. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13028. get: function () {
  13029. return [
  13030. new BABYLON.Color3(0.5, 0.0, 0.1),
  13031. new BABYLON.Color3(0.9, 0.0, 0.0),
  13032. new BABYLON.Color3(0.2, 0.0, 0.0),
  13033. new BABYLON.Color3(1.0, 0.9, 0.0),
  13034. new BABYLON.Color3(0.1, 0.1, 0.1),
  13035. new BABYLON.Color3(0.9, 0.9, 0.9)
  13036. ];
  13037. },
  13038. enumerable: true,
  13039. configurable: true
  13040. });
  13041. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13042. get: function () {
  13043. return [
  13044. new BABYLON.Color3(0.1, 0.0, 0.5),
  13045. new BABYLON.Color3(0.0, 0.0, 0.5),
  13046. new BABYLON.Color3(0.1, 0.0, 0.2),
  13047. new BABYLON.Color3(0.0, 0.0, 1.0),
  13048. new BABYLON.Color3(0.1, 0.2, 0.3),
  13049. new BABYLON.Color3(0.0, 0.2, 0.9)
  13050. ];
  13051. },
  13052. enumerable: true,
  13053. configurable: true
  13054. });
  13055. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13056. get: function () {
  13057. return this._fireColors;
  13058. },
  13059. set: function (value) {
  13060. this._fireColors = value;
  13061. this.updateShaderUniforms();
  13062. },
  13063. enumerable: true,
  13064. configurable: true
  13065. });
  13066. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13067. get: function () {
  13068. return this._time;
  13069. },
  13070. set: function (value) {
  13071. this._time = value;
  13072. this.updateShaderUniforms();
  13073. },
  13074. enumerable: true,
  13075. configurable: true
  13076. });
  13077. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13078. get: function () {
  13079. return this._speed;
  13080. },
  13081. set: function (value) {
  13082. this._speed = value;
  13083. this.updateShaderUniforms();
  13084. },
  13085. enumerable: true,
  13086. configurable: true
  13087. });
  13088. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  13089. get: function () {
  13090. return this._shift;
  13091. },
  13092. set: function (value) {
  13093. this._shift = value;
  13094. this.updateShaderUniforms();
  13095. },
  13096. enumerable: true,
  13097. configurable: true
  13098. });
  13099. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13100. get: function () {
  13101. return this._alphaThreshold;
  13102. },
  13103. set: function (value) {
  13104. this._alphaThreshold = value;
  13105. this.updateShaderUniforms();
  13106. },
  13107. enumerable: true,
  13108. configurable: true
  13109. });
  13110. return FireProceduralTexture;
  13111. })(BABYLON.ProceduralTexture);
  13112. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13113. var CloudProceduralTexture = (function (_super) {
  13114. __extends(CloudProceduralTexture, _super);
  13115. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13116. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13117. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13118. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13119. this.updateShaderUniforms();
  13120. this.refreshRate = 0;
  13121. }
  13122. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13123. this.setColor3("skyColor", this._skyColor);
  13124. this.setColor3("cloudColor", this._cloudColor);
  13125. };
  13126. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13127. get: function () {
  13128. return this._skyColor;
  13129. },
  13130. set: function (value) {
  13131. this._skyColor = value;
  13132. this.updateShaderUniforms();
  13133. },
  13134. enumerable: true,
  13135. configurable: true
  13136. });
  13137. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13138. get: function () {
  13139. return this._cloudColor;
  13140. },
  13141. set: function (value) {
  13142. this._cloudColor = value;
  13143. this.updateShaderUniforms();
  13144. },
  13145. enumerable: true,
  13146. configurable: true
  13147. });
  13148. return CloudProceduralTexture;
  13149. })(BABYLON.ProceduralTexture);
  13150. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13151. var GrassProceduralTexture = (function (_super) {
  13152. __extends(GrassProceduralTexture, _super);
  13153. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13154. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13155. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13156. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13157. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13158. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13159. this._grassColors = [
  13160. new BABYLON.Color3(0.29, 0.38, 0.02),
  13161. new BABYLON.Color3(0.36, 0.49, 0.09),
  13162. new BABYLON.Color3(0.51, 0.6, 0.28)
  13163. ];
  13164. this.updateShaderUniforms();
  13165. this.refreshRate = 0;
  13166. }
  13167. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13168. this.setColor3("herb1Color", this._grassColors[0]);
  13169. this.setColor3("herb2Color", this._grassColors[1]);
  13170. this.setColor3("herb3Color", this._grassColors[2]);
  13171. this.setColor3("groundColor", this._groundColor);
  13172. };
  13173. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13174. get: function () {
  13175. return this._grassColors;
  13176. },
  13177. set: function (value) {
  13178. this._grassColors = value;
  13179. this.updateShaderUniforms();
  13180. },
  13181. enumerable: true,
  13182. configurable: true
  13183. });
  13184. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13185. get: function () {
  13186. return this._groundColor;
  13187. },
  13188. set: function (value) {
  13189. this.groundColor = value;
  13190. this.updateShaderUniforms();
  13191. },
  13192. enumerable: true,
  13193. configurable: true
  13194. });
  13195. return GrassProceduralTexture;
  13196. })(BABYLON.ProceduralTexture);
  13197. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13198. var RoadProceduralTexture = (function (_super) {
  13199. __extends(RoadProceduralTexture, _super);
  13200. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13201. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13202. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13203. this.updateShaderUniforms();
  13204. this.refreshRate = 0;
  13205. }
  13206. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13207. this.setColor3("roadColor", this._roadColor);
  13208. };
  13209. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13210. get: function () {
  13211. return this._roadColor;
  13212. },
  13213. set: function (value) {
  13214. this._roadColor = value;
  13215. this.updateShaderUniforms();
  13216. },
  13217. enumerable: true,
  13218. configurable: true
  13219. });
  13220. return RoadProceduralTexture;
  13221. })(BABYLON.ProceduralTexture);
  13222. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13223. var BrickProceduralTexture = (function (_super) {
  13224. __extends(BrickProceduralTexture, _super);
  13225. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13226. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13227. this._numberOfBricksHeight = 15;
  13228. this._numberOfBricksWidth = 5;
  13229. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13230. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13231. this.updateShaderUniforms();
  13232. this.refreshRate = 0;
  13233. }
  13234. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13235. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13236. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13237. this.setColor3("brickColor", this._brickColor);
  13238. this.setColor3("jointColor", this._jointColor);
  13239. };
  13240. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13241. get: function () {
  13242. return this._numberOfBricksHeight;
  13243. },
  13244. enumerable: true,
  13245. configurable: true
  13246. });
  13247. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  13248. set: function (value) {
  13249. this._numberOfBricksHeight = value;
  13250. this.updateShaderUniforms();
  13251. },
  13252. enumerable: true,
  13253. configurable: true
  13254. });
  13255. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13256. get: function () {
  13257. return this._numberOfBricksWidth;
  13258. },
  13259. set: function (value) {
  13260. this._numberOfBricksHeight = value;
  13261. this.updateShaderUniforms();
  13262. },
  13263. enumerable: true,
  13264. configurable: true
  13265. });
  13266. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13267. get: function () {
  13268. return this._jointColor;
  13269. },
  13270. set: function (value) {
  13271. this._jointColor = value;
  13272. this.updateShaderUniforms();
  13273. },
  13274. enumerable: true,
  13275. configurable: true
  13276. });
  13277. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13278. get: function () {
  13279. return this._brickColor;
  13280. },
  13281. set: function (value) {
  13282. this._brickColor = value;
  13283. this.updateShaderUniforms();
  13284. },
  13285. enumerable: true,
  13286. configurable: true
  13287. });
  13288. return BrickProceduralTexture;
  13289. })(BABYLON.ProceduralTexture);
  13290. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13291. var MarbleProceduralTexture = (function (_super) {
  13292. __extends(MarbleProceduralTexture, _super);
  13293. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13294. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13295. this._numberOfTilesHeight = 3;
  13296. this._numberOfTilesWidth = 3;
  13297. this._amplitude = 9.0;
  13298. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13299. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13300. this.updateShaderUniforms();
  13301. this.refreshRate = 0;
  13302. }
  13303. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13304. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13305. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13306. this.setFloat("amplitude", this._amplitude);
  13307. this.setColor3("marbleColor", this._marbleColor);
  13308. this.setColor3("jointColor", this._jointColor);
  13309. };
  13310. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13311. get: function () {
  13312. return this._numberOfTilesHeight;
  13313. },
  13314. set: function (value) {
  13315. this._numberOfTilesHeight = value;
  13316. this.updateShaderUniforms();
  13317. },
  13318. enumerable: true,
  13319. configurable: true
  13320. });
  13321. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13322. get: function () {
  13323. return this._numberOfTilesWidth;
  13324. },
  13325. set: function (value) {
  13326. this._numberOfTilesWidth = value;
  13327. this.updateShaderUniforms();
  13328. },
  13329. enumerable: true,
  13330. configurable: true
  13331. });
  13332. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13333. get: function () {
  13334. return this._jointColor;
  13335. },
  13336. set: function (value) {
  13337. this._jointColor = value;
  13338. this.updateShaderUniforms();
  13339. },
  13340. enumerable: true,
  13341. configurable: true
  13342. });
  13343. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13344. get: function () {
  13345. return this._marbleColor;
  13346. },
  13347. set: function (value) {
  13348. this._marbleColor = value;
  13349. this.updateShaderUniforms();
  13350. },
  13351. enumerable: true,
  13352. configurable: true
  13353. });
  13354. return MarbleProceduralTexture;
  13355. })(BABYLON.ProceduralTexture);
  13356. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13357. })(BABYLON || (BABYLON = {}));
  13358. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13359. var BABYLON;
  13360. (function (BABYLON) {
  13361. var CustomProceduralTexture = (function (_super) {
  13362. __extends(CustomProceduralTexture, _super);
  13363. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13364. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13365. this._animate = true;
  13366. this._time = 0;
  13367. this._texturePath = texturePath;
  13368. //Try to load json
  13369. this.loadJson(texturePath);
  13370. this.refreshRate = 1;
  13371. }
  13372. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13373. var _this = this;
  13374. var that = this;
  13375. function noConfigFile() {
  13376. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13377. try {
  13378. that.setFragment(that._texturePath);
  13379. }
  13380. catch (ex) {
  13381. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13382. }
  13383. }
  13384. var configFileUrl = jsonUrl + "/config.json";
  13385. var xhr = new XMLHttpRequest();
  13386. xhr.open("GET", configFileUrl, true);
  13387. xhr.addEventListener("load", function () {
  13388. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13389. try {
  13390. _this._config = JSON.parse(xhr.response);
  13391. _this.updateShaderUniforms();
  13392. _this.updateTextures();
  13393. _this.setFragment(_this._texturePath + "/custom");
  13394. _this._animate = _this._config.animate;
  13395. _this.refreshRate = _this._config.refreshrate;
  13396. }
  13397. catch (ex) {
  13398. noConfigFile();
  13399. }
  13400. }
  13401. else {
  13402. noConfigFile();
  13403. }
  13404. }, false);
  13405. xhr.addEventListener("error", function () {
  13406. noConfigFile();
  13407. }, false);
  13408. try {
  13409. xhr.send();
  13410. }
  13411. catch (ex) {
  13412. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13413. }
  13414. };
  13415. CustomProceduralTexture.prototype.isReady = function () {
  13416. if (!_super.prototype.isReady.call(this)) {
  13417. return false;
  13418. }
  13419. for (var name in this._textures) {
  13420. var texture = this._textures[name];
  13421. if (!texture.isReady()) {
  13422. return false;
  13423. }
  13424. }
  13425. return true;
  13426. };
  13427. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13428. if (this._animate) {
  13429. this._time += this.getScene().getAnimationRatio() * 0.03;
  13430. this.updateShaderUniforms();
  13431. }
  13432. _super.prototype.render.call(this, useCameraPostProcess);
  13433. };
  13434. CustomProceduralTexture.prototype.updateTextures = function () {
  13435. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13436. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13437. }
  13438. };
  13439. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13440. if (this._config) {
  13441. for (var j = 0; j < this._config.uniforms.length; j++) {
  13442. var uniform = this._config.uniforms[j];
  13443. switch (uniform.type) {
  13444. case "float":
  13445. this.setFloat(uniform.name, uniform.value);
  13446. break;
  13447. case "color3":
  13448. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13449. break;
  13450. case "color4":
  13451. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13452. break;
  13453. case "vector2":
  13454. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13455. break;
  13456. case "vector3":
  13457. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13458. break;
  13459. }
  13460. }
  13461. }
  13462. this.setFloat("time", this._time);
  13463. };
  13464. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13465. get: function () {
  13466. return this._animate;
  13467. },
  13468. set: function (value) {
  13469. this._animate = value;
  13470. },
  13471. enumerable: true,
  13472. configurable: true
  13473. });
  13474. return CustomProceduralTexture;
  13475. })(BABYLON.ProceduralTexture);
  13476. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13477. })(BABYLON || (BABYLON = {}));
  13478. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13479. var BABYLON;
  13480. (function (BABYLON) {
  13481. var MirrorTexture = (function (_super) {
  13482. __extends(MirrorTexture, _super);
  13483. function MirrorTexture(name, size, scene, generateMipMaps) {
  13484. var _this = this;
  13485. _super.call(this, name, size, scene, generateMipMaps, true);
  13486. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13487. this._transformMatrix = BABYLON.Matrix.Zero();
  13488. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13489. this.onBeforeRender = function () {
  13490. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13491. _this._savedViewMatrix = scene.getViewMatrix();
  13492. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13493. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13494. scene.clipPlane = _this.mirrorPlane;
  13495. scene.getEngine().cullBackFaces = false;
  13496. };
  13497. this.onAfterRender = function () {
  13498. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13499. scene.getEngine().cullBackFaces = true;
  13500. delete scene.clipPlane;
  13501. };
  13502. }
  13503. MirrorTexture.prototype.clone = function () {
  13504. var textureSize = this.getSize();
  13505. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13506. // Base texture
  13507. newTexture.hasAlpha = this.hasAlpha;
  13508. newTexture.level = this.level;
  13509. // Mirror Texture
  13510. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13511. newTexture.renderList = this.renderList.slice(0);
  13512. return newTexture;
  13513. };
  13514. return MirrorTexture;
  13515. })(BABYLON.RenderTargetTexture);
  13516. BABYLON.MirrorTexture = MirrorTexture;
  13517. })(BABYLON || (BABYLON = {}));
  13518. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13519. var BABYLON;
  13520. (function (BABYLON) {
  13521. var DynamicTexture = (function (_super) {
  13522. __extends(DynamicTexture, _super);
  13523. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13524. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13525. _super.call(this, null, scene, !generateMipMaps);
  13526. this.name = name;
  13527. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13528. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13529. this._generateMipMaps = generateMipMaps;
  13530. if (options.getContext) {
  13531. this._canvas = options;
  13532. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13533. }
  13534. else {
  13535. this._canvas = document.createElement("canvas");
  13536. if (options.width) {
  13537. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13538. }
  13539. else {
  13540. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13541. }
  13542. }
  13543. var textureSize = this.getSize();
  13544. this._canvas.width = textureSize.width;
  13545. this._canvas.height = textureSize.height;
  13546. this._context = this._canvas.getContext("2d");
  13547. }
  13548. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13549. get: function () {
  13550. return true;
  13551. },
  13552. enumerable: true,
  13553. configurable: true
  13554. });
  13555. DynamicTexture.prototype.scale = function (ratio) {
  13556. var textureSize = this.getSize();
  13557. textureSize.width *= ratio;
  13558. textureSize.height *= ratio;
  13559. this._canvas.width = textureSize.width;
  13560. this._canvas.height = textureSize.height;
  13561. this.releaseInternalTexture();
  13562. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13563. };
  13564. DynamicTexture.prototype.getContext = function () {
  13565. return this._context;
  13566. };
  13567. DynamicTexture.prototype.clear = function () {
  13568. var size = this.getSize();
  13569. this._context.fillRect(0, 0, size.width, size.height);
  13570. };
  13571. DynamicTexture.prototype.update = function (invertY) {
  13572. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13573. };
  13574. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13575. if (update === void 0) { update = true; }
  13576. var size = this.getSize();
  13577. if (clearColor) {
  13578. this._context.fillStyle = clearColor;
  13579. this._context.fillRect(0, 0, size.width, size.height);
  13580. }
  13581. this._context.font = font;
  13582. if (x === null) {
  13583. var textSize = this._context.measureText(text);
  13584. x = (size.width - textSize.width) / 2;
  13585. }
  13586. this._context.fillStyle = color;
  13587. this._context.fillText(text, x, y);
  13588. if (update) {
  13589. this.update(invertY);
  13590. }
  13591. };
  13592. DynamicTexture.prototype.clone = function () {
  13593. var textureSize = this.getSize();
  13594. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13595. // Base texture
  13596. newTexture.hasAlpha = this.hasAlpha;
  13597. newTexture.level = this.level;
  13598. // Dynamic Texture
  13599. newTexture.wrapU = this.wrapU;
  13600. newTexture.wrapV = this.wrapV;
  13601. return newTexture;
  13602. };
  13603. return DynamicTexture;
  13604. })(BABYLON.Texture);
  13605. BABYLON.DynamicTexture = DynamicTexture;
  13606. })(BABYLON || (BABYLON = {}));
  13607. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13608. var BABYLON;
  13609. (function (BABYLON) {
  13610. var VideoTexture = (function (_super) {
  13611. __extends(VideoTexture, _super);
  13612. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13613. var _this = this;
  13614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13615. _super.call(this, null, scene, !generateMipMaps, invertY);
  13616. this._autoLaunch = true;
  13617. this.name = name;
  13618. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13619. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13620. var requiredWidth = size.width || size;
  13621. var requiredHeight = size.height || size;
  13622. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13623. var textureSize = this.getSize();
  13624. this.video = document.createElement("video");
  13625. this.video.width = textureSize.width;
  13626. this.video.height = textureSize.height;
  13627. this.video.autoplay = false;
  13628. this.video.loop = true;
  13629. this.video.addEventListener("canplaythrough", function () {
  13630. if (_this._texture) {
  13631. _this._texture.isReady = true;
  13632. }
  13633. });
  13634. urls.forEach(function (url) {
  13635. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13636. var source = document.createElement("source");
  13637. source.src = url;
  13638. _this.video.appendChild(source);
  13639. });
  13640. this._lastUpdate = BABYLON.Tools.Now;
  13641. }
  13642. VideoTexture.prototype.update = function () {
  13643. if (this._autoLaunch) {
  13644. this._autoLaunch = false;
  13645. this.video.play();
  13646. }
  13647. var now = BABYLON.Tools.Now;
  13648. if (now - this._lastUpdate < 15) {
  13649. return false;
  13650. }
  13651. this._lastUpdate = now;
  13652. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13653. return true;
  13654. };
  13655. return VideoTexture;
  13656. })(BABYLON.Texture);
  13657. BABYLON.VideoTexture = VideoTexture;
  13658. })(BABYLON || (BABYLON = {}));
  13659. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13660. (function (BABYLON) {
  13661. var EffectFallbacks = (function () {
  13662. function EffectFallbacks() {
  13663. this._defines = {};
  13664. this._currentRank = 32;
  13665. this._maxRank = -1;
  13666. }
  13667. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13668. if (!this._defines[rank]) {
  13669. if (rank < this._currentRank) {
  13670. this._currentRank = rank;
  13671. }
  13672. if (rank > this._maxRank) {
  13673. this._maxRank = rank;
  13674. }
  13675. this._defines[rank] = new Array();
  13676. }
  13677. this._defines[rank].push(define);
  13678. };
  13679. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13680. get: function () {
  13681. return this._currentRank <= this._maxRank;
  13682. },
  13683. enumerable: true,
  13684. configurable: true
  13685. });
  13686. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13687. var currentFallbacks = this._defines[this._currentRank];
  13688. for (var index = 0; index < currentFallbacks.length; index++) {
  13689. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13690. }
  13691. this._currentRank++;
  13692. return currentDefines;
  13693. };
  13694. return EffectFallbacks;
  13695. })();
  13696. BABYLON.EffectFallbacks = EffectFallbacks;
  13697. var Effect = (function () {
  13698. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13699. var _this = this;
  13700. this._isReady = false;
  13701. this._compilationError = "";
  13702. this._valueCache = [];
  13703. this._engine = engine;
  13704. this.name = baseName;
  13705. this.defines = defines;
  13706. this._uniformsNames = uniformsNames.concat(samplers);
  13707. this._samplers = samplers;
  13708. this._attributesNames = attributesNames;
  13709. this.onError = onError;
  13710. this.onCompiled = onCompiled;
  13711. var vertexSource;
  13712. var fragmentSource;
  13713. if (baseName.vertexElement) {
  13714. vertexSource = document.getElementById(baseName.vertexElement);
  13715. if (!vertexSource) {
  13716. vertexSource = baseName.vertexElement;
  13717. }
  13718. }
  13719. else {
  13720. vertexSource = baseName.vertex || baseName;
  13721. }
  13722. if (baseName.fragmentElement) {
  13723. fragmentSource = document.getElementById(baseName.fragmentElement);
  13724. if (!fragmentSource) {
  13725. fragmentSource = baseName.fragmentElement;
  13726. }
  13727. }
  13728. else {
  13729. fragmentSource = baseName.fragment || baseName;
  13730. }
  13731. this._loadVertexShader(vertexSource, function (vertexCode) {
  13732. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13733. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13734. });
  13735. });
  13736. }
  13737. // Properties
  13738. Effect.prototype.isReady = function () {
  13739. return this._isReady;
  13740. };
  13741. Effect.prototype.getProgram = function () {
  13742. return this._program;
  13743. };
  13744. Effect.prototype.getAttributesNames = function () {
  13745. return this._attributesNames;
  13746. };
  13747. Effect.prototype.getAttributeLocation = function (index) {
  13748. return this._attributes[index];
  13749. };
  13750. Effect.prototype.getAttributeLocationByName = function (name) {
  13751. var index = this._attributesNames.indexOf(name);
  13752. return this._attributes[index];
  13753. };
  13754. Effect.prototype.getAttributesCount = function () {
  13755. return this._attributes.length;
  13756. };
  13757. Effect.prototype.getUniformIndex = function (uniformName) {
  13758. return this._uniformsNames.indexOf(uniformName);
  13759. };
  13760. Effect.prototype.getUniform = function (uniformName) {
  13761. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13762. };
  13763. Effect.prototype.getSamplers = function () {
  13764. return this._samplers;
  13765. };
  13766. Effect.prototype.getCompilationError = function () {
  13767. return this._compilationError;
  13768. };
  13769. // Methods
  13770. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13771. // DOM element ?
  13772. if (vertex instanceof HTMLElement) {
  13773. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13774. callback(vertexCode);
  13775. return;
  13776. }
  13777. // Is in local store ?
  13778. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13779. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13780. return;
  13781. }
  13782. var vertexShaderUrl;
  13783. if (vertex[0] === ".") {
  13784. vertexShaderUrl = vertex;
  13785. }
  13786. else {
  13787. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13788. }
  13789. // Vertex shader
  13790. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13791. };
  13792. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13793. // DOM element ?
  13794. if (fragment instanceof HTMLElement) {
  13795. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13796. callback(fragmentCode);
  13797. return;
  13798. }
  13799. // Is in local store ?
  13800. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13801. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13802. return;
  13803. }
  13804. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13805. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13806. return;
  13807. }
  13808. var fragmentShaderUrl;
  13809. if (fragment[0] === ".") {
  13810. fragmentShaderUrl = fragment;
  13811. }
  13812. else {
  13813. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13814. }
  13815. // Fragment shader
  13816. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13817. };
  13818. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13819. try {
  13820. var engine = this._engine;
  13821. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13822. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13823. this._attributes = engine.getAttributes(this._program, attributesNames);
  13824. for (var index = 0; index < this._samplers.length; index++) {
  13825. var sampler = this.getUniform(this._samplers[index]);
  13826. if (sampler == null) {
  13827. this._samplers.splice(index, 1);
  13828. index--;
  13829. }
  13830. }
  13831. engine.bindSamplers(this);
  13832. this._isReady = true;
  13833. if (this.onCompiled) {
  13834. this.onCompiled(this);
  13835. }
  13836. }
  13837. catch (e) {
  13838. // Is it a problem with precision?
  13839. if (e.message.indexOf("highp") !== -1) {
  13840. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13841. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13842. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13843. return;
  13844. }
  13845. // Let's go through fallbacks then
  13846. if (fallbacks && fallbacks.isMoreFallbacks) {
  13847. defines = fallbacks.reduce(defines);
  13848. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13849. }
  13850. else {
  13851. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13852. BABYLON.Tools.Error("Defines: " + defines);
  13853. BABYLON.Tools.Error("Error: " + e.message);
  13854. this._compilationError = e.message;
  13855. if (this.onError) {
  13856. this.onError(this, this._compilationError);
  13857. }
  13858. }
  13859. }
  13860. };
  13861. Effect.prototype._bindTexture = function (channel, texture) {
  13862. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13863. };
  13864. Effect.prototype.setTexture = function (channel, texture) {
  13865. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13866. };
  13867. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13868. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13869. };
  13870. //public _cacheMatrix(uniformName, matrix) {
  13871. // if (!this._valueCache[uniformName]) {
  13872. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13873. // }
  13874. // for (var index = 0; index < 16; index++) {
  13875. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13876. // }
  13877. //};
  13878. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13879. if (!this._valueCache[uniformName]) {
  13880. this._valueCache[uniformName] = [x, y];
  13881. return;
  13882. }
  13883. this._valueCache[uniformName][0] = x;
  13884. this._valueCache[uniformName][1] = y;
  13885. };
  13886. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13887. if (!this._valueCache[uniformName]) {
  13888. this._valueCache[uniformName] = [x, y, z];
  13889. return;
  13890. }
  13891. this._valueCache[uniformName][0] = x;
  13892. this._valueCache[uniformName][1] = y;
  13893. this._valueCache[uniformName][2] = z;
  13894. };
  13895. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13896. if (!this._valueCache[uniformName]) {
  13897. this._valueCache[uniformName] = [x, y, z, w];
  13898. return;
  13899. }
  13900. this._valueCache[uniformName][0] = x;
  13901. this._valueCache[uniformName][1] = y;
  13902. this._valueCache[uniformName][2] = z;
  13903. this._valueCache[uniformName][3] = w;
  13904. };
  13905. Effect.prototype.setArray = function (uniformName, array) {
  13906. this._engine.setArray(this.getUniform(uniformName), array);
  13907. return this;
  13908. };
  13909. Effect.prototype.setArray2 = function (uniformName, array) {
  13910. this._engine.setArray2(this.getUniform(uniformName), array);
  13911. return this;
  13912. };
  13913. Effect.prototype.setArray3 = function (uniformName, array) {
  13914. this._engine.setArray3(this.getUniform(uniformName), array);
  13915. return this;
  13916. };
  13917. Effect.prototype.setArray4 = function (uniformName, array) {
  13918. this._engine.setArray4(this.getUniform(uniformName), array);
  13919. return this;
  13920. };
  13921. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13922. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13923. return this;
  13924. };
  13925. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13926. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13927. // return;
  13928. //this._cacheMatrix(uniformName, matrix);
  13929. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13930. return this;
  13931. };
  13932. Effect.prototype.setFloat = function (uniformName, value) {
  13933. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13934. return this;
  13935. this._valueCache[uniformName] = value;
  13936. this._engine.setFloat(this.getUniform(uniformName), value);
  13937. return this;
  13938. };
  13939. Effect.prototype.setBool = function (uniformName, bool) {
  13940. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13941. return this;
  13942. this._valueCache[uniformName] = bool;
  13943. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13944. return this;
  13945. };
  13946. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13947. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13948. return this;
  13949. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13950. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13951. return this;
  13952. };
  13953. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13954. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13955. return this;
  13956. this._cacheFloat2(uniformName, x, y);
  13957. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13958. return this;
  13959. };
  13960. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13961. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13962. return this;
  13963. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13964. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13965. return this;
  13966. };
  13967. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13968. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13969. return this;
  13970. this._cacheFloat3(uniformName, x, y, z);
  13971. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13972. return this;
  13973. };
  13974. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13975. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13976. return this;
  13977. this._cacheFloat4(uniformName, x, y, z, w);
  13978. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13979. return this;
  13980. };
  13981. Effect.prototype.setColor3 = function (uniformName, color3) {
  13982. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13983. return this;
  13984. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13985. this._engine.setColor3(this.getUniform(uniformName), color3);
  13986. return this;
  13987. };
  13988. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13989. 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)
  13990. return this;
  13991. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13992. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13993. return this;
  13994. };
  13995. // Statics
  13996. 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}",
  13997. 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}",
  13998. 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}",
  13999. 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}",
  14000. 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}",
  14001. 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}",
  14002. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  14003. 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}",
  14004. 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}",
  14005. 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}",
  14006. 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)\n{\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, 0.002);\n\n float d = t - moments.x;\n\n return clamp(variance / (variance + d * d) - 0.05, 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}",
  14007. 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}",
  14008. 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}",
  14009. 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(NEED_UV)\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}",
  14010. 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}",
  14011. 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}",
  14012. 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}",
  14013. 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}",
  14014. 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}",
  14015. 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}",
  14016. 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}",
  14017. 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}",
  14018. 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}",
  14019. 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}",
  14020. 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}",
  14021. 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}",
  14022. 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}",
  14023. 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}",
  14024. 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}",
  14025. 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}",
  14026. 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}",
  14027. 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}",
  14028. 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}",
  14029. 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}",
  14030. 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}",
  14031. 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}",
  14032. 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}",
  14033. 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}",
  14034. 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}",
  14035. 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}",
  14036. 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}",
  14037. 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}",
  14038. 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}",
  14039. 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}",
  14040. 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}",
  14041. 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;\nuniform float opacityLevel;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || 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 OPACITY\n vec4 opacityColor = texture2D(opacitySampler, vUV);\n float alpha = 1.0;\n\n #ifdef OPACITYRGB\n opacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n #else\n alpha *= opacityColor.a * opacityLevel;\n #endif\n\n #if defined(BASIC_RENDER)\n gl_FragColor = vec4(diffuseColor.rgb, alpha);\n #else\n gl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n #endif\n\n gl_FragColor.a = alpha;\n#else\n #ifndef BASIC_RENDER\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n #else\n gl_FragColor = diffuseColor;\n #endif\n#endif\n\n}",
  14042. 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}",
  14043. };
  14044. return Effect;
  14045. })();
  14046. BABYLON.Effect = Effect;
  14047. })(BABYLON || (BABYLON = {}));
  14048. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14049. (function (BABYLON) {
  14050. var Material = (function () {
  14051. function Material(name, scene, doNotAdd) {
  14052. this.name = name;
  14053. this.checkReadyOnEveryCall = true;
  14054. this.checkReadyOnlyOnce = false;
  14055. this.state = "";
  14056. this.alpha = 1.0;
  14057. this.backFaceCulling = true;
  14058. this._wasPreviouslyReady = false;
  14059. this._fillMode = Material.TriangleFillMode;
  14060. this.pointSize = 1.0;
  14061. this.id = name;
  14062. this._scene = scene;
  14063. if (!doNotAdd) {
  14064. scene.materials.push(this);
  14065. }
  14066. }
  14067. Object.defineProperty(Material, "TriangleFillMode", {
  14068. get: function () {
  14069. return Material._TriangleFillMode;
  14070. },
  14071. enumerable: true,
  14072. configurable: true
  14073. });
  14074. Object.defineProperty(Material, "WireFrameFillMode", {
  14075. get: function () {
  14076. return Material._WireFrameFillMode;
  14077. },
  14078. enumerable: true,
  14079. configurable: true
  14080. });
  14081. Object.defineProperty(Material, "PointFillMode", {
  14082. get: function () {
  14083. return Material._PointFillMode;
  14084. },
  14085. enumerable: true,
  14086. configurable: true
  14087. });
  14088. Object.defineProperty(Material.prototype, "wireframe", {
  14089. get: function () {
  14090. return this._fillMode === Material.WireFrameFillMode;
  14091. },
  14092. set: function (value) {
  14093. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14094. },
  14095. enumerable: true,
  14096. configurable: true
  14097. });
  14098. Object.defineProperty(Material.prototype, "pointsCloud", {
  14099. get: function () {
  14100. return this._fillMode === Material.PointFillMode;
  14101. },
  14102. set: function (value) {
  14103. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14104. },
  14105. enumerable: true,
  14106. configurable: true
  14107. });
  14108. Object.defineProperty(Material.prototype, "fillMode", {
  14109. get: function () {
  14110. return this._fillMode;
  14111. },
  14112. set: function (value) {
  14113. this._fillMode = value;
  14114. },
  14115. enumerable: true,
  14116. configurable: true
  14117. });
  14118. Material.prototype.isReady = function (mesh, useInstances) {
  14119. return true;
  14120. };
  14121. Material.prototype.getEffect = function () {
  14122. return this._effect;
  14123. };
  14124. Material.prototype.getScene = function () {
  14125. return this._scene;
  14126. };
  14127. Material.prototype.needAlphaBlending = function () {
  14128. return (this.alpha < 1.0);
  14129. };
  14130. Material.prototype.needAlphaTesting = function () {
  14131. return false;
  14132. };
  14133. Material.prototype.getAlphaTestTexture = function () {
  14134. return null;
  14135. };
  14136. Material.prototype.trackCreation = function (onCompiled, onError) {
  14137. };
  14138. Material.prototype._preBind = function () {
  14139. var engine = this._scene.getEngine();
  14140. engine.enableEffect(this._effect);
  14141. engine.setState(this.backFaceCulling);
  14142. };
  14143. Material.prototype.bind = function (world, mesh) {
  14144. this._scene._cachedMaterial = this;
  14145. if (this.onBind) {
  14146. this.onBind(this);
  14147. }
  14148. };
  14149. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14150. };
  14151. Material.prototype.unbind = function () {
  14152. };
  14153. Material.prototype.dispose = function (forceDisposeEffect) {
  14154. // Remove from scene
  14155. var index = this._scene.materials.indexOf(this);
  14156. this._scene.materials.splice(index, 1);
  14157. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14158. if (forceDisposeEffect && this._effect) {
  14159. this._scene.getEngine()._releaseEffect(this._effect);
  14160. this._effect = null;
  14161. }
  14162. // Callback
  14163. if (this.onDispose) {
  14164. this.onDispose();
  14165. }
  14166. };
  14167. Material._TriangleFillMode = 0;
  14168. Material._WireFrameFillMode = 1;
  14169. Material._PointFillMode = 2;
  14170. return Material;
  14171. })();
  14172. BABYLON.Material = Material;
  14173. })(BABYLON || (BABYLON = {}));
  14174. //# sourceMappingURL=babylon.material.js.map
  14175. var BABYLON;
  14176. (function (BABYLON) {
  14177. var maxSimultaneousLights = 4;
  14178. var FresnelParameters = (function () {
  14179. function FresnelParameters() {
  14180. this.isEnabled = true;
  14181. this.leftColor = BABYLON.Color3.White();
  14182. this.rightColor = BABYLON.Color3.Black();
  14183. this.bias = 0;
  14184. this.power = 1;
  14185. }
  14186. return FresnelParameters;
  14187. })();
  14188. BABYLON.FresnelParameters = FresnelParameters;
  14189. var StandardMaterial = (function (_super) {
  14190. __extends(StandardMaterial, _super);
  14191. function StandardMaterial(name, scene) {
  14192. var _this = this;
  14193. _super.call(this, name, scene);
  14194. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14195. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14196. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14197. this.specularPower = 64;
  14198. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14199. this.useAlphaFromDiffuseTexture = false;
  14200. this.useSpecularOverAlpha = true;
  14201. this.fogEnabled = true;
  14202. this._cachedDefines = null;
  14203. this._renderTargets = new BABYLON.SmartArray(16);
  14204. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14205. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14206. this._scaledDiffuse = new BABYLON.Color3();
  14207. this._scaledSpecular = new BABYLON.Color3();
  14208. this.getRenderTargetTextures = function () {
  14209. _this._renderTargets.reset();
  14210. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14211. _this._renderTargets.push(_this.reflectionTexture);
  14212. }
  14213. return _this._renderTargets;
  14214. };
  14215. }
  14216. StandardMaterial.prototype.needAlphaBlending = function () {
  14217. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14218. };
  14219. StandardMaterial.prototype.needAlphaTesting = function () {
  14220. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14221. };
  14222. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14223. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14224. };
  14225. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14226. return this.diffuseTexture;
  14227. };
  14228. // Methods
  14229. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14230. if (this.checkReadyOnlyOnce) {
  14231. if (this._wasPreviouslyReady) {
  14232. return true;
  14233. }
  14234. }
  14235. var scene = this.getScene();
  14236. if (!this.checkReadyOnEveryCall) {
  14237. if (this._renderId === scene.getRenderId()) {
  14238. return true;
  14239. }
  14240. }
  14241. var engine = scene.getEngine();
  14242. var defines = [];
  14243. var fallbacks = new BABYLON.EffectFallbacks();
  14244. var needNormals = false;
  14245. var needUVs = false;
  14246. // Textures
  14247. if (scene.texturesEnabled) {
  14248. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14249. if (!this.diffuseTexture.isReady()) {
  14250. return false;
  14251. }
  14252. else {
  14253. needUVs = true;
  14254. defines.push("#define DIFFUSE");
  14255. }
  14256. }
  14257. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14258. if (!this.ambientTexture.isReady()) {
  14259. return false;
  14260. }
  14261. else {
  14262. needUVs = true;
  14263. defines.push("#define AMBIENT");
  14264. }
  14265. }
  14266. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14267. if (!this.opacityTexture.isReady()) {
  14268. return false;
  14269. }
  14270. else {
  14271. needUVs = true;
  14272. defines.push("#define OPACITY");
  14273. if (this.opacityTexture.getAlphaFromRGB) {
  14274. defines.push("#define OPACITYRGB");
  14275. }
  14276. }
  14277. }
  14278. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14279. if (!this.reflectionTexture.isReady()) {
  14280. return false;
  14281. }
  14282. else {
  14283. needNormals = true;
  14284. needUVs = true;
  14285. defines.push("#define REFLECTION");
  14286. fallbacks.addFallback(0, "REFLECTION");
  14287. }
  14288. }
  14289. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14290. if (!this.emissiveTexture.isReady()) {
  14291. return false;
  14292. }
  14293. else {
  14294. needUVs = true;
  14295. defines.push("#define EMISSIVE");
  14296. }
  14297. }
  14298. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14299. if (!this.specularTexture.isReady()) {
  14300. return false;
  14301. }
  14302. else {
  14303. needUVs = true;
  14304. defines.push("#define SPECULAR");
  14305. fallbacks.addFallback(0, "SPECULAR");
  14306. }
  14307. }
  14308. }
  14309. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14310. if (!this.bumpTexture.isReady()) {
  14311. return false;
  14312. }
  14313. else {
  14314. needUVs = true;
  14315. defines.push("#define BUMP");
  14316. fallbacks.addFallback(0, "BUMP");
  14317. }
  14318. }
  14319. // Effect
  14320. if (this.useSpecularOverAlpha) {
  14321. defines.push("#define SPECULAROVERALPHA");
  14322. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14323. }
  14324. if (scene.clipPlane) {
  14325. defines.push("#define CLIPPLANE");
  14326. }
  14327. if (engine.getAlphaTesting()) {
  14328. defines.push("#define ALPHATEST");
  14329. }
  14330. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14331. defines.push("#define ALPHAFROMDIFFUSE");
  14332. }
  14333. // Point size
  14334. if (this.pointsCloud || scene.forcePointsCloud) {
  14335. defines.push("#define POINTSIZE");
  14336. }
  14337. // Fog
  14338. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14339. defines.push("#define FOG");
  14340. fallbacks.addFallback(1, "FOG");
  14341. }
  14342. var shadowsActivated = false;
  14343. var lightIndex = 0;
  14344. if (scene.lightsEnabled) {
  14345. for (var index = 0; index < scene.lights.length; index++) {
  14346. var light = scene.lights[index];
  14347. if (!light.isEnabled()) {
  14348. continue;
  14349. }
  14350. // Excluded check
  14351. if (light._excludedMeshesIds.length > 0) {
  14352. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14353. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14354. if (excludedMesh) {
  14355. light.excludedMeshes.push(excludedMesh);
  14356. }
  14357. }
  14358. light._excludedMeshesIds = [];
  14359. }
  14360. // Included check
  14361. if (light._includedOnlyMeshesIds.length > 0) {
  14362. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14363. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14364. if (includedOnlyMesh) {
  14365. light.includedOnlyMeshes.push(includedOnlyMesh);
  14366. }
  14367. }
  14368. light._includedOnlyMeshesIds = [];
  14369. }
  14370. if (!light.canAffectMesh(mesh)) {
  14371. continue;
  14372. }
  14373. needNormals = true;
  14374. defines.push("#define LIGHT" + lightIndex);
  14375. if (lightIndex > 0) {
  14376. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14377. }
  14378. var type;
  14379. if (light instanceof BABYLON.SpotLight) {
  14380. type = "#define SPOTLIGHT" + lightIndex;
  14381. }
  14382. else if (light instanceof BABYLON.HemisphericLight) {
  14383. type = "#define HEMILIGHT" + lightIndex;
  14384. }
  14385. else {
  14386. type = "#define POINTDIRLIGHT" + lightIndex;
  14387. }
  14388. defines.push(type);
  14389. if (lightIndex > 0) {
  14390. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14391. }
  14392. // Shadows
  14393. if (scene.shadowsEnabled) {
  14394. var shadowGenerator = light.getShadowGenerator();
  14395. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14396. defines.push("#define SHADOW" + lightIndex);
  14397. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14398. if (!shadowsActivated) {
  14399. defines.push("#define SHADOWS");
  14400. shadowsActivated = true;
  14401. }
  14402. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14403. defines.push("#define SHADOWVSM" + lightIndex);
  14404. if (lightIndex > 0) {
  14405. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14406. }
  14407. }
  14408. if (shadowGenerator.usePoissonSampling) {
  14409. defines.push("#define SHADOWPCF" + lightIndex);
  14410. if (lightIndex > 0) {
  14411. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14412. }
  14413. }
  14414. }
  14415. }
  14416. lightIndex++;
  14417. if (lightIndex === maxSimultaneousLights)
  14418. break;
  14419. }
  14420. }
  14421. if (StandardMaterial.FresnelEnabled) {
  14422. // Fresnel
  14423. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14424. var fresnelRank = 1;
  14425. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14426. defines.push("#define DIFFUSEFRESNEL");
  14427. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14428. fresnelRank++;
  14429. }
  14430. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14431. defines.push("#define OPACITYFRESNEL");
  14432. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14433. fresnelRank++;
  14434. }
  14435. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14436. defines.push("#define REFLECTIONFRESNEL");
  14437. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14438. fresnelRank++;
  14439. }
  14440. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14441. defines.push("#define EMISSIVEFRESNEL");
  14442. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14443. fresnelRank++;
  14444. }
  14445. needNormals = true;
  14446. defines.push("#define FRESNEL");
  14447. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14448. }
  14449. }
  14450. // Attribs
  14451. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14452. if (mesh) {
  14453. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14454. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14455. defines.push("#define NORMAL");
  14456. }
  14457. if (needUVs) {
  14458. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14459. attribs.push(BABYLON.VertexBuffer.UVKind);
  14460. defines.push("#define UV1");
  14461. }
  14462. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14463. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14464. defines.push("#define UV2");
  14465. }
  14466. }
  14467. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14468. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14469. defines.push("#define VERTEXCOLOR");
  14470. if (mesh.hasVertexAlpha) {
  14471. defines.push("#define VERTEXALPHA");
  14472. }
  14473. }
  14474. if (mesh.useBones) {
  14475. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14476. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14477. defines.push("#define BONES");
  14478. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14479. defines.push("#define BONES4");
  14480. fallbacks.addFallback(0, "BONES4");
  14481. }
  14482. // Instances
  14483. if (useInstances) {
  14484. defines.push("#define INSTANCES");
  14485. attribs.push("world0");
  14486. attribs.push("world1");
  14487. attribs.push("world2");
  14488. attribs.push("world3");
  14489. }
  14490. }
  14491. // Get correct effect
  14492. var join = defines.join("\n");
  14493. if (this._cachedDefines !== join) {
  14494. this._cachedDefines = join;
  14495. scene.resetCachedMaterial();
  14496. // Legacy browser patch
  14497. var shaderName = "default";
  14498. if (!scene.getEngine().getCaps().standardDerivatives) {
  14499. shaderName = "legacydefault";
  14500. }
  14501. 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);
  14502. }
  14503. if (!this._effect.isReady()) {
  14504. return false;
  14505. }
  14506. this._renderId = scene.getRenderId();
  14507. this._wasPreviouslyReady = true;
  14508. return true;
  14509. };
  14510. StandardMaterial.prototype.unbind = function () {
  14511. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14512. this._effect.setTexture("reflection2DSampler", null);
  14513. }
  14514. };
  14515. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14516. this._effect.setMatrix("world", world);
  14517. };
  14518. StandardMaterial.prototype.bind = function (world, mesh) {
  14519. var scene = this.getScene();
  14520. // Matrices
  14521. this.bindOnlyWorldMatrix(world);
  14522. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14523. // Bones
  14524. if (mesh.useBones) {
  14525. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14526. }
  14527. if (scene.getCachedMaterial() !== this) {
  14528. if (StandardMaterial.FresnelEnabled) {
  14529. // Fresnel
  14530. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14531. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14532. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14533. }
  14534. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14535. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14536. }
  14537. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14538. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14539. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14540. }
  14541. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14542. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14543. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14544. }
  14545. }
  14546. // Textures
  14547. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14548. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14549. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14550. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14551. }
  14552. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14553. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14554. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14555. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14556. }
  14557. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14558. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14559. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14560. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14561. }
  14562. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14563. if (this.reflectionTexture.isCube) {
  14564. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14565. }
  14566. else {
  14567. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14568. }
  14569. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14570. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14571. }
  14572. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14573. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14574. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14575. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14576. }
  14577. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14578. this._effect.setTexture("specularSampler", this.specularTexture);
  14579. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14580. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14581. }
  14582. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14583. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14584. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14585. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14586. }
  14587. // Clip plane
  14588. if (scene.clipPlane) {
  14589. var clipPlane = scene.clipPlane;
  14590. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14591. }
  14592. // Point size
  14593. if (this.pointsCloud) {
  14594. this._effect.setFloat("pointSize", this.pointSize);
  14595. }
  14596. // Colors
  14597. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14598. // Scaling down color according to emissive
  14599. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14600. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14601. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14602. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14603. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14604. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14605. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14606. }
  14607. // Scaling down color according to emissive
  14608. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14609. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14610. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14611. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14612. if (scene.lightsEnabled) {
  14613. var lightIndex = 0;
  14614. for (var index = 0; index < scene.lights.length; index++) {
  14615. var light = scene.lights[index];
  14616. if (!light.isEnabled()) {
  14617. continue;
  14618. }
  14619. if (!light.canAffectMesh(mesh)) {
  14620. continue;
  14621. }
  14622. if (light instanceof BABYLON.PointLight) {
  14623. // Point Light
  14624. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14625. }
  14626. else if (light instanceof BABYLON.DirectionalLight) {
  14627. // Directional Light
  14628. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14629. }
  14630. else if (light instanceof BABYLON.SpotLight) {
  14631. // Spot Light
  14632. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14633. }
  14634. else if (light instanceof BABYLON.HemisphericLight) {
  14635. // Hemispheric Light
  14636. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14637. }
  14638. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14639. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14640. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14641. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14642. // Shadows
  14643. if (scene.shadowsEnabled) {
  14644. var shadowGenerator = light.getShadowGenerator();
  14645. if (mesh.receiveShadows && shadowGenerator) {
  14646. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14647. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14648. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  14649. }
  14650. }
  14651. lightIndex++;
  14652. if (lightIndex === maxSimultaneousLights)
  14653. break;
  14654. }
  14655. }
  14656. // View
  14657. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14658. this._effect.setMatrix("view", scene.getViewMatrix());
  14659. }
  14660. // Fog
  14661. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14662. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14663. this._effect.setColor3("vFogColor", scene.fogColor);
  14664. }
  14665. _super.prototype.bind.call(this, world, mesh);
  14666. };
  14667. StandardMaterial.prototype.getAnimatables = function () {
  14668. var results = [];
  14669. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14670. results.push(this.diffuseTexture);
  14671. }
  14672. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14673. results.push(this.ambientTexture);
  14674. }
  14675. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14676. results.push(this.opacityTexture);
  14677. }
  14678. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14679. results.push(this.reflectionTexture);
  14680. }
  14681. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14682. results.push(this.emissiveTexture);
  14683. }
  14684. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14685. results.push(this.specularTexture);
  14686. }
  14687. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14688. results.push(this.bumpTexture);
  14689. }
  14690. return results;
  14691. };
  14692. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14693. if (this.diffuseTexture) {
  14694. this.diffuseTexture.dispose();
  14695. }
  14696. if (this.ambientTexture) {
  14697. this.ambientTexture.dispose();
  14698. }
  14699. if (this.opacityTexture) {
  14700. this.opacityTexture.dispose();
  14701. }
  14702. if (this.reflectionTexture) {
  14703. this.reflectionTexture.dispose();
  14704. }
  14705. if (this.emissiveTexture) {
  14706. this.emissiveTexture.dispose();
  14707. }
  14708. if (this.specularTexture) {
  14709. this.specularTexture.dispose();
  14710. }
  14711. if (this.bumpTexture) {
  14712. this.bumpTexture.dispose();
  14713. }
  14714. _super.prototype.dispose.call(this, forceDisposeEffect);
  14715. };
  14716. StandardMaterial.prototype.clone = function (name) {
  14717. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14718. // Base material
  14719. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14720. newStandardMaterial.alpha = this.alpha;
  14721. newStandardMaterial.fillMode = this.fillMode;
  14722. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14723. // Standard material
  14724. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14725. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14726. }
  14727. if (this.ambientTexture && this.ambientTexture.clone) {
  14728. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14729. }
  14730. if (this.opacityTexture && this.opacityTexture.clone) {
  14731. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14732. }
  14733. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14734. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14735. }
  14736. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14737. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14738. }
  14739. if (this.specularTexture && this.specularTexture.clone) {
  14740. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14741. }
  14742. if (this.bumpTexture && this.bumpTexture.clone) {
  14743. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14744. }
  14745. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14746. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14747. newStandardMaterial.specularColor = this.specularColor.clone();
  14748. newStandardMaterial.specularPower = this.specularPower;
  14749. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14750. return newStandardMaterial;
  14751. };
  14752. // Statics
  14753. // Flags used to enable or disable a type of texture for all Standard Materials
  14754. StandardMaterial.DiffuseTextureEnabled = true;
  14755. StandardMaterial.AmbientTextureEnabled = true;
  14756. StandardMaterial.OpacityTextureEnabled = true;
  14757. StandardMaterial.ReflectionTextureEnabled = true;
  14758. StandardMaterial.EmissiveTextureEnabled = true;
  14759. StandardMaterial.SpecularTextureEnabled = true;
  14760. StandardMaterial.BumpTextureEnabled = true;
  14761. StandardMaterial.FresnelEnabled = true;
  14762. return StandardMaterial;
  14763. })(BABYLON.Material);
  14764. BABYLON.StandardMaterial = StandardMaterial;
  14765. })(BABYLON || (BABYLON = {}));
  14766. //# sourceMappingURL=babylon.standardMaterial.js.map
  14767. var BABYLON;
  14768. (function (BABYLON) {
  14769. var MultiMaterial = (function (_super) {
  14770. __extends(MultiMaterial, _super);
  14771. function MultiMaterial(name, scene) {
  14772. _super.call(this, name, scene, true);
  14773. this.subMaterials = new Array();
  14774. scene.multiMaterials.push(this);
  14775. }
  14776. // Properties
  14777. MultiMaterial.prototype.getSubMaterial = function (index) {
  14778. if (index < 0 || index >= this.subMaterials.length) {
  14779. return this.getScene().defaultMaterial;
  14780. }
  14781. return this.subMaterials[index];
  14782. };
  14783. // Methods
  14784. MultiMaterial.prototype.isReady = function (mesh) {
  14785. for (var index = 0; index < this.subMaterials.length; index++) {
  14786. var subMaterial = this.subMaterials[index];
  14787. if (subMaterial) {
  14788. if (!this.subMaterials[index].isReady(mesh)) {
  14789. return false;
  14790. }
  14791. }
  14792. }
  14793. return true;
  14794. };
  14795. return MultiMaterial;
  14796. })(BABYLON.Material);
  14797. BABYLON.MultiMaterial = MultiMaterial;
  14798. })(BABYLON || (BABYLON = {}));
  14799. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14800. (function (BABYLON) {
  14801. var Database = (function () {
  14802. function Database(urlToScene, callbackManifestChecked) {
  14803. // Handling various flavors of prefixed version of IndexedDB
  14804. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14805. this.callbackManifestChecked = callbackManifestChecked;
  14806. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14807. this.db = null;
  14808. this.enableSceneOffline = false;
  14809. this.enableTexturesOffline = false;
  14810. this.manifestVersionFound = 0;
  14811. this.mustUpdateRessources = false;
  14812. this.hasReachedQuota = false;
  14813. this.checkManifestFile();
  14814. }
  14815. Database.prototype.checkManifestFile = function () {
  14816. var _this = this;
  14817. function noManifestFile() {
  14818. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14819. that.enableSceneOffline = false;
  14820. that.enableTexturesOffline = false;
  14821. that.callbackManifestChecked(false);
  14822. }
  14823. var that = this;
  14824. var manifestURL = this.currentSceneUrl + ".manifest";
  14825. var xhr = new XMLHttpRequest();
  14826. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14827. xhr.open("GET", manifestURLTimeStamped, true);
  14828. xhr.addEventListener("load", function () {
  14829. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14830. try {
  14831. var manifestFile = JSON.parse(xhr.response);
  14832. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14833. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14834. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14835. _this.manifestVersionFound = manifestFile.version;
  14836. }
  14837. if (_this.callbackManifestChecked) {
  14838. _this.callbackManifestChecked(true);
  14839. }
  14840. }
  14841. catch (ex) {
  14842. noManifestFile();
  14843. }
  14844. }
  14845. else {
  14846. noManifestFile();
  14847. }
  14848. }, false);
  14849. xhr.addEventListener("error", function (event) {
  14850. noManifestFile();
  14851. }, false);
  14852. try {
  14853. xhr.send();
  14854. }
  14855. catch (ex) {
  14856. BABYLON.Tools.Error("Error on XHR send request.");
  14857. that.callbackManifestChecked(false);
  14858. }
  14859. };
  14860. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14861. var _this = this;
  14862. function handleError() {
  14863. that.isSupported = false;
  14864. if (errorCallback)
  14865. errorCallback();
  14866. }
  14867. var that = this;
  14868. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14869. // Your browser doesn't support IndexedDB
  14870. this.isSupported = false;
  14871. if (errorCallback)
  14872. errorCallback();
  14873. }
  14874. else {
  14875. // If the DB hasn't been opened or created yet
  14876. if (!this.db) {
  14877. this.hasReachedQuota = false;
  14878. this.isSupported = true;
  14879. var request = this.idbFactory.open("babylonjs", 1);
  14880. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14881. request.onerror = function (event) {
  14882. handleError();
  14883. };
  14884. // executes when a version change transaction cannot complete due to other active transactions
  14885. request.onblocked = function (event) {
  14886. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14887. handleError();
  14888. };
  14889. // DB has been opened successfully
  14890. request.onsuccess = function (event) {
  14891. _this.db = request.result;
  14892. successCallback();
  14893. };
  14894. // Initialization of the DB. Creating Scenes & Textures stores
  14895. request.onupgradeneeded = function (event) {
  14896. _this.db = (event.target).result;
  14897. try {
  14898. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14899. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14900. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14901. }
  14902. catch (ex) {
  14903. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14904. handleError();
  14905. }
  14906. };
  14907. }
  14908. else {
  14909. if (successCallback)
  14910. successCallback();
  14911. }
  14912. }
  14913. };
  14914. Database.prototype.loadImageFromDB = function (url, image) {
  14915. var _this = this;
  14916. var completeURL = Database.ReturnFullUrlLocation(url);
  14917. var saveAndLoadImage = function () {
  14918. if (!_this.hasReachedQuota && _this.db !== null) {
  14919. // the texture is not yet in the DB, let's try to save it
  14920. _this._saveImageIntoDBAsync(completeURL, image);
  14921. }
  14922. else {
  14923. image.src = url;
  14924. }
  14925. };
  14926. if (!this.mustUpdateRessources) {
  14927. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14928. }
  14929. else {
  14930. saveAndLoadImage();
  14931. }
  14932. };
  14933. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14934. if (this.isSupported && this.db !== null) {
  14935. var texture;
  14936. var transaction = this.db.transaction(["textures"]);
  14937. transaction.onabort = function (event) {
  14938. image.src = url;
  14939. };
  14940. transaction.oncomplete = function (event) {
  14941. var blobTextureURL;
  14942. if (texture) {
  14943. var URL = window.URL || window.webkitURL;
  14944. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14945. image.onerror = function () {
  14946. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14947. image.src = url;
  14948. };
  14949. image.src = blobTextureURL;
  14950. }
  14951. else {
  14952. notInDBCallback();
  14953. }
  14954. };
  14955. var getRequest = transaction.objectStore("textures").get(url);
  14956. getRequest.onsuccess = function (event) {
  14957. texture = (event.target).result;
  14958. };
  14959. getRequest.onerror = function (event) {
  14960. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14961. image.src = url;
  14962. };
  14963. }
  14964. else {
  14965. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14966. image.src = url;
  14967. }
  14968. };
  14969. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14970. var _this = this;
  14971. if (this.isSupported) {
  14972. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14973. var generateBlobUrl = function () {
  14974. var blobTextureURL;
  14975. if (blob) {
  14976. var URL = window.URL || window.webkitURL;
  14977. try {
  14978. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14979. }
  14980. catch (ex) {
  14981. blobTextureURL = URL.createObjectURL(blob);
  14982. }
  14983. }
  14984. image.src = blobTextureURL;
  14985. };
  14986. if (Database.isUASupportingBlobStorage) {
  14987. var xhr = new XMLHttpRequest(), blob;
  14988. xhr.open("GET", url, true);
  14989. xhr.responseType = "blob";
  14990. xhr.addEventListener("load", function () {
  14991. if (xhr.status === 200) {
  14992. // Blob as response (XHR2)
  14993. blob = xhr.response;
  14994. var transaction = _this.db.transaction(["textures"], "readwrite");
  14995. // the transaction could abort because of a QuotaExceededError error
  14996. transaction.onabort = function (event) {
  14997. try {
  14998. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14999. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15000. this.hasReachedQuota = true;
  15001. }
  15002. }
  15003. catch (ex) {
  15004. }
  15005. generateBlobUrl();
  15006. };
  15007. transaction.oncomplete = function (event) {
  15008. generateBlobUrl();
  15009. };
  15010. var newTexture = { textureUrl: url, data: blob };
  15011. try {
  15012. // Put the blob into the dabase
  15013. var addRequest = transaction.objectStore("textures").put(newTexture);
  15014. addRequest.onsuccess = function (event) {
  15015. };
  15016. addRequest.onerror = function (event) {
  15017. generateBlobUrl();
  15018. };
  15019. }
  15020. catch (ex) {
  15021. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15022. if (ex.code === 25) {
  15023. Database.isUASupportingBlobStorage = false;
  15024. }
  15025. image.src = url;
  15026. }
  15027. }
  15028. else {
  15029. image.src = url;
  15030. }
  15031. }, false);
  15032. xhr.addEventListener("error", function (event) {
  15033. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15034. image.src = url;
  15035. }, false);
  15036. xhr.send();
  15037. }
  15038. else {
  15039. image.src = url;
  15040. }
  15041. }
  15042. else {
  15043. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15044. image.src = url;
  15045. }
  15046. };
  15047. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15048. var _this = this;
  15049. var updateVersion = function (event) {
  15050. // the version is not yet in the DB or we need to update it
  15051. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15052. };
  15053. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15054. };
  15055. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15056. var _this = this;
  15057. if (this.isSupported) {
  15058. var version;
  15059. try {
  15060. var transaction = this.db.transaction(["versions"]);
  15061. transaction.oncomplete = function (event) {
  15062. if (version) {
  15063. // If the version in the JSON file is > than the version in DB
  15064. if (_this.manifestVersionFound > version.data) {
  15065. _this.mustUpdateRessources = true;
  15066. updateInDBCallback();
  15067. }
  15068. else {
  15069. callback(version.data);
  15070. }
  15071. }
  15072. else {
  15073. _this.mustUpdateRessources = true;
  15074. updateInDBCallback();
  15075. }
  15076. };
  15077. transaction.onabort = function (event) {
  15078. callback(-1);
  15079. };
  15080. var getRequest = transaction.objectStore("versions").get(url);
  15081. getRequest.onsuccess = function (event) {
  15082. version = (event.target).result;
  15083. };
  15084. getRequest.onerror = function (event) {
  15085. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15086. callback(-1);
  15087. };
  15088. }
  15089. catch (ex) {
  15090. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15091. callback(-1);
  15092. }
  15093. }
  15094. else {
  15095. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15096. callback(-1);
  15097. }
  15098. };
  15099. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15100. var _this = this;
  15101. if (this.isSupported && !this.hasReachedQuota) {
  15102. try {
  15103. // Open a transaction to the database
  15104. var transaction = this.db.transaction(["versions"], "readwrite");
  15105. // the transaction could abort because of a QuotaExceededError error
  15106. transaction.onabort = function (event) {
  15107. try {
  15108. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15109. _this.hasReachedQuota = true;
  15110. }
  15111. }
  15112. catch (ex) {
  15113. }
  15114. callback(-1);
  15115. };
  15116. transaction.oncomplete = function (event) {
  15117. callback(_this.manifestVersionFound);
  15118. };
  15119. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15120. // Put the scene into the database
  15121. var addRequest = transaction.objectStore("versions").put(newVersion);
  15122. addRequest.onsuccess = function (event) {
  15123. };
  15124. addRequest.onerror = function (event) {
  15125. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15126. };
  15127. }
  15128. catch (ex) {
  15129. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15130. callback(-1);
  15131. }
  15132. }
  15133. else {
  15134. callback(-1);
  15135. }
  15136. };
  15137. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15138. var _this = this;
  15139. var completeUrl = Database.ReturnFullUrlLocation(url);
  15140. var saveAndLoadFile = function (event) {
  15141. // the scene is not yet in the DB, let's try to save it
  15142. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15143. };
  15144. this._checkVersionFromDB(completeUrl, function (version) {
  15145. if (version !== -1) {
  15146. if (!_this.mustUpdateRessources) {
  15147. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15148. }
  15149. else {
  15150. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15151. }
  15152. }
  15153. else {
  15154. errorCallback();
  15155. }
  15156. });
  15157. };
  15158. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15159. if (this.isSupported) {
  15160. var targetStore;
  15161. if (url.indexOf(".babylon") !== -1) {
  15162. targetStore = "scenes";
  15163. }
  15164. else {
  15165. targetStore = "textures";
  15166. }
  15167. var file;
  15168. var transaction = this.db.transaction([targetStore]);
  15169. transaction.oncomplete = function (event) {
  15170. if (file) {
  15171. callback(file.data);
  15172. }
  15173. else {
  15174. notInDBCallback();
  15175. }
  15176. };
  15177. transaction.onabort = function (event) {
  15178. notInDBCallback();
  15179. };
  15180. var getRequest = transaction.objectStore(targetStore).get(url);
  15181. getRequest.onsuccess = function (event) {
  15182. file = (event.target).result;
  15183. };
  15184. getRequest.onerror = function (event) {
  15185. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15186. notInDBCallback();
  15187. };
  15188. }
  15189. else {
  15190. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15191. callback();
  15192. }
  15193. };
  15194. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15195. var _this = this;
  15196. if (this.isSupported) {
  15197. var targetStore;
  15198. if (url.indexOf(".babylon") !== -1) {
  15199. targetStore = "scenes";
  15200. }
  15201. else {
  15202. targetStore = "textures";
  15203. }
  15204. // Create XHR
  15205. var xhr = new XMLHttpRequest(), fileData;
  15206. xhr.open("GET", url, true);
  15207. if (useArrayBuffer) {
  15208. xhr.responseType = "arraybuffer";
  15209. }
  15210. xhr.onprogress = progressCallback;
  15211. xhr.addEventListener("load", function () {
  15212. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15213. // Blob as response (XHR2)
  15214. //fileData = xhr.responseText;
  15215. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15216. if (!_this.hasReachedQuota) {
  15217. // Open a transaction to the database
  15218. var transaction = _this.db.transaction([targetStore], "readwrite");
  15219. // the transaction could abort because of a QuotaExceededError error
  15220. transaction.onabort = function (event) {
  15221. try {
  15222. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15223. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15224. this.hasReachedQuota = true;
  15225. }
  15226. }
  15227. catch (ex) {
  15228. }
  15229. callback(fileData);
  15230. };
  15231. transaction.oncomplete = function (event) {
  15232. callback(fileData);
  15233. };
  15234. var newFile;
  15235. if (targetStore === "scenes") {
  15236. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15237. }
  15238. else {
  15239. newFile = { textureUrl: url, data: fileData };
  15240. }
  15241. try {
  15242. // Put the scene into the database
  15243. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15244. addRequest.onsuccess = function (event) {
  15245. };
  15246. addRequest.onerror = function (event) {
  15247. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15248. };
  15249. }
  15250. catch (ex) {
  15251. callback(fileData);
  15252. }
  15253. }
  15254. else {
  15255. callback(fileData);
  15256. }
  15257. }
  15258. else {
  15259. callback();
  15260. }
  15261. }, false);
  15262. xhr.addEventListener("error", function (event) {
  15263. BABYLON.Tools.Error("error on XHR request.");
  15264. callback();
  15265. }, false);
  15266. xhr.send();
  15267. }
  15268. else {
  15269. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15270. callback();
  15271. }
  15272. };
  15273. Database.isUASupportingBlobStorage = true;
  15274. Database.parseURL = function (url) {
  15275. var a = document.createElement('a');
  15276. a.href = url;
  15277. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15278. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15279. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15280. return absLocation;
  15281. };
  15282. Database.ReturnFullUrlLocation = function (url) {
  15283. if (url.indexOf("http:/") === -1) {
  15284. return (BABYLON.Database.parseURL(window.location.href) + url);
  15285. }
  15286. else {
  15287. return url;
  15288. }
  15289. };
  15290. return Database;
  15291. })();
  15292. BABYLON.Database = Database;
  15293. })(BABYLON || (BABYLON = {}));
  15294. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15295. (function (BABYLON) {
  15296. var SpriteManager = (function () {
  15297. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15298. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15299. this.name = name;
  15300. this.cellSize = cellSize;
  15301. this.sprites = new Array();
  15302. this.renderingGroupId = 0;
  15303. this.fogEnabled = true;
  15304. this._vertexDeclaration = [3, 4, 4, 4];
  15305. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15306. this._capacity = capacity;
  15307. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15308. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15309. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15310. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15311. this._scene = scene;
  15312. this._scene.spriteManagers.push(this);
  15313. // VBO
  15314. this._vertexDeclaration = [3, 4, 4, 4];
  15315. this._vertexStrideSize = 15 * 4;
  15316. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15317. var indices = [];
  15318. var index = 0;
  15319. for (var count = 0; count < capacity; count++) {
  15320. indices.push(index);
  15321. indices.push(index + 1);
  15322. indices.push(index + 2);
  15323. indices.push(index);
  15324. indices.push(index + 2);
  15325. indices.push(index + 3);
  15326. index += 4;
  15327. }
  15328. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15329. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15330. // Effects
  15331. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15332. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15333. }
  15334. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15335. var arrayOffset = index * 15;
  15336. if (offsetX === 0)
  15337. offsetX = this._epsilon;
  15338. else if (offsetX === 1)
  15339. offsetX = 1 - this._epsilon;
  15340. if (offsetY === 0)
  15341. offsetY = this._epsilon;
  15342. else if (offsetY === 1)
  15343. offsetY = 1 - this._epsilon;
  15344. this._vertices[arrayOffset] = sprite.position.x;
  15345. this._vertices[arrayOffset + 1] = sprite.position.y;
  15346. this._vertices[arrayOffset + 2] = sprite.position.z;
  15347. this._vertices[arrayOffset + 3] = sprite.angle;
  15348. this._vertices[arrayOffset + 4] = sprite.size;
  15349. this._vertices[arrayOffset + 5] = offsetX;
  15350. this._vertices[arrayOffset + 6] = offsetY;
  15351. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  15352. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  15353. var offset = (sprite.cellIndex / rowSize) >> 0;
  15354. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  15355. this._vertices[arrayOffset + 10] = offset;
  15356. // Color
  15357. this._vertices[arrayOffset + 11] = sprite.color.r;
  15358. this._vertices[arrayOffset + 12] = sprite.color.g;
  15359. this._vertices[arrayOffset + 13] = sprite.color.b;
  15360. this._vertices[arrayOffset + 14] = sprite.color.a;
  15361. };
  15362. SpriteManager.prototype.render = function () {
  15363. // Check
  15364. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15365. return;
  15366. var engine = this._scene.getEngine();
  15367. var baseSize = this._spriteTexture.getBaseSize();
  15368. // Sprites
  15369. var deltaTime = engine.getDeltaTime();
  15370. var max = Math.min(this._capacity, this.sprites.length);
  15371. var rowSize = baseSize.width / this.cellSize;
  15372. var offset = 0;
  15373. for (var index = 0; index < max; index++) {
  15374. var sprite = this.sprites[index];
  15375. if (!sprite) {
  15376. continue;
  15377. }
  15378. sprite._animate(deltaTime);
  15379. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15380. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15381. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15382. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15383. }
  15384. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15385. // Render
  15386. var effect = this._effectBase;
  15387. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15388. effect = this._effectFog;
  15389. }
  15390. engine.enableEffect(effect);
  15391. var viewMatrix = this._scene.getViewMatrix();
  15392. effect.setTexture("diffuseSampler", this._spriteTexture);
  15393. effect.setMatrix("view", viewMatrix);
  15394. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15395. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15396. // Fog
  15397. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15398. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15399. effect.setColor3("vFogColor", this._scene.fogColor);
  15400. }
  15401. // VBOs
  15402. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15403. // Draw order
  15404. effect.setBool("alphaTest", true);
  15405. engine.setColorWrite(false);
  15406. engine.draw(true, 0, max * 6);
  15407. engine.setColorWrite(true);
  15408. effect.setBool("alphaTest", false);
  15409. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15410. engine.draw(true, 0, max * 6);
  15411. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15412. };
  15413. SpriteManager.prototype.dispose = function () {
  15414. if (this._vertexBuffer) {
  15415. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15416. this._vertexBuffer = null;
  15417. }
  15418. if (this._indexBuffer) {
  15419. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15420. this._indexBuffer = null;
  15421. }
  15422. if (this._spriteTexture) {
  15423. this._spriteTexture.dispose();
  15424. this._spriteTexture = null;
  15425. }
  15426. // Remove from scene
  15427. var index = this._scene.spriteManagers.indexOf(this);
  15428. this._scene.spriteManagers.splice(index, 1);
  15429. // Callback
  15430. if (this.onDispose) {
  15431. this.onDispose();
  15432. }
  15433. };
  15434. return SpriteManager;
  15435. })();
  15436. BABYLON.SpriteManager = SpriteManager;
  15437. })(BABYLON || (BABYLON = {}));
  15438. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15439. (function (BABYLON) {
  15440. var Sprite = (function () {
  15441. function Sprite(name, manager) {
  15442. this.name = name;
  15443. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15444. this.size = 1.0;
  15445. this.angle = 0;
  15446. this.cellIndex = 0;
  15447. this.invertU = 0;
  15448. this.invertV = 0;
  15449. this.animations = new Array();
  15450. this._animationStarted = false;
  15451. this._loopAnimation = false;
  15452. this._fromIndex = 0;
  15453. this._toIndex = 0;
  15454. this._delay = 0;
  15455. this._direction = 1;
  15456. this._frameCount = 0;
  15457. this._time = 0;
  15458. this._manager = manager;
  15459. this._manager.sprites.push(this);
  15460. this.position = BABYLON.Vector3.Zero();
  15461. }
  15462. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15463. this._fromIndex = from;
  15464. this._toIndex = to;
  15465. this._loopAnimation = loop;
  15466. this._delay = delay;
  15467. this._animationStarted = true;
  15468. this._direction = from < to ? 1 : -1;
  15469. this.cellIndex = from;
  15470. this._time = 0;
  15471. };
  15472. Sprite.prototype.stopAnimation = function () {
  15473. this._animationStarted = false;
  15474. };
  15475. Sprite.prototype._animate = function (deltaTime) {
  15476. if (!this._animationStarted)
  15477. return;
  15478. this._time += deltaTime;
  15479. if (this._time > this._delay) {
  15480. this._time = this._time % this._delay;
  15481. this.cellIndex += this._direction;
  15482. if (this.cellIndex == this._toIndex) {
  15483. if (this._loopAnimation) {
  15484. this.cellIndex = this._fromIndex;
  15485. }
  15486. else {
  15487. this._animationStarted = false;
  15488. if (this.disposeWhenFinishedAnimating) {
  15489. this.dispose();
  15490. }
  15491. }
  15492. }
  15493. }
  15494. };
  15495. Sprite.prototype.dispose = function () {
  15496. for (var i = 0; i < this._manager.sprites.length; i++) {
  15497. if (this._manager.sprites[i] == this) {
  15498. this._manager.sprites.splice(i, 1);
  15499. }
  15500. }
  15501. };
  15502. return Sprite;
  15503. })();
  15504. BABYLON.Sprite = Sprite;
  15505. })(BABYLON || (BABYLON = {}));
  15506. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15507. (function (BABYLON) {
  15508. var Layer = (function () {
  15509. function Layer(name, imgUrl, scene, isBackground, color) {
  15510. this.name = name;
  15511. this._vertexDeclaration = [2];
  15512. this._vertexStrideSize = 2 * 4;
  15513. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15514. this.isBackground = isBackground === undefined ? true : isBackground;
  15515. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15516. this._scene = scene;
  15517. this._scene.layers.push(this);
  15518. // VBO
  15519. var vertices = [];
  15520. vertices.push(1, 1);
  15521. vertices.push(-1, 1);
  15522. vertices.push(-1, -1);
  15523. vertices.push(1, -1);
  15524. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15525. // Indices
  15526. var indices = [];
  15527. indices.push(0);
  15528. indices.push(1);
  15529. indices.push(2);
  15530. indices.push(0);
  15531. indices.push(2);
  15532. indices.push(3);
  15533. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15534. // Effects
  15535. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15536. }
  15537. Layer.prototype.render = function () {
  15538. // Check
  15539. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15540. return;
  15541. var engine = this._scene.getEngine();
  15542. // Render
  15543. engine.enableEffect(this._effect);
  15544. engine.setState(false);
  15545. // Texture
  15546. this._effect.setTexture("textureSampler", this.texture);
  15547. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15548. // Color
  15549. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15550. // VBOs
  15551. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15552. // Draw order
  15553. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15554. engine.draw(true, 0, 6);
  15555. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15556. };
  15557. Layer.prototype.dispose = function () {
  15558. if (this._vertexBuffer) {
  15559. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15560. this._vertexBuffer = null;
  15561. }
  15562. if (this._indexBuffer) {
  15563. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15564. this._indexBuffer = null;
  15565. }
  15566. if (this.texture) {
  15567. this.texture.dispose();
  15568. this.texture = null;
  15569. }
  15570. // Remove from scene
  15571. var index = this._scene.layers.indexOf(this);
  15572. this._scene.layers.splice(index, 1);
  15573. // Callback
  15574. if (this.onDispose) {
  15575. this.onDispose();
  15576. }
  15577. };
  15578. return Layer;
  15579. })();
  15580. BABYLON.Layer = Layer;
  15581. })(BABYLON || (BABYLON = {}));
  15582. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15583. (function (BABYLON) {
  15584. var Particle = (function () {
  15585. function Particle() {
  15586. this.position = BABYLON.Vector3.Zero();
  15587. this.direction = BABYLON.Vector3.Zero();
  15588. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15589. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15590. this.lifeTime = 1.0;
  15591. this.age = 0;
  15592. this.size = 0;
  15593. this.angle = 0;
  15594. this.angularSpeed = 0;
  15595. }
  15596. Particle.prototype.copyTo = function (other) {
  15597. other.position.copyFrom(this.position);
  15598. other.direction.copyFrom(this.direction);
  15599. other.color.copyFrom(this.color);
  15600. other.colorStep.copyFrom(this.colorStep);
  15601. other.lifeTime = this.lifeTime;
  15602. other.age = this.age;
  15603. other.size = this.size;
  15604. other.angle = this.angle;
  15605. other.angularSpeed = this.angularSpeed;
  15606. };
  15607. return Particle;
  15608. })();
  15609. BABYLON.Particle = Particle;
  15610. })(BABYLON || (BABYLON = {}));
  15611. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15612. (function (BABYLON) {
  15613. var randomNumber = function (min, max) {
  15614. if (min === max) {
  15615. return (min);
  15616. }
  15617. var random = Math.random();
  15618. return ((random * (max - min)) + min);
  15619. };
  15620. var ParticleSystem = (function () {
  15621. function ParticleSystem(name, capacity, scene, customEffect) {
  15622. var _this = this;
  15623. this.name = name;
  15624. this.renderingGroupId = 0;
  15625. this.emitter = null;
  15626. this.emitRate = 10;
  15627. this.manualEmitCount = -1;
  15628. this.updateSpeed = 0.01;
  15629. this.targetStopDuration = 0;
  15630. this.disposeOnStop = false;
  15631. this.minEmitPower = 1;
  15632. this.maxEmitPower = 1;
  15633. this.minLifeTime = 1;
  15634. this.maxLifeTime = 1;
  15635. this.minSize = 1;
  15636. this.maxSize = 1;
  15637. this.minAngularSpeed = 0;
  15638. this.maxAngularSpeed = 0;
  15639. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15640. this.forceDepthWrite = false;
  15641. this.gravity = BABYLON.Vector3.Zero();
  15642. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15643. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15644. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15645. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15646. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15647. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15648. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15649. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15650. this.particles = new Array();
  15651. this._vertexDeclaration = [3, 4, 4];
  15652. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15653. this._stockParticles = new Array();
  15654. this._newPartsExcess = 0;
  15655. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15656. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15657. this._scaledDirection = BABYLON.Vector3.Zero();
  15658. this._scaledGravity = BABYLON.Vector3.Zero();
  15659. this._currentRenderId = -1;
  15660. this._started = false;
  15661. this._stopped = false;
  15662. this._actualFrame = 0;
  15663. this.id = name;
  15664. this._capacity = capacity;
  15665. this._scene = scene;
  15666. this._customEffect = customEffect;
  15667. scene.particleSystems.push(this);
  15668. // VBO
  15669. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15670. var indices = [];
  15671. var index = 0;
  15672. for (var count = 0; count < capacity; count++) {
  15673. indices.push(index);
  15674. indices.push(index + 1);
  15675. indices.push(index + 2);
  15676. indices.push(index);
  15677. indices.push(index + 2);
  15678. indices.push(index + 3);
  15679. index += 4;
  15680. }
  15681. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15682. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15683. // Default behaviors
  15684. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15685. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15686. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15687. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15688. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15689. };
  15690. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15691. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15692. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15693. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15694. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15695. };
  15696. this.updateFunction = function (particles) {
  15697. for (var index = 0; index < particles.length; index++) {
  15698. var particle = particles[index];
  15699. particle.age += _this._scaledUpdateSpeed;
  15700. if (particle.age >= particle.lifeTime) {
  15701. _this.recycleParticle(particle);
  15702. index--;
  15703. continue;
  15704. }
  15705. else {
  15706. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15707. particle.color.addInPlace(_this._scaledColorStep);
  15708. if (particle.color.a < 0)
  15709. particle.color.a = 0;
  15710. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15711. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15712. particle.position.addInPlace(_this._scaledDirection);
  15713. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15714. particle.direction.addInPlace(_this._scaledGravity);
  15715. }
  15716. }
  15717. };
  15718. }
  15719. ParticleSystem.prototype.recycleParticle = function (particle) {
  15720. var lastParticle = this.particles.pop();
  15721. if (lastParticle !== particle) {
  15722. lastParticle.copyTo(particle);
  15723. this._stockParticles.push(lastParticle);
  15724. }
  15725. };
  15726. ParticleSystem.prototype.getCapacity = function () {
  15727. return this._capacity;
  15728. };
  15729. ParticleSystem.prototype.isAlive = function () {
  15730. return this._alive;
  15731. };
  15732. ParticleSystem.prototype.isStarted = function () {
  15733. return this._started;
  15734. };
  15735. ParticleSystem.prototype.start = function () {
  15736. this._started = true;
  15737. this._stopped = false;
  15738. this._actualFrame = 0;
  15739. };
  15740. ParticleSystem.prototype.stop = function () {
  15741. this._stopped = true;
  15742. };
  15743. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15744. var offset = index * 11;
  15745. this._vertices[offset] = particle.position.x;
  15746. this._vertices[offset + 1] = particle.position.y;
  15747. this._vertices[offset + 2] = particle.position.z;
  15748. this._vertices[offset + 3] = particle.color.r;
  15749. this._vertices[offset + 4] = particle.color.g;
  15750. this._vertices[offset + 5] = particle.color.b;
  15751. this._vertices[offset + 6] = particle.color.a;
  15752. this._vertices[offset + 7] = particle.angle;
  15753. this._vertices[offset + 8] = particle.size;
  15754. this._vertices[offset + 9] = offsetX;
  15755. this._vertices[offset + 10] = offsetY;
  15756. };
  15757. ParticleSystem.prototype._update = function (newParticles) {
  15758. // Update current
  15759. this._alive = this.particles.length > 0;
  15760. this.updateFunction(this.particles);
  15761. // Add new ones
  15762. var worldMatrix;
  15763. if (this.emitter.position) {
  15764. worldMatrix = this.emitter.getWorldMatrix();
  15765. }
  15766. else {
  15767. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15768. }
  15769. for (var index = 0; index < newParticles; index++) {
  15770. if (this.particles.length === this._capacity) {
  15771. break;
  15772. }
  15773. if (this._stockParticles.length !== 0) {
  15774. var particle = this._stockParticles.pop();
  15775. particle.age = 0;
  15776. }
  15777. else {
  15778. particle = new BABYLON.Particle();
  15779. }
  15780. this.particles.push(particle);
  15781. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15782. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15783. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15784. particle.size = randomNumber(this.minSize, this.maxSize);
  15785. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15786. this.startPositionFunction(worldMatrix, particle.position);
  15787. var step = randomNumber(0, 1.0);
  15788. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15789. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15790. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15791. }
  15792. };
  15793. ParticleSystem.prototype._getEffect = function () {
  15794. if (this._customEffect) {
  15795. return this._customEffect;
  15796. }
  15797. ;
  15798. var defines = [];
  15799. if (this._scene.clipPlane) {
  15800. defines.push("#define CLIPPLANE");
  15801. }
  15802. // Effect
  15803. var join = defines.join("\n");
  15804. if (this._cachedDefines !== join) {
  15805. this._cachedDefines = join;
  15806. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15807. }
  15808. return this._effect;
  15809. };
  15810. ParticleSystem.prototype.animate = function () {
  15811. if (!this._started)
  15812. return;
  15813. var effect = this._getEffect();
  15814. // Check
  15815. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15816. return;
  15817. if (this._currentRenderId === this._scene.getRenderId()) {
  15818. return;
  15819. }
  15820. this._currentRenderId = this._scene.getRenderId();
  15821. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15822. // determine the number of particles we need to create
  15823. var emitCout;
  15824. if (this.manualEmitCount > -1) {
  15825. emitCout = this.manualEmitCount;
  15826. this.manualEmitCount = 0;
  15827. }
  15828. else {
  15829. emitCout = this.emitRate;
  15830. }
  15831. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15832. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15833. if (this._newPartsExcess > 1.0) {
  15834. newParticles += this._newPartsExcess >> 0;
  15835. this._newPartsExcess -= this._newPartsExcess >> 0;
  15836. }
  15837. this._alive = false;
  15838. if (!this._stopped) {
  15839. this._actualFrame += this._scaledUpdateSpeed;
  15840. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15841. this.stop();
  15842. }
  15843. else {
  15844. newParticles = 0;
  15845. }
  15846. this._update(newParticles);
  15847. // Stopped?
  15848. if (this._stopped) {
  15849. if (!this._alive) {
  15850. this._started = false;
  15851. if (this.disposeOnStop) {
  15852. this._scene._toBeDisposed.push(this);
  15853. }
  15854. }
  15855. }
  15856. // Update VBO
  15857. var offset = 0;
  15858. for (var index = 0; index < this.particles.length; index++) {
  15859. var particle = this.particles[index];
  15860. this._appendParticleVertex(offset++, particle, 0, 0);
  15861. this._appendParticleVertex(offset++, particle, 1, 0);
  15862. this._appendParticleVertex(offset++, particle, 1, 1);
  15863. this._appendParticleVertex(offset++, particle, 0, 1);
  15864. }
  15865. var engine = this._scene.getEngine();
  15866. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15867. };
  15868. ParticleSystem.prototype.render = function () {
  15869. var effect = this._getEffect();
  15870. // Check
  15871. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15872. return 0;
  15873. var engine = this._scene.getEngine();
  15874. // Render
  15875. engine.enableEffect(effect);
  15876. engine.setState(false);
  15877. var viewMatrix = this._scene.getViewMatrix();
  15878. effect.setTexture("diffuseSampler", this.particleTexture);
  15879. effect.setMatrix("view", viewMatrix);
  15880. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15881. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15882. if (this._scene.clipPlane) {
  15883. var clipPlane = this._scene.clipPlane;
  15884. var invView = viewMatrix.clone();
  15885. invView.invert();
  15886. effect.setMatrix("invView", invView);
  15887. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15888. }
  15889. // VBOs
  15890. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15891. // Draw order
  15892. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15893. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15894. }
  15895. else {
  15896. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15897. }
  15898. if (this.forceDepthWrite) {
  15899. engine.setDepthWrite(true);
  15900. }
  15901. engine.draw(true, 0, this.particles.length * 6);
  15902. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15903. return this.particles.length;
  15904. };
  15905. ParticleSystem.prototype.dispose = function () {
  15906. if (this._vertexBuffer) {
  15907. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15908. this._vertexBuffer = null;
  15909. }
  15910. if (this._indexBuffer) {
  15911. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15912. this._indexBuffer = null;
  15913. }
  15914. if (this.particleTexture) {
  15915. this.particleTexture.dispose();
  15916. this.particleTexture = null;
  15917. }
  15918. // Remove from scene
  15919. var index = this._scene.particleSystems.indexOf(this);
  15920. this._scene.particleSystems.splice(index, 1);
  15921. // Callback
  15922. if (this.onDispose) {
  15923. this.onDispose();
  15924. }
  15925. };
  15926. // Clone
  15927. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15928. var result = new ParticleSystem(name, this._capacity, this._scene);
  15929. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15930. if (newEmitter === undefined) {
  15931. newEmitter = this.emitter;
  15932. }
  15933. result.emitter = newEmitter;
  15934. if (this.particleTexture) {
  15935. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15936. }
  15937. result.start();
  15938. return result;
  15939. };
  15940. // Statics
  15941. ParticleSystem.BLENDMODE_ONEONE = 0;
  15942. ParticleSystem.BLENDMODE_STANDARD = 1;
  15943. return ParticleSystem;
  15944. })();
  15945. BABYLON.ParticleSystem = ParticleSystem;
  15946. })(BABYLON || (BABYLON = {}));
  15947. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15948. (function (BABYLON) {
  15949. var Animation = (function () {
  15950. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15951. this.name = name;
  15952. this.targetProperty = targetProperty;
  15953. this.framePerSecond = framePerSecond;
  15954. this.dataType = dataType;
  15955. this.loopMode = loopMode;
  15956. this._offsetsCache = {};
  15957. this._highLimitsCache = {};
  15958. this._stopped = false;
  15959. this.targetPropertyPath = targetProperty.split(".");
  15960. this.dataType = dataType;
  15961. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15962. }
  15963. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15964. var dataType = undefined;
  15965. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15966. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15967. }
  15968. else if (from instanceof BABYLON.Quaternion) {
  15969. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15970. }
  15971. else if (from instanceof BABYLON.Vector3) {
  15972. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15973. }
  15974. else if (from instanceof BABYLON.Vector2) {
  15975. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15976. }
  15977. else if (from instanceof BABYLON.Color3) {
  15978. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15979. }
  15980. if (dataType == undefined) {
  15981. return null;
  15982. }
  15983. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15984. var keys = [];
  15985. keys.push({ frame: 0, value: from });
  15986. keys.push({ frame: totalFrame, value: to });
  15987. animation.setKeys(keys);
  15988. mesh.animations.push(animation);
  15989. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15990. };
  15991. // Methods
  15992. Animation.prototype.isStopped = function () {
  15993. return this._stopped;
  15994. };
  15995. Animation.prototype.getKeys = function () {
  15996. return this._keys;
  15997. };
  15998. Animation.prototype.getEasingFunction = function () {
  15999. return this._easingFunction;
  16000. };
  16001. Animation.prototype.setEasingFunction = function (easingFunction) {
  16002. this._easingFunction = easingFunction;
  16003. };
  16004. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16005. return startValue + (endValue - startValue) * gradient;
  16006. };
  16007. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16008. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16009. };
  16010. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16011. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16012. };
  16013. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16014. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16015. };
  16016. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16017. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16018. };
  16019. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16020. var startScale = new BABYLON.Vector3(0, 0, 0);
  16021. var startRotation = new BABYLON.Quaternion();
  16022. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16023. startValue.decompose(startScale, startRotation, startTranslation);
  16024. var endScale = new BABYLON.Vector3(0, 0, 0);
  16025. var endRotation = new BABYLON.Quaternion();
  16026. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16027. endValue.decompose(endScale, endRotation, endTranslation);
  16028. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16029. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16030. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16031. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16032. return result;
  16033. };
  16034. Animation.prototype.clone = function () {
  16035. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16036. clone.setKeys(this._keys);
  16037. return clone;
  16038. };
  16039. Animation.prototype.setKeys = function (values) {
  16040. this._keys = values.slice(0);
  16041. this._offsetsCache = {};
  16042. this._highLimitsCache = {};
  16043. };
  16044. Animation.prototype._getKeyValue = function (value) {
  16045. if (typeof value === "function") {
  16046. return value();
  16047. }
  16048. return value;
  16049. };
  16050. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16051. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16052. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16053. }
  16054. this.currentFrame = currentFrame;
  16055. // Try to get a hash to find the right key
  16056. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  16057. if (this._keys[startKey].frame >= currentFrame) {
  16058. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16059. startKey--;
  16060. }
  16061. }
  16062. for (var key = startKey; key < this._keys.length; key++) {
  16063. if (this._keys[key + 1].frame >= currentFrame) {
  16064. var startValue = this._getKeyValue(this._keys[key].value);
  16065. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16066. // gradient : percent of currentFrame between the frame inf and the frame sup
  16067. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16068. // check for easingFunction and correction of gradient
  16069. if (this._easingFunction != null) {
  16070. gradient = this._easingFunction.ease(gradient);
  16071. }
  16072. switch (this.dataType) {
  16073. case Animation.ANIMATIONTYPE_FLOAT:
  16074. switch (loopMode) {
  16075. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16076. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16077. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16078. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16079. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16080. }
  16081. break;
  16082. case Animation.ANIMATIONTYPE_QUATERNION:
  16083. var quaternion = null;
  16084. switch (loopMode) {
  16085. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16086. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16087. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16088. break;
  16089. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16090. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16091. break;
  16092. }
  16093. return quaternion;
  16094. case Animation.ANIMATIONTYPE_VECTOR3:
  16095. switch (loopMode) {
  16096. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16097. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16098. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16099. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16100. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16101. }
  16102. case Animation.ANIMATIONTYPE_VECTOR2:
  16103. switch (loopMode) {
  16104. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16105. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16106. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16107. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16108. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16109. }
  16110. case Animation.ANIMATIONTYPE_COLOR3:
  16111. switch (loopMode) {
  16112. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16113. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16114. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16115. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16116. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16117. }
  16118. case Animation.ANIMATIONTYPE_MATRIX:
  16119. switch (loopMode) {
  16120. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16121. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16122. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16123. return startValue;
  16124. }
  16125. default:
  16126. break;
  16127. }
  16128. break;
  16129. }
  16130. }
  16131. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16132. };
  16133. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16134. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16135. this._stopped = true;
  16136. return false;
  16137. }
  16138. var returnValue = true;
  16139. // Adding a start key at frame 0 if missing
  16140. if (this._keys[0].frame !== 0) {
  16141. var newKey = { frame: 0, value: this._keys[0].value };
  16142. this._keys.splice(0, 0, newKey);
  16143. }
  16144. // Check limits
  16145. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16146. from = this._keys[0].frame;
  16147. }
  16148. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16149. to = this._keys[this._keys.length - 1].frame;
  16150. }
  16151. // Compute ratio
  16152. var range = to - from;
  16153. var offsetValue;
  16154. // ratio represents the frame delta between from and to
  16155. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16156. var highLimitValue = 0;
  16157. if (ratio > range && !loop) {
  16158. returnValue = false;
  16159. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16160. }
  16161. else {
  16162. // Get max value if required
  16163. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16164. var keyOffset = to.toString() + from.toString();
  16165. if (!this._offsetsCache[keyOffset]) {
  16166. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16167. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16168. switch (this.dataType) {
  16169. case Animation.ANIMATIONTYPE_FLOAT:
  16170. this._offsetsCache[keyOffset] = toValue - fromValue;
  16171. break;
  16172. case Animation.ANIMATIONTYPE_QUATERNION:
  16173. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16174. break;
  16175. case Animation.ANIMATIONTYPE_VECTOR3:
  16176. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16177. case Animation.ANIMATIONTYPE_VECTOR2:
  16178. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16179. case Animation.ANIMATIONTYPE_COLOR3:
  16180. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16181. default:
  16182. break;
  16183. }
  16184. this._highLimitsCache[keyOffset] = toValue;
  16185. }
  16186. highLimitValue = this._highLimitsCache[keyOffset];
  16187. offsetValue = this._offsetsCache[keyOffset];
  16188. }
  16189. }
  16190. if (offsetValue === undefined) {
  16191. switch (this.dataType) {
  16192. case Animation.ANIMATIONTYPE_FLOAT:
  16193. offsetValue = 0;
  16194. break;
  16195. case Animation.ANIMATIONTYPE_QUATERNION:
  16196. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16197. break;
  16198. case Animation.ANIMATIONTYPE_VECTOR3:
  16199. offsetValue = BABYLON.Vector3.Zero();
  16200. break;
  16201. case Animation.ANIMATIONTYPE_VECTOR2:
  16202. offsetValue = BABYLON.Vector2.Zero();
  16203. break;
  16204. case Animation.ANIMATIONTYPE_COLOR3:
  16205. offsetValue = BABYLON.Color3.Black();
  16206. }
  16207. }
  16208. // Compute value
  16209. var repeatCount = (ratio / range) >> 0;
  16210. var currentFrame = returnValue ? from + ratio % range : to;
  16211. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16212. // Set value
  16213. if (this.targetPropertyPath.length > 1) {
  16214. var property = this._target[this.targetPropertyPath[0]];
  16215. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16216. property = property[this.targetPropertyPath[index]];
  16217. }
  16218. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16219. }
  16220. else {
  16221. this._target[this.targetPropertyPath[0]] = currentValue;
  16222. }
  16223. if (this._target.markAsDirty) {
  16224. this._target.markAsDirty(this.targetProperty);
  16225. }
  16226. if (!returnValue) {
  16227. this._stopped = true;
  16228. }
  16229. return returnValue;
  16230. };
  16231. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16232. get: function () {
  16233. return Animation._ANIMATIONTYPE_FLOAT;
  16234. },
  16235. enumerable: true,
  16236. configurable: true
  16237. });
  16238. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16239. get: function () {
  16240. return Animation._ANIMATIONTYPE_VECTOR3;
  16241. },
  16242. enumerable: true,
  16243. configurable: true
  16244. });
  16245. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16246. get: function () {
  16247. return Animation._ANIMATIONTYPE_VECTOR2;
  16248. },
  16249. enumerable: true,
  16250. configurable: true
  16251. });
  16252. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16253. get: function () {
  16254. return Animation._ANIMATIONTYPE_QUATERNION;
  16255. },
  16256. enumerable: true,
  16257. configurable: true
  16258. });
  16259. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16260. get: function () {
  16261. return Animation._ANIMATIONTYPE_MATRIX;
  16262. },
  16263. enumerable: true,
  16264. configurable: true
  16265. });
  16266. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16267. get: function () {
  16268. return Animation._ANIMATIONTYPE_COLOR3;
  16269. },
  16270. enumerable: true,
  16271. configurable: true
  16272. });
  16273. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16274. get: function () {
  16275. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16276. },
  16277. enumerable: true,
  16278. configurable: true
  16279. });
  16280. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16281. get: function () {
  16282. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16283. },
  16284. enumerable: true,
  16285. configurable: true
  16286. });
  16287. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16288. get: function () {
  16289. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16290. },
  16291. enumerable: true,
  16292. configurable: true
  16293. });
  16294. // Statics
  16295. Animation._ANIMATIONTYPE_FLOAT = 0;
  16296. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16297. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16298. Animation._ANIMATIONTYPE_MATRIX = 3;
  16299. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16300. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16301. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16302. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16303. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16304. return Animation;
  16305. })();
  16306. BABYLON.Animation = Animation;
  16307. })(BABYLON || (BABYLON = {}));
  16308. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16309. (function (BABYLON) {
  16310. var Animatable = (function () {
  16311. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16312. if (fromFrame === void 0) { fromFrame = 0; }
  16313. if (toFrame === void 0) { toFrame = 100; }
  16314. if (loopAnimation === void 0) { loopAnimation = false; }
  16315. if (speedRatio === void 0) { speedRatio = 1.0; }
  16316. this.target = target;
  16317. this.fromFrame = fromFrame;
  16318. this.toFrame = toFrame;
  16319. this.loopAnimation = loopAnimation;
  16320. this.speedRatio = speedRatio;
  16321. this.onAnimationEnd = onAnimationEnd;
  16322. this._animations = new Array();
  16323. this._paused = false;
  16324. this.animationStarted = false;
  16325. if (animations) {
  16326. this.appendAnimations(target, animations);
  16327. }
  16328. this._scene = scene;
  16329. scene._activeAnimatables.push(this);
  16330. }
  16331. // Methods
  16332. Animatable.prototype.appendAnimations = function (target, animations) {
  16333. for (var index = 0; index < animations.length; index++) {
  16334. var animation = animations[index];
  16335. animation._target = target;
  16336. this._animations.push(animation);
  16337. }
  16338. };
  16339. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16340. var animations = this._animations;
  16341. for (var index = 0; index < animations.length; index++) {
  16342. if (animations[index].targetProperty === property) {
  16343. return animations[index];
  16344. }
  16345. }
  16346. return null;
  16347. };
  16348. Animatable.prototype.pause = function () {
  16349. if (this._paused) {
  16350. return;
  16351. }
  16352. this._paused = true;
  16353. };
  16354. Animatable.prototype.restart = function () {
  16355. this._paused = false;
  16356. };
  16357. Animatable.prototype.stop = function () {
  16358. var index = this._scene._activeAnimatables.indexOf(this);
  16359. if (index > -1) {
  16360. this._scene._activeAnimatables.splice(index, 1);
  16361. }
  16362. if (this.onAnimationEnd) {
  16363. this.onAnimationEnd();
  16364. }
  16365. };
  16366. Animatable.prototype._animate = function (delay) {
  16367. if (this._paused) {
  16368. if (!this._pausedDelay) {
  16369. this._pausedDelay = delay;
  16370. }
  16371. return true;
  16372. }
  16373. if (!this._localDelayOffset) {
  16374. this._localDelayOffset = delay;
  16375. }
  16376. else if (this._pausedDelay) {
  16377. this._localDelayOffset += delay - this._pausedDelay;
  16378. this._pausedDelay = null;
  16379. }
  16380. // Animating
  16381. var running = false;
  16382. var animations = this._animations;
  16383. for (var index = 0; index < animations.length; index++) {
  16384. var animation = animations[index];
  16385. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16386. running = running || isRunning;
  16387. }
  16388. if (!running && this.onAnimationEnd) {
  16389. this.onAnimationEnd();
  16390. }
  16391. return running;
  16392. };
  16393. return Animatable;
  16394. })();
  16395. BABYLON.Animatable = Animatable;
  16396. })(BABYLON || (BABYLON = {}));
  16397. //# sourceMappingURL=babylon.animatable.js.map
  16398. var BABYLON;
  16399. (function (BABYLON) {
  16400. var EasingFunction = (function () {
  16401. function EasingFunction() {
  16402. // Properties
  16403. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16404. }
  16405. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16406. get: function () {
  16407. return EasingFunction._EASINGMODE_EASEIN;
  16408. },
  16409. enumerable: true,
  16410. configurable: true
  16411. });
  16412. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16413. get: function () {
  16414. return EasingFunction._EASINGMODE_EASEOUT;
  16415. },
  16416. enumerable: true,
  16417. configurable: true
  16418. });
  16419. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16420. get: function () {
  16421. return EasingFunction._EASINGMODE_EASEINOUT;
  16422. },
  16423. enumerable: true,
  16424. configurable: true
  16425. });
  16426. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16427. var n = Math.min(Math.max(easingMode, 0), 2);
  16428. this._easingMode = n;
  16429. };
  16430. EasingFunction.prototype.getEasingMode = function () {
  16431. return this._easingMode;
  16432. };
  16433. EasingFunction.prototype.easeInCore = function (gradient) {
  16434. throw new Error('You must implement this method');
  16435. };
  16436. EasingFunction.prototype.ease = function (gradient) {
  16437. switch (this._easingMode) {
  16438. case EasingFunction.EASINGMODE_EASEIN:
  16439. return this.easeInCore(gradient);
  16440. case EasingFunction.EASINGMODE_EASEOUT:
  16441. return (1 - this.easeInCore(1 - gradient));
  16442. }
  16443. if (gradient >= 0.5) {
  16444. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16445. }
  16446. return (this.easeInCore(gradient * 2) * 0.5);
  16447. };
  16448. //Statics
  16449. EasingFunction._EASINGMODE_EASEIN = 0;
  16450. EasingFunction._EASINGMODE_EASEOUT = 1;
  16451. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16452. return EasingFunction;
  16453. })();
  16454. BABYLON.EasingFunction = EasingFunction;
  16455. var CircleEase = (function (_super) {
  16456. __extends(CircleEase, _super);
  16457. function CircleEase() {
  16458. _super.apply(this, arguments);
  16459. }
  16460. CircleEase.prototype.easeInCore = function (gradient) {
  16461. gradient = Math.max(0, Math.min(1, gradient));
  16462. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16463. };
  16464. return CircleEase;
  16465. })(EasingFunction);
  16466. BABYLON.CircleEase = CircleEase;
  16467. var BackEase = (function (_super) {
  16468. __extends(BackEase, _super);
  16469. function BackEase(amplitude) {
  16470. if (amplitude === void 0) { amplitude = 1; }
  16471. _super.call(this);
  16472. this.amplitude = amplitude;
  16473. }
  16474. BackEase.prototype.easeInCore = function (gradient) {
  16475. var num = Math.max(0, this.amplitude);
  16476. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16477. };
  16478. return BackEase;
  16479. })(EasingFunction);
  16480. BABYLON.BackEase = BackEase;
  16481. var BounceEase = (function (_super) {
  16482. __extends(BounceEase, _super);
  16483. function BounceEase(bounces, bounciness) {
  16484. if (bounces === void 0) { bounces = 3; }
  16485. if (bounciness === void 0) { bounciness = 2; }
  16486. _super.call(this);
  16487. this.bounces = bounces;
  16488. this.bounciness = bounciness;
  16489. }
  16490. BounceEase.prototype.easeInCore = function (gradient) {
  16491. var y = Math.max(0.0, this.bounces);
  16492. var bounciness = this.bounciness;
  16493. if (bounciness <= 1.0) {
  16494. bounciness = 1.001;
  16495. }
  16496. var num9 = Math.pow(bounciness, y);
  16497. var num5 = 1.0 - bounciness;
  16498. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16499. var num15 = gradient * num4;
  16500. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16501. var num3 = Math.floor(num65);
  16502. var num13 = num3 + 1.0;
  16503. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16504. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16505. var num7 = (num8 + num12) * 0.5;
  16506. var num6 = gradient - num7;
  16507. var num2 = num7 - num8;
  16508. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16509. };
  16510. return BounceEase;
  16511. })(EasingFunction);
  16512. BABYLON.BounceEase = BounceEase;
  16513. var CubicEase = (function (_super) {
  16514. __extends(CubicEase, _super);
  16515. function CubicEase() {
  16516. _super.apply(this, arguments);
  16517. }
  16518. CubicEase.prototype.easeInCore = function (gradient) {
  16519. return (gradient * gradient * gradient);
  16520. };
  16521. return CubicEase;
  16522. })(EasingFunction);
  16523. BABYLON.CubicEase = CubicEase;
  16524. var ElasticEase = (function (_super) {
  16525. __extends(ElasticEase, _super);
  16526. function ElasticEase(oscillations, springiness) {
  16527. if (oscillations === void 0) { oscillations = 3; }
  16528. if (springiness === void 0) { springiness = 3; }
  16529. _super.call(this);
  16530. this.oscillations = oscillations;
  16531. this.springiness = springiness;
  16532. }
  16533. ElasticEase.prototype.easeInCore = function (gradient) {
  16534. var num2;
  16535. var num3 = Math.max(0.0, this.oscillations);
  16536. var num = Math.max(0.0, this.springiness);
  16537. if (num == 0) {
  16538. num2 = gradient;
  16539. }
  16540. else {
  16541. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16542. }
  16543. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16544. };
  16545. return ElasticEase;
  16546. })(EasingFunction);
  16547. BABYLON.ElasticEase = ElasticEase;
  16548. var ExponentialEase = (function (_super) {
  16549. __extends(ExponentialEase, _super);
  16550. function ExponentialEase(exponent) {
  16551. if (exponent === void 0) { exponent = 2; }
  16552. _super.call(this);
  16553. this.exponent = exponent;
  16554. }
  16555. ExponentialEase.prototype.easeInCore = function (gradient) {
  16556. if (this.exponent <= 0) {
  16557. return gradient;
  16558. }
  16559. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16560. };
  16561. return ExponentialEase;
  16562. })(EasingFunction);
  16563. BABYLON.ExponentialEase = ExponentialEase;
  16564. var PowerEase = (function (_super) {
  16565. __extends(PowerEase, _super);
  16566. function PowerEase(power) {
  16567. if (power === void 0) { power = 2; }
  16568. _super.call(this);
  16569. this.power = power;
  16570. }
  16571. PowerEase.prototype.easeInCore = function (gradient) {
  16572. var y = Math.max(0.0, this.power);
  16573. return Math.pow(gradient, y);
  16574. };
  16575. return PowerEase;
  16576. })(EasingFunction);
  16577. BABYLON.PowerEase = PowerEase;
  16578. var QuadraticEase = (function (_super) {
  16579. __extends(QuadraticEase, _super);
  16580. function QuadraticEase() {
  16581. _super.apply(this, arguments);
  16582. }
  16583. QuadraticEase.prototype.easeInCore = function (gradient) {
  16584. return (gradient * gradient);
  16585. };
  16586. return QuadraticEase;
  16587. })(EasingFunction);
  16588. BABYLON.QuadraticEase = QuadraticEase;
  16589. var QuarticEase = (function (_super) {
  16590. __extends(QuarticEase, _super);
  16591. function QuarticEase() {
  16592. _super.apply(this, arguments);
  16593. }
  16594. QuarticEase.prototype.easeInCore = function (gradient) {
  16595. return (gradient * gradient * gradient * gradient);
  16596. };
  16597. return QuarticEase;
  16598. })(EasingFunction);
  16599. BABYLON.QuarticEase = QuarticEase;
  16600. var QuinticEase = (function (_super) {
  16601. __extends(QuinticEase, _super);
  16602. function QuinticEase() {
  16603. _super.apply(this, arguments);
  16604. }
  16605. QuinticEase.prototype.easeInCore = function (gradient) {
  16606. return (gradient * gradient * gradient * gradient * gradient);
  16607. };
  16608. return QuinticEase;
  16609. })(EasingFunction);
  16610. BABYLON.QuinticEase = QuinticEase;
  16611. var SineEase = (function (_super) {
  16612. __extends(SineEase, _super);
  16613. function SineEase() {
  16614. _super.apply(this, arguments);
  16615. }
  16616. SineEase.prototype.easeInCore = function (gradient) {
  16617. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16618. };
  16619. return SineEase;
  16620. })(EasingFunction);
  16621. BABYLON.SineEase = SineEase;
  16622. var BezierCurveEase = (function (_super) {
  16623. __extends(BezierCurveEase, _super);
  16624. function BezierCurveEase(x1, y1, x2, y2) {
  16625. if (x1 === void 0) { x1 = 0; }
  16626. if (y1 === void 0) { y1 = 0; }
  16627. if (x2 === void 0) { x2 = 1; }
  16628. if (y2 === void 0) { y2 = 1; }
  16629. _super.call(this);
  16630. this.x1 = x1;
  16631. this.y1 = y1;
  16632. this.x2 = x2;
  16633. this.y2 = y2;
  16634. }
  16635. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16636. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16637. };
  16638. return BezierCurveEase;
  16639. })(EasingFunction);
  16640. BABYLON.BezierCurveEase = BezierCurveEase;
  16641. })(BABYLON || (BABYLON = {}));
  16642. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16643. (function (BABYLON) {
  16644. var Octree = (function () {
  16645. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16646. if (maxDepth === void 0) { maxDepth = 2; }
  16647. this.maxDepth = maxDepth;
  16648. this.dynamicContent = new Array();
  16649. this._maxBlockCapacity = maxBlockCapacity || 64;
  16650. this._selectionContent = new BABYLON.SmartArray(1024);
  16651. this._creationFunc = creationFunc;
  16652. }
  16653. // Methods
  16654. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16655. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16656. };
  16657. Octree.prototype.addMesh = function (entry) {
  16658. for (var index = 0; index < this.blocks.length; index++) {
  16659. var block = this.blocks[index];
  16660. block.addEntry(entry);
  16661. }
  16662. };
  16663. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16664. this._selectionContent.reset();
  16665. for (var index = 0; index < this.blocks.length; index++) {
  16666. var block = this.blocks[index];
  16667. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16668. }
  16669. if (allowDuplicate) {
  16670. this._selectionContent.concat(this.dynamicContent);
  16671. }
  16672. else {
  16673. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16674. }
  16675. return this._selectionContent;
  16676. };
  16677. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16678. this._selectionContent.reset();
  16679. for (var index = 0; index < this.blocks.length; index++) {
  16680. var block = this.blocks[index];
  16681. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16682. }
  16683. if (allowDuplicate) {
  16684. this._selectionContent.concat(this.dynamicContent);
  16685. }
  16686. else {
  16687. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16688. }
  16689. return this._selectionContent;
  16690. };
  16691. Octree.prototype.intersectsRay = function (ray) {
  16692. this._selectionContent.reset();
  16693. for (var index = 0; index < this.blocks.length; index++) {
  16694. var block = this.blocks[index];
  16695. block.intersectsRay(ray, this._selectionContent);
  16696. }
  16697. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16698. return this._selectionContent;
  16699. };
  16700. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16701. target.blocks = new Array();
  16702. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16703. for (var x = 0; x < 2; x++) {
  16704. for (var y = 0; y < 2; y++) {
  16705. for (var z = 0; z < 2; z++) {
  16706. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16707. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16708. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16709. block.addEntries(entries);
  16710. target.blocks.push(block);
  16711. }
  16712. }
  16713. }
  16714. };
  16715. Octree.CreationFuncForMeshes = function (entry, block) {
  16716. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16717. block.entries.push(entry);
  16718. }
  16719. };
  16720. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16721. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16722. block.entries.push(entry);
  16723. }
  16724. };
  16725. return Octree;
  16726. })();
  16727. BABYLON.Octree = Octree;
  16728. })(BABYLON || (BABYLON = {}));
  16729. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16730. (function (BABYLON) {
  16731. var OctreeBlock = (function () {
  16732. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16733. this.entries = new Array();
  16734. this._boundingVectors = new Array();
  16735. this._capacity = capacity;
  16736. this._depth = depth;
  16737. this._maxDepth = maxDepth;
  16738. this._creationFunc = creationFunc;
  16739. this._minPoint = minPoint;
  16740. this._maxPoint = maxPoint;
  16741. this._boundingVectors.push(minPoint.clone());
  16742. this._boundingVectors.push(maxPoint.clone());
  16743. this._boundingVectors.push(minPoint.clone());
  16744. this._boundingVectors[2].x = maxPoint.x;
  16745. this._boundingVectors.push(minPoint.clone());
  16746. this._boundingVectors[3].y = maxPoint.y;
  16747. this._boundingVectors.push(minPoint.clone());
  16748. this._boundingVectors[4].z = maxPoint.z;
  16749. this._boundingVectors.push(maxPoint.clone());
  16750. this._boundingVectors[5].z = minPoint.z;
  16751. this._boundingVectors.push(maxPoint.clone());
  16752. this._boundingVectors[6].x = minPoint.x;
  16753. this._boundingVectors.push(maxPoint.clone());
  16754. this._boundingVectors[7].y = minPoint.y;
  16755. }
  16756. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16757. // Property
  16758. get: function () {
  16759. return this._capacity;
  16760. },
  16761. enumerable: true,
  16762. configurable: true
  16763. });
  16764. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16765. get: function () {
  16766. return this._minPoint;
  16767. },
  16768. enumerable: true,
  16769. configurable: true
  16770. });
  16771. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16772. get: function () {
  16773. return this._maxPoint;
  16774. },
  16775. enumerable: true,
  16776. configurable: true
  16777. });
  16778. // Methods
  16779. OctreeBlock.prototype.addEntry = function (entry) {
  16780. if (this.blocks) {
  16781. for (var index = 0; index < this.blocks.length; index++) {
  16782. var block = this.blocks[index];
  16783. block.addEntry(entry);
  16784. }
  16785. return;
  16786. }
  16787. this._creationFunc(entry, this);
  16788. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16789. this.createInnerBlocks();
  16790. }
  16791. };
  16792. OctreeBlock.prototype.addEntries = function (entries) {
  16793. for (var index = 0; index < entries.length; index++) {
  16794. var mesh = entries[index];
  16795. this.addEntry(mesh);
  16796. }
  16797. };
  16798. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16799. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16800. if (this.blocks) {
  16801. for (var index = 0; index < this.blocks.length; index++) {
  16802. var block = this.blocks[index];
  16803. block.select(frustumPlanes, selection, allowDuplicate);
  16804. }
  16805. return;
  16806. }
  16807. if (allowDuplicate) {
  16808. selection.concat(this.entries);
  16809. }
  16810. else {
  16811. selection.concatWithNoDuplicate(this.entries);
  16812. }
  16813. }
  16814. };
  16815. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16816. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16817. if (this.blocks) {
  16818. for (var index = 0; index < this.blocks.length; index++) {
  16819. var block = this.blocks[index];
  16820. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16821. }
  16822. return;
  16823. }
  16824. if (allowDuplicate) {
  16825. selection.concat(this.entries);
  16826. }
  16827. else {
  16828. selection.concatWithNoDuplicate(this.entries);
  16829. }
  16830. }
  16831. };
  16832. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16833. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16834. if (this.blocks) {
  16835. for (var index = 0; index < this.blocks.length; index++) {
  16836. var block = this.blocks[index];
  16837. block.intersectsRay(ray, selection);
  16838. }
  16839. return;
  16840. }
  16841. selection.concatWithNoDuplicate(this.entries);
  16842. }
  16843. };
  16844. OctreeBlock.prototype.createInnerBlocks = function () {
  16845. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16846. };
  16847. return OctreeBlock;
  16848. })();
  16849. BABYLON.OctreeBlock = OctreeBlock;
  16850. })(BABYLON || (BABYLON = {}));
  16851. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16852. (function (BABYLON) {
  16853. var Bone = (function () {
  16854. function Bone(name, skeleton, parentBone, matrix) {
  16855. this.name = name;
  16856. this.children = new Array();
  16857. this.animations = new Array();
  16858. this._worldTransform = new BABYLON.Matrix();
  16859. this._absoluteTransform = new BABYLON.Matrix();
  16860. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16861. this._skeleton = skeleton;
  16862. this._matrix = matrix;
  16863. this._baseMatrix = matrix;
  16864. skeleton.bones.push(this);
  16865. if (parentBone) {
  16866. this._parent = parentBone;
  16867. parentBone.children.push(this);
  16868. }
  16869. else {
  16870. this._parent = null;
  16871. }
  16872. this._updateDifferenceMatrix();
  16873. }
  16874. // Members
  16875. Bone.prototype.getParent = function () {
  16876. return this._parent;
  16877. };
  16878. Bone.prototype.getLocalMatrix = function () {
  16879. return this._matrix;
  16880. };
  16881. Bone.prototype.getBaseMatrix = function () {
  16882. return this._baseMatrix;
  16883. };
  16884. Bone.prototype.getWorldMatrix = function () {
  16885. return this._worldTransform;
  16886. };
  16887. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16888. return this._invertedAbsoluteTransform;
  16889. };
  16890. Bone.prototype.getAbsoluteMatrix = function () {
  16891. var matrix = this._matrix.clone();
  16892. var parent = this._parent;
  16893. while (parent) {
  16894. matrix = matrix.multiply(parent.getLocalMatrix());
  16895. parent = parent.getParent();
  16896. }
  16897. return matrix;
  16898. };
  16899. // Methods
  16900. Bone.prototype.updateMatrix = function (matrix) {
  16901. this._matrix = matrix;
  16902. this._skeleton._markAsDirty();
  16903. this._updateDifferenceMatrix();
  16904. };
  16905. Bone.prototype._updateDifferenceMatrix = function () {
  16906. if (this._parent) {
  16907. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16908. }
  16909. else {
  16910. this._absoluteTransform.copyFrom(this._matrix);
  16911. }
  16912. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16913. for (var index = 0; index < this.children.length; index++) {
  16914. this.children[index]._updateDifferenceMatrix();
  16915. }
  16916. };
  16917. Bone.prototype.markAsDirty = function () {
  16918. this._skeleton._markAsDirty();
  16919. };
  16920. return Bone;
  16921. })();
  16922. BABYLON.Bone = Bone;
  16923. })(BABYLON || (BABYLON = {}));
  16924. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16925. (function (BABYLON) {
  16926. var Skeleton = (function () {
  16927. function Skeleton(name, id, scene) {
  16928. this.name = name;
  16929. this.id = id;
  16930. this.bones = new Array();
  16931. this._isDirty = true;
  16932. this._identity = BABYLON.Matrix.Identity();
  16933. this.bones = [];
  16934. this._scene = scene;
  16935. scene.skeletons.push(this);
  16936. }
  16937. // Members
  16938. Skeleton.prototype.getTransformMatrices = function () {
  16939. return this._transformMatrices;
  16940. };
  16941. // Methods
  16942. Skeleton.prototype._markAsDirty = function () {
  16943. this._isDirty = true;
  16944. };
  16945. Skeleton.prototype.prepare = function () {
  16946. if (!this._isDirty) {
  16947. return;
  16948. }
  16949. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16950. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16951. }
  16952. for (var index = 0; index < this.bones.length; index++) {
  16953. var bone = this.bones[index];
  16954. var parentBone = bone.getParent();
  16955. if (parentBone) {
  16956. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16957. }
  16958. else {
  16959. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16960. }
  16961. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16962. }
  16963. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16964. this._isDirty = false;
  16965. this._scene._activeBones += this.bones.length;
  16966. };
  16967. Skeleton.prototype.getAnimatables = function () {
  16968. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16969. this._animatables = [];
  16970. for (var index = 0; index < this.bones.length; index++) {
  16971. this._animatables.push(this.bones[index]);
  16972. }
  16973. }
  16974. return this._animatables;
  16975. };
  16976. Skeleton.prototype.clone = function (name, id) {
  16977. var result = new Skeleton(name, id || name, this._scene);
  16978. for (var index = 0; index < this.bones.length; index++) {
  16979. var source = this.bones[index];
  16980. var parentBone = null;
  16981. if (source.getParent()) {
  16982. var parentIndex = this.bones.indexOf(source.getParent());
  16983. parentBone = result.bones[parentIndex];
  16984. }
  16985. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16986. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16987. }
  16988. return result;
  16989. };
  16990. return Skeleton;
  16991. })();
  16992. BABYLON.Skeleton = Skeleton;
  16993. })(BABYLON || (BABYLON = {}));
  16994. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16995. (function (BABYLON) {
  16996. var PostProcess = (function () {
  16997. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16998. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  16999. this.name = name;
  17000. this.width = -1;
  17001. this.height = -1;
  17002. this._reusable = false;
  17003. this._textures = new BABYLON.SmartArray(2);
  17004. this._currentRenderTextureInd = 0;
  17005. if (camera != null) {
  17006. this._camera = camera;
  17007. this._scene = camera.getScene();
  17008. camera.attachPostProcess(this);
  17009. this._engine = this._scene.getEngine();
  17010. }
  17011. else {
  17012. this._engine = engine;
  17013. }
  17014. this._renderRatio = ratio;
  17015. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17016. this._reusable = reusable || false;
  17017. samplers = samplers || [];
  17018. samplers.push("textureSampler");
  17019. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17020. }
  17021. PostProcess.prototype.isReusable = function () {
  17022. return this._reusable;
  17023. };
  17024. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17025. camera = camera || this._camera;
  17026. var scene = camera.getScene();
  17027. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17028. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17029. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17030. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17031. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17032. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17033. if (this._textures.length > 0) {
  17034. for (var i = 0; i < this._textures.length; i++) {
  17035. this._engine._releaseTexture(this._textures.data[i]);
  17036. }
  17037. this._textures.reset();
  17038. }
  17039. this.width = desiredWidth;
  17040. this.height = desiredHeight;
  17041. 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 }));
  17042. if (this._reusable) {
  17043. 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 }));
  17044. }
  17045. if (this.onSizeChanged) {
  17046. this.onSizeChanged();
  17047. }
  17048. }
  17049. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17050. if (this.onActivate) {
  17051. this.onActivate(camera);
  17052. }
  17053. // Clear
  17054. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17055. if (this._reusable) {
  17056. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17057. }
  17058. };
  17059. PostProcess.prototype.apply = function () {
  17060. // Check
  17061. if (!this._effect.isReady())
  17062. return null;
  17063. // States
  17064. this._engine.enableEffect(this._effect);
  17065. this._engine.setState(false);
  17066. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17067. this._engine.setDepthBuffer(false);
  17068. this._engine.setDepthWrite(false);
  17069. // Texture
  17070. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17071. // Parameters
  17072. if (this.onApply) {
  17073. this.onApply(this._effect);
  17074. }
  17075. return this._effect;
  17076. };
  17077. PostProcess.prototype.dispose = function (camera) {
  17078. camera = camera || this._camera;
  17079. if (this._textures.length > 0) {
  17080. for (var i = 0; i < this._textures.length; i++) {
  17081. this._engine._releaseTexture(this._textures.data[i]);
  17082. }
  17083. this._textures.reset();
  17084. }
  17085. if (!camera) {
  17086. return;
  17087. }
  17088. camera.detachPostProcess(this);
  17089. var index = camera._postProcesses.indexOf(this);
  17090. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17091. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17092. }
  17093. };
  17094. return PostProcess;
  17095. })();
  17096. BABYLON.PostProcess = PostProcess;
  17097. })(BABYLON || (BABYLON = {}));
  17098. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17099. (function (BABYLON) {
  17100. var PostProcessManager = (function () {
  17101. function PostProcessManager(scene) {
  17102. this._vertexDeclaration = [2];
  17103. this._vertexStrideSize = 2 * 4;
  17104. this._scene = scene;
  17105. // VBO
  17106. var vertices = [];
  17107. vertices.push(1, 1);
  17108. vertices.push(-1, 1);
  17109. vertices.push(-1, -1);
  17110. vertices.push(1, -1);
  17111. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17112. // Indices
  17113. var indices = [];
  17114. indices.push(0);
  17115. indices.push(1);
  17116. indices.push(2);
  17117. indices.push(0);
  17118. indices.push(2);
  17119. indices.push(3);
  17120. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17121. }
  17122. // Methods
  17123. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17124. var postProcesses = this._scene.activeCamera._postProcesses;
  17125. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17126. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17127. return false;
  17128. }
  17129. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17130. return true;
  17131. };
  17132. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17133. var engine = this._scene.getEngine();
  17134. for (var index = 0; index < postProcesses.length; index++) {
  17135. if (index < postProcesses.length - 1) {
  17136. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17137. }
  17138. else {
  17139. if (targetTexture) {
  17140. engine.bindFramebuffer(targetTexture);
  17141. }
  17142. else {
  17143. engine.restoreDefaultFramebuffer();
  17144. }
  17145. }
  17146. var pp = postProcesses[index];
  17147. var effect = pp.apply();
  17148. if (effect) {
  17149. if (pp.onBeforeRender) {
  17150. pp.onBeforeRender(effect);
  17151. }
  17152. // VBOs
  17153. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17154. // Draw order
  17155. engine.draw(true, 0, 6);
  17156. }
  17157. }
  17158. // Restore depth buffer
  17159. engine.setDepthBuffer(true);
  17160. engine.setDepthWrite(true);
  17161. };
  17162. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17163. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17164. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17165. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17166. return;
  17167. }
  17168. var engine = this._scene.getEngine();
  17169. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17170. if (index < postProcessesTakenIndices.length - 1) {
  17171. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17172. }
  17173. else {
  17174. if (targetTexture) {
  17175. engine.bindFramebuffer(targetTexture);
  17176. }
  17177. else {
  17178. engine.restoreDefaultFramebuffer();
  17179. }
  17180. }
  17181. if (doNotPresent) {
  17182. break;
  17183. }
  17184. var pp = postProcesses[postProcessesTakenIndices[index]];
  17185. var effect = pp.apply();
  17186. if (effect) {
  17187. if (pp.onBeforeRender) {
  17188. pp.onBeforeRender(effect);
  17189. }
  17190. // VBOs
  17191. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17192. // Draw order
  17193. engine.draw(true, 0, 6);
  17194. }
  17195. }
  17196. // Restore depth buffer
  17197. engine.setDepthBuffer(true);
  17198. engine.setDepthWrite(true);
  17199. };
  17200. PostProcessManager.prototype.dispose = function () {
  17201. if (this._vertexBuffer) {
  17202. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17203. this._vertexBuffer = null;
  17204. }
  17205. if (this._indexBuffer) {
  17206. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17207. this._indexBuffer = null;
  17208. }
  17209. };
  17210. return PostProcessManager;
  17211. })();
  17212. BABYLON.PostProcessManager = PostProcessManager;
  17213. })(BABYLON || (BABYLON = {}));
  17214. //# sourceMappingURL=babylon.postProcessManager.js.map
  17215. var BABYLON;
  17216. (function (BABYLON) {
  17217. var PassPostProcess = (function (_super) {
  17218. __extends(PassPostProcess, _super);
  17219. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17220. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17221. }
  17222. return PassPostProcess;
  17223. })(BABYLON.PostProcess);
  17224. BABYLON.PassPostProcess = PassPostProcess;
  17225. })(BABYLON || (BABYLON = {}));
  17226. //# sourceMappingURL=babylon.passPostProcess.js.map
  17227. var BABYLON;
  17228. (function (BABYLON) {
  17229. var BlurPostProcess = (function (_super) {
  17230. __extends(BlurPostProcess, _super);
  17231. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17232. var _this = this;
  17233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17234. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17235. this.direction = direction;
  17236. this.blurWidth = blurWidth;
  17237. this.onApply = function (effect) {
  17238. effect.setFloat2("screenSize", _this.width, _this.height);
  17239. effect.setVector2("direction", _this.direction);
  17240. effect.setFloat("blurWidth", _this.blurWidth);
  17241. };
  17242. }
  17243. return BlurPostProcess;
  17244. })(BABYLON.PostProcess);
  17245. BABYLON.BlurPostProcess = BlurPostProcess;
  17246. })(BABYLON || (BABYLON = {}));
  17247. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17248. var BABYLON;
  17249. (function (BABYLON) {
  17250. var FilterPostProcess = (function (_super) {
  17251. __extends(FilterPostProcess, _super);
  17252. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17253. var _this = this;
  17254. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17255. this.kernelMatrix = kernelMatrix;
  17256. this.onApply = function (effect) {
  17257. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17258. };
  17259. }
  17260. return FilterPostProcess;
  17261. })(BABYLON.PostProcess);
  17262. BABYLON.FilterPostProcess = FilterPostProcess;
  17263. })(BABYLON || (BABYLON = {}));
  17264. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17265. var BABYLON;
  17266. (function (BABYLON) {
  17267. var RefractionPostProcess = (function (_super) {
  17268. __extends(RefractionPostProcess, _super);
  17269. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17270. var _this = this;
  17271. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17272. this.color = color;
  17273. this.depth = depth;
  17274. this.colorLevel = colorLevel;
  17275. this.onActivate = function (cam) {
  17276. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17277. };
  17278. this.onApply = function (effect) {
  17279. effect.setColor3("baseColor", _this.color);
  17280. effect.setFloat("depth", _this.depth);
  17281. effect.setFloat("colorLevel", _this.colorLevel);
  17282. effect.setTexture("refractionSampler", _this._refRexture);
  17283. };
  17284. }
  17285. // Methods
  17286. RefractionPostProcess.prototype.dispose = function (camera) {
  17287. if (this._refRexture) {
  17288. this._refRexture.dispose();
  17289. }
  17290. _super.prototype.dispose.call(this, camera);
  17291. };
  17292. return RefractionPostProcess;
  17293. })(BABYLON.PostProcess);
  17294. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17295. })(BABYLON || (BABYLON = {}));
  17296. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17297. var BABYLON;
  17298. (function (BABYLON) {
  17299. var BlackAndWhitePostProcess = (function (_super) {
  17300. __extends(BlackAndWhitePostProcess, _super);
  17301. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17302. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17303. }
  17304. return BlackAndWhitePostProcess;
  17305. })(BABYLON.PostProcess);
  17306. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17307. })(BABYLON || (BABYLON = {}));
  17308. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17309. var BABYLON;
  17310. (function (BABYLON) {
  17311. var ConvolutionPostProcess = (function (_super) {
  17312. __extends(ConvolutionPostProcess, _super);
  17313. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17314. var _this = this;
  17315. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17316. this.kernel = kernel;
  17317. this.onApply = function (effect) {
  17318. effect.setFloat2("screenSize", _this.width, _this.height);
  17319. effect.setArray("kernel", _this.kernel);
  17320. };
  17321. }
  17322. // Statics
  17323. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17324. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17325. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17326. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17327. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17328. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17329. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17330. return ConvolutionPostProcess;
  17331. })(BABYLON.PostProcess);
  17332. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17333. })(BABYLON || (BABYLON = {}));
  17334. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17335. var BABYLON;
  17336. (function (BABYLON) {
  17337. var FxaaPostProcess = (function (_super) {
  17338. __extends(FxaaPostProcess, _super);
  17339. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17340. var _this = this;
  17341. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17342. this.onSizeChanged = function () {
  17343. _this.texelWidth = 1.0 / _this.width;
  17344. _this.texelHeight = 1.0 / _this.height;
  17345. };
  17346. this.onApply = function (effect) {
  17347. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17348. };
  17349. }
  17350. return FxaaPostProcess;
  17351. })(BABYLON.PostProcess);
  17352. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17353. })(BABYLON || (BABYLON = {}));
  17354. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17355. (function (BABYLON) {
  17356. var LensFlare = (function () {
  17357. function LensFlare(size, position, color, imgUrl, system) {
  17358. this.size = size;
  17359. this.position = position;
  17360. this.dispose = function () {
  17361. if (this.texture) {
  17362. this.texture.dispose();
  17363. }
  17364. // Remove from scene
  17365. var index = this._system.lensFlares.indexOf(this);
  17366. this._system.lensFlares.splice(index, 1);
  17367. };
  17368. this.color = color || new BABYLON.Color3(1, 1, 1);
  17369. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17370. this._system = system;
  17371. system.lensFlares.push(this);
  17372. }
  17373. return LensFlare;
  17374. })();
  17375. BABYLON.LensFlare = LensFlare;
  17376. })(BABYLON || (BABYLON = {}));
  17377. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17378. (function (BABYLON) {
  17379. var LensFlareSystem = (function () {
  17380. function LensFlareSystem(name, emitter, scene) {
  17381. this.name = name;
  17382. this.lensFlares = new Array();
  17383. this.borderLimit = 300;
  17384. this._vertexDeclaration = [2];
  17385. this._vertexStrideSize = 2 * 4;
  17386. this._isEnabled = true;
  17387. this._scene = scene;
  17388. this._emitter = emitter;
  17389. scene.lensFlareSystems.push(this);
  17390. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17391. // VBO
  17392. var vertices = [];
  17393. vertices.push(1, 1);
  17394. vertices.push(-1, 1);
  17395. vertices.push(-1, -1);
  17396. vertices.push(1, -1);
  17397. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17398. // Indices
  17399. var indices = [];
  17400. indices.push(0);
  17401. indices.push(1);
  17402. indices.push(2);
  17403. indices.push(0);
  17404. indices.push(2);
  17405. indices.push(3);
  17406. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17407. // Effects
  17408. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17409. }
  17410. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17411. get: function () {
  17412. return this._isEnabled;
  17413. },
  17414. set: function (value) {
  17415. this._isEnabled = value;
  17416. },
  17417. enumerable: true,
  17418. configurable: true
  17419. });
  17420. LensFlareSystem.prototype.getScene = function () {
  17421. return this._scene;
  17422. };
  17423. LensFlareSystem.prototype.getEmitter = function () {
  17424. return this._emitter;
  17425. };
  17426. LensFlareSystem.prototype.getEmitterPosition = function () {
  17427. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17428. };
  17429. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17430. var position = this.getEmitterPosition();
  17431. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17432. this._positionX = position.x;
  17433. this._positionY = position.y;
  17434. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17435. if (position.z > 0) {
  17436. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17437. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17438. return true;
  17439. }
  17440. }
  17441. return false;
  17442. };
  17443. LensFlareSystem.prototype._isVisible = function () {
  17444. if (!this._isEnabled) {
  17445. return false;
  17446. }
  17447. var emitterPosition = this.getEmitterPosition();
  17448. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17449. var distance = direction.length();
  17450. direction.normalize();
  17451. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17452. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17453. return !pickInfo.hit || pickInfo.distance > distance;
  17454. };
  17455. LensFlareSystem.prototype.render = function () {
  17456. if (!this._effect.isReady())
  17457. return false;
  17458. var engine = this._scene.getEngine();
  17459. var viewport = this._scene.activeCamera.viewport;
  17460. var globalViewport = viewport.toGlobal(engine);
  17461. // Position
  17462. if (!this.computeEffectivePosition(globalViewport)) {
  17463. return false;
  17464. }
  17465. // Visibility
  17466. if (!this._isVisible()) {
  17467. return false;
  17468. }
  17469. // Intensity
  17470. var awayX;
  17471. var awayY;
  17472. if (this._positionX < this.borderLimit + globalViewport.x) {
  17473. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17474. }
  17475. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17476. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17477. }
  17478. else {
  17479. awayX = 0;
  17480. }
  17481. if (this._positionY < this.borderLimit + globalViewport.y) {
  17482. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17483. }
  17484. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17485. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17486. }
  17487. else {
  17488. awayY = 0;
  17489. }
  17490. var away = (awayX > awayY) ? awayX : awayY;
  17491. if (away > this.borderLimit) {
  17492. away = this.borderLimit;
  17493. }
  17494. var intensity = 1.0 - (away / this.borderLimit);
  17495. if (intensity < 0) {
  17496. return false;
  17497. }
  17498. if (intensity > 1.0) {
  17499. intensity = 1.0;
  17500. }
  17501. // Position
  17502. var centerX = globalViewport.x + globalViewport.width / 2;
  17503. var centerY = globalViewport.y + globalViewport.height / 2;
  17504. var distX = centerX - this._positionX;
  17505. var distY = centerY - this._positionY;
  17506. // Effects
  17507. engine.enableEffect(this._effect);
  17508. engine.setState(false);
  17509. engine.setDepthBuffer(false);
  17510. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17511. // VBOs
  17512. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17513. for (var index = 0; index < this.lensFlares.length; index++) {
  17514. var flare = this.lensFlares[index];
  17515. var x = centerX - (distX * flare.position);
  17516. var y = centerY - (distY * flare.position);
  17517. var cw = flare.size;
  17518. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17519. var cx = 2 * (x / globalViewport.width) - 1.0;
  17520. var cy = 1.0 - 2 * (y / globalViewport.height);
  17521. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17522. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17523. // Texture
  17524. this._effect.setTexture("textureSampler", flare.texture);
  17525. // Color
  17526. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17527. // Draw order
  17528. engine.draw(true, 0, 6);
  17529. }
  17530. engine.setDepthBuffer(true);
  17531. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17532. return true;
  17533. };
  17534. LensFlareSystem.prototype.dispose = function () {
  17535. if (this._vertexBuffer) {
  17536. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17537. this._vertexBuffer = null;
  17538. }
  17539. if (this._indexBuffer) {
  17540. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17541. this._indexBuffer = null;
  17542. }
  17543. while (this.lensFlares.length) {
  17544. this.lensFlares[0].dispose();
  17545. }
  17546. // Remove from scene
  17547. var index = this._scene.lensFlareSystems.indexOf(this);
  17548. this._scene.lensFlareSystems.splice(index, 1);
  17549. };
  17550. return LensFlareSystem;
  17551. })();
  17552. BABYLON.LensFlareSystem = LensFlareSystem;
  17553. })(BABYLON || (BABYLON = {}));
  17554. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17555. (function (BABYLON) {
  17556. var IntersectionInfo = (function () {
  17557. function IntersectionInfo(bu, bv, distance) {
  17558. this.bu = bu;
  17559. this.bv = bv;
  17560. this.distance = distance;
  17561. this.faceId = 0;
  17562. this.subMeshId = 0;
  17563. }
  17564. return IntersectionInfo;
  17565. })();
  17566. BABYLON.IntersectionInfo = IntersectionInfo;
  17567. var PickingInfo = (function () {
  17568. function PickingInfo() {
  17569. this.hit = false;
  17570. this.distance = 0;
  17571. this.pickedPoint = null;
  17572. this.pickedMesh = null;
  17573. this.bu = 0;
  17574. this.bv = 0;
  17575. this.faceId = -1;
  17576. this.subMeshId = 0;
  17577. }
  17578. // Methods
  17579. PickingInfo.prototype.getNormal = function () {
  17580. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17581. return null;
  17582. }
  17583. var indices = this.pickedMesh.getIndices();
  17584. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17585. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17586. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17587. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17588. normal0 = normal0.scale(this.bu);
  17589. normal1 = normal1.scale(this.bv);
  17590. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17591. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17592. };
  17593. PickingInfo.prototype.getTextureCoordinates = function () {
  17594. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17595. return null;
  17596. }
  17597. var indices = this.pickedMesh.getIndices();
  17598. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17599. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17600. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17601. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17602. uv0 = uv0.scale(this.bu);
  17603. uv1 = uv1.scale(this.bv);
  17604. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17605. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17606. };
  17607. return PickingInfo;
  17608. })();
  17609. BABYLON.PickingInfo = PickingInfo;
  17610. })(BABYLON || (BABYLON = {}));
  17611. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17612. (function (BABYLON) {
  17613. var FilesInput = (function () {
  17614. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17615. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17616. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17617. this._engine = p_engine;
  17618. this._canvas = p_canvas;
  17619. this._currentScene = p_scene;
  17620. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17621. this._progressCallback = p_progressCallback;
  17622. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17623. this._textureLoadingCallback = p_textureLoadingCallback;
  17624. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17625. }
  17626. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17627. var _this = this;
  17628. if (p_elementToMonitor) {
  17629. this._elementToMonitor = p_elementToMonitor;
  17630. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17631. _this.drag(e);
  17632. }, false);
  17633. this._elementToMonitor.addEventListener("dragover", function (e) {
  17634. _this.drag(e);
  17635. }, false);
  17636. this._elementToMonitor.addEventListener("drop", function (e) {
  17637. _this.drop(e);
  17638. }, false);
  17639. }
  17640. };
  17641. FilesInput.prototype.renderFunction = function () {
  17642. if (this._additionnalRenderLoopLogicCallback) {
  17643. this._additionnalRenderLoopLogicCallback();
  17644. }
  17645. if (this._currentScene) {
  17646. if (this._textureLoadingCallback) {
  17647. var remaining = this._currentScene.getWaitingItemsCount();
  17648. if (remaining > 0) {
  17649. this._textureLoadingCallback(remaining);
  17650. }
  17651. }
  17652. this._currentScene.render();
  17653. }
  17654. };
  17655. FilesInput.prototype.drag = function (e) {
  17656. e.stopPropagation();
  17657. e.preventDefault();
  17658. };
  17659. FilesInput.prototype.drop = function (eventDrop) {
  17660. eventDrop.stopPropagation();
  17661. eventDrop.preventDefault();
  17662. this.loadFiles(eventDrop);
  17663. };
  17664. FilesInput.prototype.loadFiles = function (event) {
  17665. if (this._startingProcessingFilesCallback)
  17666. this._startingProcessingFilesCallback();
  17667. // Handling data transfer via drag'n'drop
  17668. if (event && event.dataTransfer && event.dataTransfer.files) {
  17669. this._filesToLoad = event.dataTransfer.files;
  17670. }
  17671. // Handling files from input files
  17672. if (event && event.target && event.target.files) {
  17673. this._filesToLoad = event.target.files;
  17674. }
  17675. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17676. for (var i = 0; i < this._filesToLoad.length; i++) {
  17677. switch (this._filesToLoad[i].type) {
  17678. case "image/jpeg":
  17679. case "image/png":
  17680. case "image/bmp":
  17681. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17682. break;
  17683. case "image/targa":
  17684. case "image/vnd.ms-dds":
  17685. case "audio/wav":
  17686. case "audio/x-wav":
  17687. case "audio/mp3":
  17688. case "audio/mpeg":
  17689. case "audio/mpeg3":
  17690. case "audio/x-mpeg-3":
  17691. case "audio/ogg":
  17692. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17693. break;
  17694. default:
  17695. 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) {
  17696. this._sceneFileToLoad = this._filesToLoad[i];
  17697. }
  17698. break;
  17699. }
  17700. }
  17701. this.reload();
  17702. }
  17703. };
  17704. FilesInput.prototype.reload = function () {
  17705. var _this = this;
  17706. var that = this;
  17707. // If a ".babylon" file has been provided
  17708. if (this._sceneFileToLoad) {
  17709. if (this._currentScene) {
  17710. this._engine.stopRenderLoop();
  17711. this._currentScene.dispose();
  17712. }
  17713. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17714. that._currentScene = newScene;
  17715. // Wait for textures and shaders to be ready
  17716. that._currentScene.executeWhenReady(function () {
  17717. // Attach camera to canvas inputs
  17718. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17719. that._currentScene.createDefaultCameraOrLight();
  17720. }
  17721. that._currentScene.activeCamera.attachControl(that._canvas);
  17722. if (that._sceneLoadedCallback) {
  17723. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17724. }
  17725. that._engine.runRenderLoop(function () {
  17726. that.renderFunction();
  17727. });
  17728. });
  17729. }, function (progress) {
  17730. if (_this._progressCallback) {
  17731. _this._progressCallback(progress);
  17732. }
  17733. });
  17734. }
  17735. else {
  17736. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17737. }
  17738. };
  17739. FilesInput.FilesTextures = new Array();
  17740. FilesInput.FilesToLoad = new Array();
  17741. return FilesInput;
  17742. })();
  17743. BABYLON.FilesInput = FilesInput;
  17744. })(BABYLON || (BABYLON = {}));
  17745. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17746. (function (BABYLON) {
  17747. var OimoJSPlugin = (function () {
  17748. function OimoJSPlugin() {
  17749. this._registeredMeshes = [];
  17750. /**
  17751. * Update the body position according to the mesh position
  17752. * @param mesh
  17753. */
  17754. this.updateBodyPosition = function (mesh) {
  17755. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17756. var registeredMesh = this._registeredMeshes[index];
  17757. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17758. var body = registeredMesh.body.body;
  17759. mesh.computeWorldMatrix(true);
  17760. var center = mesh.getBoundingInfo().boundingBox.center;
  17761. body.setPosition(center.x, center.y, center.z);
  17762. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17763. return;
  17764. }
  17765. // Case where the parent has been updated
  17766. if (registeredMesh.mesh.parent === mesh) {
  17767. mesh.computeWorldMatrix(true);
  17768. registeredMesh.mesh.computeWorldMatrix(true);
  17769. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17770. var absoluteRotation = mesh.rotation;
  17771. body = registeredMesh.body.body;
  17772. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17773. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17774. return;
  17775. }
  17776. }
  17777. };
  17778. }
  17779. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17780. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17781. };
  17782. OimoJSPlugin.prototype.initialize = function (iterations) {
  17783. this._world = new OIMO.World();
  17784. this._world.clear();
  17785. };
  17786. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17787. this._world.gravity = gravity;
  17788. };
  17789. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17790. var body = null;
  17791. this.unregisterMesh(mesh);
  17792. mesh.computeWorldMatrix(true);
  17793. var initialRotation = null;
  17794. if (mesh.rotationQuaternion) {
  17795. initialRotation = mesh.rotationQuaternion.clone();
  17796. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17797. mesh.computeWorldMatrix(true);
  17798. }
  17799. var bbox = mesh.getBoundingInfo().boundingBox;
  17800. // The delta between the mesh position and the mesh bounding box center
  17801. var deltaPosition = mesh.position.subtract(bbox.center);
  17802. // Transform delta position with the rotation
  17803. if (initialRotation) {
  17804. var m = new BABYLON.Matrix();
  17805. initialRotation.toRotationMatrix(m);
  17806. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17807. }
  17808. switch (impostor) {
  17809. case BABYLON.PhysicsEngine.SphereImpostor:
  17810. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17811. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17812. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17813. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17814. body = new OIMO.Body({
  17815. type: 'sphere',
  17816. size: [size],
  17817. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17818. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17819. move: options.mass != 0,
  17820. config: [options.mass, options.friction, options.restitution],
  17821. world: this._world
  17822. });
  17823. break;
  17824. case BABYLON.PhysicsEngine.PlaneImpostor:
  17825. case BABYLON.PhysicsEngine.CylinderImpostor:
  17826. case BABYLON.PhysicsEngine.BoxImpostor:
  17827. var min = bbox.minimumWorld;
  17828. var max = bbox.maximumWorld;
  17829. var box = max.subtract(min);
  17830. var sizeX = this._checkWithEpsilon(box.x);
  17831. var sizeY = this._checkWithEpsilon(box.y);
  17832. var sizeZ = this._checkWithEpsilon(box.z);
  17833. body = new OIMO.Body({
  17834. type: 'box',
  17835. size: [sizeX, sizeY, sizeZ],
  17836. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17837. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17838. move: options.mass != 0,
  17839. config: [options.mass, options.friction, options.restitution],
  17840. world: this._world
  17841. });
  17842. break;
  17843. }
  17844. //If quaternion was set as the rotation of the object
  17845. if (initialRotation) {
  17846. //We have to access the rigid body's properties to set the quaternion.
  17847. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17848. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17849. //update the internal rotation matrix
  17850. body.body.syncShapes();
  17851. }
  17852. this._registeredMeshes.push({
  17853. mesh: mesh,
  17854. body: body,
  17855. delta: deltaPosition
  17856. });
  17857. return body;
  17858. };
  17859. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17860. var types = [], sizes = [], positions = [], rotations = [];
  17861. var initialMesh = parts[0].mesh;
  17862. for (var index = 0; index < parts.length; index++) {
  17863. var part = parts[index];
  17864. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17865. types.push(bodyParameters.type);
  17866. sizes.push.apply(sizes, bodyParameters.size);
  17867. positions.push.apply(positions, bodyParameters.pos);
  17868. rotations.push.apply(rotations, bodyParameters.rot);
  17869. }
  17870. var body = new OIMO.Body({
  17871. type: types,
  17872. size: sizes,
  17873. pos: positions,
  17874. rot: rotations,
  17875. move: options.mass != 0,
  17876. config: [options.mass, options.friction, options.restitution],
  17877. world: this._world
  17878. });
  17879. this._registeredMeshes.push({
  17880. mesh: initialMesh,
  17881. body: body
  17882. });
  17883. return body;
  17884. };
  17885. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17886. var bodyParameters = null;
  17887. var mesh = part.mesh;
  17888. // We need the bounding box/sphere info to compute the physics body
  17889. mesh.computeWorldMatrix();
  17890. switch (part.impostor) {
  17891. case BABYLON.PhysicsEngine.SphereImpostor:
  17892. var bbox = mesh.getBoundingInfo().boundingBox;
  17893. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17894. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17895. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17896. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17897. bodyParameters = {
  17898. type: 'sphere',
  17899. /* bug with oimo : sphere needs 3 sizes in this case */
  17900. size: [size, -1, -1],
  17901. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17902. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17903. };
  17904. break;
  17905. case BABYLON.PhysicsEngine.PlaneImpostor:
  17906. case BABYLON.PhysicsEngine.BoxImpostor:
  17907. bbox = mesh.getBoundingInfo().boundingBox;
  17908. var min = bbox.minimumWorld;
  17909. var max = bbox.maximumWorld;
  17910. var box = max.subtract(min);
  17911. var sizeX = this._checkWithEpsilon(box.x);
  17912. var sizeY = this._checkWithEpsilon(box.y);
  17913. var sizeZ = this._checkWithEpsilon(box.z);
  17914. var relativePosition = mesh.position;
  17915. bodyParameters = {
  17916. type: 'box',
  17917. size: [sizeX, sizeY, sizeZ],
  17918. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17919. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17920. };
  17921. break;
  17922. }
  17923. return bodyParameters;
  17924. };
  17925. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17926. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17927. var registeredMesh = this._registeredMeshes[index];
  17928. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17929. if (registeredMesh.body) {
  17930. this._world.removeRigidBody(registeredMesh.body.body);
  17931. this._unbindBody(registeredMesh.body);
  17932. }
  17933. this._registeredMeshes.splice(index, 1);
  17934. return;
  17935. }
  17936. }
  17937. };
  17938. OimoJSPlugin.prototype._unbindBody = function (body) {
  17939. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17940. var registeredMesh = this._registeredMeshes[index];
  17941. if (registeredMesh.body === body) {
  17942. registeredMesh.body = null;
  17943. }
  17944. }
  17945. };
  17946. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17947. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17948. var registeredMesh = this._registeredMeshes[index];
  17949. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17950. // Get object mass to have a behaviour similar to cannon.js
  17951. var mass = registeredMesh.body.body.massInfo.mass;
  17952. // The force is scaled with the mass of object
  17953. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17954. return;
  17955. }
  17956. }
  17957. };
  17958. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17959. var body1 = null, body2 = null;
  17960. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17961. var registeredMesh = this._registeredMeshes[index];
  17962. if (registeredMesh.mesh === mesh1) {
  17963. body1 = registeredMesh.body.body;
  17964. }
  17965. else if (registeredMesh.mesh === mesh2) {
  17966. body2 = registeredMesh.body.body;
  17967. }
  17968. }
  17969. if (!body1 || !body2) {
  17970. return false;
  17971. }
  17972. if (!options) {
  17973. options = {};
  17974. }
  17975. new OIMO.Link({
  17976. type: options.type,
  17977. body1: body1,
  17978. body2: body2,
  17979. min: options.min,
  17980. max: options.max,
  17981. axe1: options.axe1,
  17982. axe2: options.axe2,
  17983. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17984. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17985. collision: options.collision,
  17986. spring: options.spring,
  17987. world: this._world
  17988. });
  17989. return true;
  17990. };
  17991. OimoJSPlugin.prototype.dispose = function () {
  17992. this._world.clear();
  17993. while (this._registeredMeshes.length) {
  17994. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17995. }
  17996. };
  17997. OimoJSPlugin.prototype.isSupported = function () {
  17998. return OIMO !== undefined;
  17999. };
  18000. OimoJSPlugin.prototype._getLastShape = function (body) {
  18001. var lastShape = body.shapes;
  18002. while (lastShape.next) {
  18003. lastShape = lastShape.next;
  18004. }
  18005. return lastShape;
  18006. };
  18007. OimoJSPlugin.prototype.runOneStep = function (time) {
  18008. this._world.step();
  18009. // Update the position of all registered meshes
  18010. var i = this._registeredMeshes.length;
  18011. var m;
  18012. while (i--) {
  18013. var body = this._registeredMeshes[i].body.body;
  18014. var mesh = this._registeredMeshes[i].mesh;
  18015. var delta = this._registeredMeshes[i].delta;
  18016. if (!body.sleeping) {
  18017. if (body.shapes.next) {
  18018. var parentShape = this._getLastShape(body);
  18019. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18020. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18021. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18022. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18023. if (!mesh.rotationQuaternion) {
  18024. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18025. }
  18026. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18027. mesh.computeWorldMatrix();
  18028. }
  18029. else {
  18030. m = body.getMatrix();
  18031. mtx = BABYLON.Matrix.FromArray(m);
  18032. // Body position
  18033. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18034. if (!delta) {
  18035. mesh.position.x = bodyX;
  18036. mesh.position.y = bodyY;
  18037. mesh.position.z = bodyZ;
  18038. }
  18039. else {
  18040. mesh.position.x = bodyX + delta.x;
  18041. mesh.position.y = bodyY + delta.y;
  18042. mesh.position.z = bodyZ + delta.z;
  18043. }
  18044. if (!mesh.rotationQuaternion) {
  18045. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18046. }
  18047. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18048. mesh.computeWorldMatrix();
  18049. }
  18050. }
  18051. }
  18052. };
  18053. return OimoJSPlugin;
  18054. })();
  18055. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18056. })(BABYLON || (BABYLON = {}));
  18057. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18058. (function (BABYLON) {
  18059. var PhysicsEngine = (function () {
  18060. function PhysicsEngine(plugin) {
  18061. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18062. }
  18063. PhysicsEngine.prototype._initialize = function (gravity) {
  18064. this._currentPlugin.initialize();
  18065. this._setGravity(gravity);
  18066. };
  18067. PhysicsEngine.prototype._runOneStep = function (delta) {
  18068. if (delta > 0.1) {
  18069. delta = 0.1;
  18070. }
  18071. else if (delta <= 0) {
  18072. delta = 1.0 / 60.0;
  18073. }
  18074. this._currentPlugin.runOneStep(delta);
  18075. };
  18076. PhysicsEngine.prototype._setGravity = function (gravity) {
  18077. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18078. this._currentPlugin.setGravity(this.gravity);
  18079. };
  18080. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18081. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18082. };
  18083. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18084. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18085. };
  18086. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18087. this._currentPlugin.unregisterMesh(mesh);
  18088. };
  18089. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18090. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18091. };
  18092. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18093. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18094. };
  18095. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18096. this._currentPlugin.updateBodyPosition(mesh);
  18097. };
  18098. PhysicsEngine.prototype.dispose = function () {
  18099. this._currentPlugin.dispose();
  18100. };
  18101. PhysicsEngine.prototype.isSupported = function () {
  18102. return this._currentPlugin.isSupported();
  18103. };
  18104. // Statics
  18105. PhysicsEngine.NoImpostor = 0;
  18106. PhysicsEngine.SphereImpostor = 1;
  18107. PhysicsEngine.BoxImpostor = 2;
  18108. PhysicsEngine.PlaneImpostor = 3;
  18109. PhysicsEngine.MeshImpostor = 4;
  18110. PhysicsEngine.CapsuleImpostor = 5;
  18111. PhysicsEngine.ConeImpostor = 6;
  18112. PhysicsEngine.CylinderImpostor = 7;
  18113. PhysicsEngine.ConvexHullImpostor = 8;
  18114. PhysicsEngine.Epsilon = 0.001;
  18115. return PhysicsEngine;
  18116. })();
  18117. BABYLON.PhysicsEngine = PhysicsEngine;
  18118. })(BABYLON || (BABYLON = {}));
  18119. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18120. (function (BABYLON) {
  18121. var serializeLight = function (light) {
  18122. var serializationObject = {};
  18123. serializationObject.name = light.name;
  18124. serializationObject.id = light.id;
  18125. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18126. if (light instanceof BABYLON.PointLight) {
  18127. serializationObject.type = 0;
  18128. serializationObject.position = light.position.asArray();
  18129. }
  18130. else if (light instanceof BABYLON.DirectionalLight) {
  18131. serializationObject.type = 1;
  18132. var directionalLight = light;
  18133. serializationObject.position = directionalLight.position.asArray();
  18134. serializationObject.direction = directionalLight.direction.asArray();
  18135. }
  18136. else if (light instanceof BABYLON.SpotLight) {
  18137. serializationObject.type = 2;
  18138. var spotLight = light;
  18139. serializationObject.position = spotLight.position.asArray();
  18140. serializationObject.direction = spotLight.position.asArray();
  18141. serializationObject.angle = spotLight.angle;
  18142. serializationObject.exponent = spotLight.exponent;
  18143. }
  18144. else if (light instanceof BABYLON.HemisphericLight) {
  18145. serializationObject.type = 3;
  18146. var hemisphericLight = light;
  18147. serializationObject.direction = hemisphericLight.direction.asArray();
  18148. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18149. }
  18150. if (light.intensity) {
  18151. serializationObject.intensity = light.intensity;
  18152. }
  18153. serializationObject.range = light.range;
  18154. serializationObject.diffuse = light.diffuse.asArray();
  18155. serializationObject.specular = light.specular.asArray();
  18156. return serializationObject;
  18157. };
  18158. var serializeFresnelParameter = function (fresnelParameter) {
  18159. var serializationObject = {};
  18160. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18161. serializationObject.leftColor = fresnelParameter.leftColor;
  18162. serializationObject.rightColor = fresnelParameter.rightColor;
  18163. serializationObject.bias = fresnelParameter.bias;
  18164. serializationObject.power = fresnelParameter.power;
  18165. return serializationObject;
  18166. };
  18167. var appendAnimations = function (source, destination) {
  18168. if (source.animations) {
  18169. destination.animations = [];
  18170. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18171. var animation = source.animations[animationIndex];
  18172. destination.animations.push(serializeAnimation(animation));
  18173. }
  18174. }
  18175. };
  18176. var serializeCamera = function (camera) {
  18177. var serializationObject = {};
  18178. serializationObject.name = camera.name;
  18179. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18180. serializationObject.id = camera.id;
  18181. serializationObject.position = camera.position.asArray();
  18182. // Parent
  18183. if (camera.parent) {
  18184. serializationObject.parentId = camera.parent.id;
  18185. }
  18186. serializationObject.fov = camera.fov;
  18187. serializationObject.minZ = camera.minZ;
  18188. serializationObject.maxZ = camera.maxZ;
  18189. serializationObject.inertia = camera.inertia;
  18190. //setting the type
  18191. if (camera instanceof BABYLON.FreeCamera) {
  18192. serializationObject.type = "FreeCamera";
  18193. }
  18194. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18195. serializationObject.type = "ArcRotateCamera";
  18196. }
  18197. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18198. serializationObject.type = "AnaglyphArcRotateCamera";
  18199. }
  18200. else if (camera instanceof BABYLON.GamepadCamera) {
  18201. serializationObject.type = "GamepadCamera";
  18202. }
  18203. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18204. serializationObject.type = "AnaglyphFreeCamera";
  18205. }
  18206. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18207. serializationObject.type = "DeviceOrientationCamera";
  18208. }
  18209. else if (camera instanceof BABYLON.FollowCamera) {
  18210. serializationObject.type = "FollowCamera";
  18211. }
  18212. else if (camera instanceof BABYLON.OculusCamera) {
  18213. serializationObject.type = "OculusCamera";
  18214. }
  18215. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18216. serializationObject.type = "OculusGamepadCamera";
  18217. }
  18218. else if (camera instanceof BABYLON.TouchCamera) {
  18219. serializationObject.type = "TouchCamera";
  18220. }
  18221. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18222. serializationObject.type = "VirtualJoysticksCamera";
  18223. }
  18224. else if (camera instanceof BABYLON.WebVRCamera) {
  18225. serializationObject.type = "WebVRCamera";
  18226. }
  18227. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18228. serializationObject.type = "VRDeviceOrientationCamera";
  18229. }
  18230. //special properties of specific cameras
  18231. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18232. var arcCamera = camera;
  18233. serializationObject.alpha = arcCamera.alpha;
  18234. serializationObject.beta = arcCamera.beta;
  18235. serializationObject.radius = arcCamera.radius;
  18236. if (arcCamera.target && arcCamera.target.id) {
  18237. serializationObject.lockedTargetId = arcCamera.target.id;
  18238. }
  18239. }
  18240. else if (camera instanceof BABYLON.FollowCamera) {
  18241. var followCam = camera;
  18242. serializationObject.radius = followCam.radius;
  18243. serializationObject.heightOffset = followCam.heightOffset;
  18244. serializationObject.rotationOffset = followCam.rotationOffset;
  18245. }
  18246. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18247. //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.
  18248. if (camera['_eyeSpace'] !== undefined) {
  18249. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18250. }
  18251. }
  18252. //general properties that not all cameras have. The [] is due to typescript's type safety
  18253. if (camera['speed'] !== undefined) {
  18254. serializationObject.speed = camera['speed'];
  18255. }
  18256. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18257. serializationObject.target = camera['target'].asArray();
  18258. }
  18259. // Target
  18260. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18261. serializationObject.rotation = camera['rotation'].asArray();
  18262. }
  18263. // Locked target
  18264. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18265. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18266. }
  18267. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18268. serializationObject.applyGravity = camera['applyGravity'] || false;
  18269. if (camera['ellipsoid']) {
  18270. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18271. }
  18272. // Animations
  18273. appendAnimations(camera, serializationObject);
  18274. // Layer mask
  18275. serializationObject.layerMask = camera.layerMask;
  18276. return serializationObject;
  18277. };
  18278. var serializeAnimation = function (animation) {
  18279. var serializationObject = {};
  18280. serializationObject.name = animation.name;
  18281. serializationObject.property = animation.targetProperty;
  18282. serializationObject.framePerSecond = animation.framePerSecond;
  18283. serializationObject.dataType = animation.dataType;
  18284. serializationObject.loopBehavior = animation.loopMode;
  18285. var dataType = animation.dataType;
  18286. serializationObject.keys = [];
  18287. var keys = animation.getKeys();
  18288. for (var index = 0; index < keys.length; index++) {
  18289. var animationKey = keys[index];
  18290. var key = {};
  18291. key.frame = animationKey.frame;
  18292. switch (dataType) {
  18293. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18294. key.values = [animationKey.value];
  18295. break;
  18296. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18297. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18298. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18299. key.values = animationKey.value.asArray();
  18300. break;
  18301. }
  18302. serializationObject.keys.push(key);
  18303. }
  18304. return serializationObject;
  18305. };
  18306. var serializeMultiMaterial = function (material) {
  18307. var serializationObject = {};
  18308. serializationObject.name = material.name;
  18309. serializationObject.id = material.id;
  18310. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18311. serializationObject.materials = [];
  18312. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18313. var subMat = material.subMaterials[matIndex];
  18314. if (subMat) {
  18315. serializationObject.materials.push(subMat.id);
  18316. }
  18317. else {
  18318. serializationObject.materials.push(null);
  18319. }
  18320. }
  18321. return serializationObject;
  18322. };
  18323. var serializeMaterial = function (material) {
  18324. var serializationObject = {};
  18325. serializationObject.name = material.name;
  18326. serializationObject.ambient = material.ambientColor.asArray();
  18327. serializationObject.diffuse = material.diffuseColor.asArray();
  18328. serializationObject.specular = material.specularColor.asArray();
  18329. serializationObject.specularPower = material.specularPower;
  18330. serializationObject.emissive = material.emissiveColor.asArray();
  18331. serializationObject.alpha = material.alpha;
  18332. serializationObject.id = material.id;
  18333. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18334. serializationObject.backFaceCulling = material.backFaceCulling;
  18335. if (material.diffuseTexture) {
  18336. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18337. }
  18338. if (material.diffuseFresnelParameters) {
  18339. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18340. }
  18341. if (material.ambientTexture) {
  18342. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18343. }
  18344. if (material.opacityTexture) {
  18345. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18346. }
  18347. if (material.opacityFresnelParameters) {
  18348. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18349. }
  18350. if (material.reflectionTexture) {
  18351. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18352. }
  18353. if (material.reflectionFresnelParameters) {
  18354. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18355. }
  18356. if (material.emissiveTexture) {
  18357. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18358. }
  18359. if (material.emissiveFresnelParameters) {
  18360. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18361. }
  18362. if (material.specularTexture) {
  18363. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18364. }
  18365. if (material.bumpTexture) {
  18366. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18367. }
  18368. return serializationObject;
  18369. };
  18370. var serializeTexture = function (texture) {
  18371. var serializationObject = {};
  18372. if (!texture.name) {
  18373. return null;
  18374. }
  18375. if (texture instanceof BABYLON.CubeTexture) {
  18376. serializationObject.name = texture.name;
  18377. serializationObject.hasAlpha = texture.hasAlpha;
  18378. serializationObject.level = texture.level;
  18379. serializationObject.coordinatesMode = texture.coordinatesMode;
  18380. return serializationObject;
  18381. }
  18382. if (texture instanceof BABYLON.MirrorTexture) {
  18383. var mirrorTexture = texture;
  18384. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18385. serializationObject.renderList = [];
  18386. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18387. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18388. }
  18389. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18390. }
  18391. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18392. var renderTargetTexture = texture;
  18393. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18394. serializationObject.renderList = [];
  18395. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18396. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18397. }
  18398. }
  18399. var regularTexture = texture;
  18400. serializationObject.name = texture.name;
  18401. serializationObject.hasAlpha = texture.hasAlpha;
  18402. serializationObject.level = texture.level;
  18403. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18404. serializationObject.coordinatesMode = texture.coordinatesMode;
  18405. serializationObject.uOffset = regularTexture.uOffset;
  18406. serializationObject.vOffset = regularTexture.vOffset;
  18407. serializationObject.uScale = regularTexture.uScale;
  18408. serializationObject.vScale = regularTexture.vScale;
  18409. serializationObject.uAng = regularTexture.uAng;
  18410. serializationObject.vAng = regularTexture.vAng;
  18411. serializationObject.wAng = regularTexture.wAng;
  18412. serializationObject.wrapU = texture.wrapU;
  18413. serializationObject.wrapV = texture.wrapV;
  18414. // Animations
  18415. appendAnimations(texture, serializationObject);
  18416. return serializationObject;
  18417. };
  18418. var serializeSkeleton = function (skeleton) {
  18419. var serializationObject = {};
  18420. serializationObject.name = skeleton.name;
  18421. serializationObject.id = skeleton.id;
  18422. serializationObject.bones = [];
  18423. for (var index = 0; index < skeleton.bones.length; index++) {
  18424. var bone = skeleton.bones[index];
  18425. var serializedBone = {
  18426. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18427. name: bone.name,
  18428. matrix: bone.getLocalMatrix().toArray()
  18429. };
  18430. serializationObject.bones.push(serializedBone);
  18431. if (bone.animations && bone.animations.length > 0) {
  18432. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18433. }
  18434. }
  18435. return serializationObject;
  18436. };
  18437. var serializeParticleSystem = function (particleSystem) {
  18438. var serializationObject = {};
  18439. serializationObject.emitterId = particleSystem.emitter.id;
  18440. serializationObject.capacity = particleSystem.getCapacity();
  18441. if (particleSystem.particleTexture) {
  18442. serializationObject.textureName = particleSystem.particleTexture.name;
  18443. }
  18444. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18445. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18446. serializationObject.minSize = particleSystem.minSize;
  18447. serializationObject.maxSize = particleSystem.maxSize;
  18448. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18449. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18450. serializationObject.emitRate = particleSystem.emitRate;
  18451. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18452. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18453. serializationObject.gravity = particleSystem.gravity.asArray();
  18454. serializationObject.direction1 = particleSystem.direction1.asArray();
  18455. serializationObject.direction2 = particleSystem.direction2.asArray();
  18456. serializationObject.color1 = particleSystem.color1.asArray();
  18457. serializationObject.color2 = particleSystem.color2.asArray();
  18458. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18459. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18460. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18461. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18462. serializationObject.blendMode = particleSystem.blendMode;
  18463. return serializationObject;
  18464. };
  18465. var serializeLensFlareSystem = function (lensFlareSystem) {
  18466. var serializationObject = {};
  18467. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18468. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18469. serializationObject.flares = [];
  18470. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18471. var flare = lensFlareSystem.lensFlares[index];
  18472. serializationObject.flares.push({
  18473. size: flare.size,
  18474. position: flare.position,
  18475. color: flare.color.asArray(),
  18476. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18477. });
  18478. }
  18479. return serializationObject;
  18480. };
  18481. var serializeShadowGenerator = function (light) {
  18482. var serializationObject = {};
  18483. var shadowGenerator = light.getShadowGenerator();
  18484. serializationObject.lightId = light.id;
  18485. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18486. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18487. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18488. serializationObject.renderList = [];
  18489. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18490. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18491. serializationObject.renderList.push(mesh.id);
  18492. }
  18493. return serializationObject;
  18494. };
  18495. var serializedGeometries = [];
  18496. var serializeGeometry = function (geometry, serializationGeometries) {
  18497. if (serializedGeometries[geometry.id]) {
  18498. return;
  18499. }
  18500. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18501. serializationGeometries.boxes.push(serializeBox(geometry));
  18502. }
  18503. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18504. serializationGeometries.spheres.push(serializeSphere(geometry));
  18505. }
  18506. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18507. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18508. }
  18509. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18510. serializationGeometries.toruses.push(serializeTorus(geometry));
  18511. }
  18512. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18513. serializationGeometries.grounds.push(serializeGround(geometry));
  18514. }
  18515. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18516. serializationGeometries.planes.push(serializePlane(geometry));
  18517. }
  18518. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18519. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18520. }
  18521. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18522. throw new Error("Unknow primitive type");
  18523. }
  18524. else {
  18525. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18526. }
  18527. serializedGeometries[geometry.id] = true;
  18528. };
  18529. var serializeGeometryBase = function (geometry) {
  18530. var serializationObject = {};
  18531. serializationObject.id = geometry.id;
  18532. if (BABYLON.Tags.HasTags(geometry)) {
  18533. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18534. }
  18535. return serializationObject;
  18536. };
  18537. var serializeVertexData = function (vertexData) {
  18538. var serializationObject = serializeGeometryBase(vertexData);
  18539. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18540. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18541. }
  18542. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18543. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18544. }
  18545. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18546. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18547. }
  18548. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18549. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18550. }
  18551. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18552. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18553. }
  18554. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18555. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18556. serializationObject.matricesIndices._isExpanded = true;
  18557. }
  18558. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18559. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18560. }
  18561. serializationObject.indices = vertexData.getIndices();
  18562. return serializationObject;
  18563. };
  18564. var serializePrimitive = function (primitive) {
  18565. var serializationObject = serializeGeometryBase(primitive);
  18566. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18567. return serializationObject;
  18568. };
  18569. var serializeBox = function (box) {
  18570. var serializationObject = serializePrimitive(box);
  18571. serializationObject.size = box.size;
  18572. return serializationObject;
  18573. };
  18574. var serializeSphere = function (sphere) {
  18575. var serializationObject = serializePrimitive(sphere);
  18576. serializationObject.segments = sphere.segments;
  18577. serializationObject.diameter = sphere.diameter;
  18578. return serializationObject;
  18579. };
  18580. var serializeCylinder = function (cylinder) {
  18581. var serializationObject = serializePrimitive(cylinder);
  18582. serializationObject.height = cylinder.height;
  18583. serializationObject.diameterTop = cylinder.diameterTop;
  18584. serializationObject.diameterBottom = cylinder.diameterBottom;
  18585. serializationObject.tessellation = cylinder.tessellation;
  18586. return serializationObject;
  18587. };
  18588. var serializeTorus = function (torus) {
  18589. var serializationObject = serializePrimitive(torus);
  18590. serializationObject.diameter = torus.diameter;
  18591. serializationObject.thickness = torus.thickness;
  18592. serializationObject.tessellation = torus.tessellation;
  18593. return serializationObject;
  18594. };
  18595. var serializeGround = function (ground) {
  18596. var serializationObject = serializePrimitive(ground);
  18597. serializationObject.width = ground.width;
  18598. serializationObject.height = ground.height;
  18599. serializationObject.subdivisions = ground.subdivisions;
  18600. return serializationObject;
  18601. };
  18602. var serializePlane = function (plane) {
  18603. var serializationObject = serializePrimitive(plane);
  18604. serializationObject.size = plane.size;
  18605. return serializationObject;
  18606. };
  18607. var serializeTorusKnot = function (torusKnot) {
  18608. var serializationObject = serializePrimitive(torusKnot);
  18609. serializationObject.radius = torusKnot.radius;
  18610. serializationObject.tube = torusKnot.tube;
  18611. serializationObject.radialSegments = torusKnot.radialSegments;
  18612. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18613. serializationObject.p = torusKnot.p;
  18614. serializationObject.q = torusKnot.q;
  18615. return serializationObject;
  18616. };
  18617. var serializeMesh = function (mesh, serializationScene) {
  18618. var serializationObject = {};
  18619. serializationObject.name = mesh.name;
  18620. serializationObject.id = mesh.id;
  18621. if (BABYLON.Tags.HasTags(mesh)) {
  18622. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18623. }
  18624. serializationObject.position = mesh.position.asArray();
  18625. if (mesh.rotationQuaternion) {
  18626. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18627. }
  18628. else if (mesh.rotation) {
  18629. serializationObject.rotation = mesh.rotation.asArray();
  18630. }
  18631. serializationObject.scaling = mesh.scaling.asArray();
  18632. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18633. serializationObject.isEnabled = mesh.isEnabled();
  18634. serializationObject.isVisible = mesh.isVisible;
  18635. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18636. serializationObject.pickable = mesh.isPickable;
  18637. serializationObject.receiveShadows = mesh.receiveShadows;
  18638. serializationObject.billboardMode = mesh.billboardMode;
  18639. serializationObject.visibility = mesh.visibility;
  18640. serializationObject.checkCollisions = mesh.checkCollisions;
  18641. // Parent
  18642. if (mesh.parent) {
  18643. serializationObject.parentId = mesh.parent.id;
  18644. }
  18645. // Geometry
  18646. var geometry = mesh._geometry;
  18647. if (geometry) {
  18648. var geometryId = geometry.id;
  18649. serializationObject.geometryId = geometryId;
  18650. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18651. // 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
  18652. serializeGeometry(geometry, serializationScene.geometries);
  18653. }
  18654. // SubMeshes
  18655. serializationObject.subMeshes = [];
  18656. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18657. var subMesh = mesh.subMeshes[subIndex];
  18658. serializationObject.subMeshes.push({
  18659. materialIndex: subMesh.materialIndex,
  18660. verticesStart: subMesh.verticesStart,
  18661. verticesCount: subMesh.verticesCount,
  18662. indexStart: subMesh.indexStart,
  18663. indexCount: subMesh.indexCount
  18664. });
  18665. }
  18666. }
  18667. // Material
  18668. if (mesh.material) {
  18669. serializationObject.materialId = mesh.material.id;
  18670. }
  18671. else {
  18672. mesh.material = null;
  18673. }
  18674. // Skeleton
  18675. if (mesh.skeleton) {
  18676. serializationObject.skeletonId = mesh.skeleton.id;
  18677. }
  18678. // Physics
  18679. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18680. serializationObject.physicsMass = mesh.getPhysicsMass();
  18681. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18682. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18683. switch (mesh.getPhysicsImpostor()) {
  18684. case BABYLON.PhysicsEngine.BoxImpostor:
  18685. serializationObject.physicsImpostor = 1;
  18686. break;
  18687. case BABYLON.PhysicsEngine.SphereImpostor:
  18688. serializationObject.physicsImpostor = 2;
  18689. break;
  18690. }
  18691. }
  18692. // Instances
  18693. serializationObject.instances = [];
  18694. for (var index = 0; index < mesh.instances.length; index++) {
  18695. var instance = mesh.instances[index];
  18696. var serializationInstance = {
  18697. name: instance.name,
  18698. position: instance.position,
  18699. rotation: instance.rotation,
  18700. rotationQuaternion: instance.rotationQuaternion,
  18701. scaling: instance.scaling
  18702. };
  18703. serializationObject.instances.push(serializationInstance);
  18704. // Animations
  18705. appendAnimations(instance, serializationInstance);
  18706. }
  18707. // Animations
  18708. appendAnimations(mesh, serializationObject);
  18709. // Layer mask
  18710. serializationObject.layerMask = mesh.layerMask;
  18711. return serializationObject;
  18712. };
  18713. var SceneSerializer = (function () {
  18714. function SceneSerializer() {
  18715. }
  18716. SceneSerializer.Serialize = function (scene) {
  18717. var serializationObject = {};
  18718. // Scene
  18719. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18720. serializationObject.autoClear = scene.autoClear;
  18721. serializationObject.clearColor = scene.clearColor.asArray();
  18722. serializationObject.ambientColor = scene.ambientColor.asArray();
  18723. serializationObject.gravity = scene.gravity.asArray();
  18724. // Fog
  18725. if (scene.fogMode && scene.fogMode !== 0) {
  18726. serializationObject.fogMode = scene.fogMode;
  18727. serializationObject.fogColor = scene.fogColor.asArray();
  18728. serializationObject.fogStart = scene.fogStart;
  18729. serializationObject.fogEnd = scene.fogEnd;
  18730. serializationObject.fogDensity = scene.fogDensity;
  18731. }
  18732. // Lights
  18733. serializationObject.lights = [];
  18734. for (var index = 0; index < scene.lights.length; index++) {
  18735. var light = scene.lights[index];
  18736. serializationObject.lights.push(serializeLight(light));
  18737. }
  18738. // Cameras
  18739. serializationObject.cameras = [];
  18740. for (index = 0; index < scene.cameras.length; index++) {
  18741. var camera = scene.cameras[index];
  18742. serializationObject.cameras.push(serializeCamera(camera));
  18743. }
  18744. if (scene.activeCamera) {
  18745. serializationObject.activeCameraID = scene.activeCamera.id;
  18746. }
  18747. // Materials
  18748. serializationObject.materials = [];
  18749. serializationObject.multiMaterials = [];
  18750. for (index = 0; index < scene.materials.length; index++) {
  18751. var material = scene.materials[index];
  18752. if (material instanceof BABYLON.StandardMaterial) {
  18753. serializationObject.materials.push(serializeMaterial(material));
  18754. }
  18755. else if (material instanceof BABYLON.MultiMaterial) {
  18756. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18757. }
  18758. }
  18759. // Skeletons
  18760. serializationObject.skeletons = [];
  18761. for (index = 0; index < scene.skeletons.length; index++) {
  18762. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18763. }
  18764. // Geometries
  18765. serializationObject.geometries = {};
  18766. serializationObject.geometries.boxes = [];
  18767. serializationObject.geometries.spheres = [];
  18768. serializationObject.geometries.cylinders = [];
  18769. serializationObject.geometries.toruses = [];
  18770. serializationObject.geometries.grounds = [];
  18771. serializationObject.geometries.planes = [];
  18772. serializationObject.geometries.torusKnots = [];
  18773. serializationObject.geometries.vertexData = [];
  18774. serializedGeometries = [];
  18775. var geometries = scene.getGeometries();
  18776. for (index = 0; index < geometries.length; index++) {
  18777. var geometry = geometries[index];
  18778. if (geometry.isReady()) {
  18779. serializeGeometry(geometry, serializationObject.geometries);
  18780. }
  18781. }
  18782. // Meshes
  18783. serializationObject.meshes = [];
  18784. for (index = 0; index < scene.meshes.length; index++) {
  18785. var abstractMesh = scene.meshes[index];
  18786. if (abstractMesh instanceof BABYLON.Mesh) {
  18787. var mesh = abstractMesh;
  18788. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18789. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18790. }
  18791. }
  18792. }
  18793. // Particles Systems
  18794. serializationObject.particleSystems = [];
  18795. for (index = 0; index < scene.particleSystems.length; index++) {
  18796. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18797. }
  18798. // Lens flares
  18799. serializationObject.lensFlareSystems = [];
  18800. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18801. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18802. }
  18803. // Shadows
  18804. serializationObject.shadowGenerators = [];
  18805. for (index = 0; index < scene.lights.length; index++) {
  18806. light = scene.lights[index];
  18807. if (light.getShadowGenerator()) {
  18808. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18809. }
  18810. }
  18811. return serializationObject;
  18812. };
  18813. return SceneSerializer;
  18814. })();
  18815. BABYLON.SceneSerializer = SceneSerializer;
  18816. })(BABYLON || (BABYLON = {}));
  18817. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18818. (function (BABYLON) {
  18819. var SceneLoader = (function () {
  18820. function SceneLoader() {
  18821. }
  18822. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18823. get: function () {
  18824. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18825. },
  18826. set: function (value) {
  18827. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18828. },
  18829. enumerable: true,
  18830. configurable: true
  18831. });
  18832. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18833. get: function () {
  18834. return SceneLoader._ShowLoadingScreen;
  18835. },
  18836. set: function (value) {
  18837. SceneLoader._ShowLoadingScreen = value;
  18838. },
  18839. enumerable: true,
  18840. configurable: true
  18841. });
  18842. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18843. var dotPosition = sceneFilename.lastIndexOf(".");
  18844. var queryStringPosition = sceneFilename.indexOf("?");
  18845. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18846. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18847. var plugin = this._registeredPlugins[index];
  18848. if (plugin.extensions.indexOf(extension) !== -1) {
  18849. return plugin;
  18850. }
  18851. }
  18852. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18853. };
  18854. // Public functions
  18855. SceneLoader.RegisterPlugin = function (plugin) {
  18856. plugin.extensions = plugin.extensions.toLowerCase();
  18857. SceneLoader._registeredPlugins.push(plugin);
  18858. };
  18859. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18860. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18861. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18862. return;
  18863. }
  18864. var manifestChecked = function (success) {
  18865. scene.database = database;
  18866. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18867. var importMeshFromData = function (data) {
  18868. var meshes = [];
  18869. var particleSystems = [];
  18870. var skeletons = [];
  18871. try {
  18872. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18873. if (onerror) {
  18874. onerror(scene, 'unable to load the scene');
  18875. }
  18876. return;
  18877. }
  18878. }
  18879. catch (e) {
  18880. if (onerror) {
  18881. onerror(scene, e);
  18882. }
  18883. return;
  18884. }
  18885. if (onsuccess) {
  18886. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18887. onsuccess(meshes, particleSystems, skeletons);
  18888. }
  18889. };
  18890. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18891. // Direct load
  18892. importMeshFromData(sceneFilename.substr(5));
  18893. return;
  18894. }
  18895. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18896. importMeshFromData(data);
  18897. }, progressCallBack, database);
  18898. };
  18899. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18900. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18901. };
  18902. /**
  18903. * Load a scene
  18904. * @param rootUrl a string that defines the root url for scene and resources
  18905. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18906. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18907. */
  18908. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18909. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18910. };
  18911. /**
  18912. * Append a scene
  18913. * @param rootUrl a string that defines the root url for scene and resources
  18914. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18915. * @param scene is the instance of BABYLON.Scene to append to
  18916. */
  18917. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18918. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18919. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18920. return;
  18921. }
  18922. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18923. var database;
  18924. if (SceneLoader.ShowLoadingScreen) {
  18925. scene.getEngine().displayLoadingUI();
  18926. }
  18927. var loadSceneFromData = function (data) {
  18928. scene.database = database;
  18929. if (!plugin.load(scene, data, rootUrl)) {
  18930. if (onerror) {
  18931. onerror(scene);
  18932. }
  18933. scene.getEngine().hideLoadingUI();
  18934. return;
  18935. }
  18936. if (onsuccess) {
  18937. onsuccess(scene);
  18938. }
  18939. if (SceneLoader.ShowLoadingScreen) {
  18940. scene.executeWhenReady(function () {
  18941. scene.getEngine().hideLoadingUI();
  18942. });
  18943. }
  18944. };
  18945. var manifestChecked = function (success) {
  18946. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18947. };
  18948. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18949. // Direct load
  18950. loadSceneFromData(sceneFilename.substr(5));
  18951. return;
  18952. }
  18953. if (rootUrl.indexOf("file:") === -1) {
  18954. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18955. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18956. }
  18957. else {
  18958. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18959. }
  18960. };
  18961. // Flags
  18962. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18963. SceneLoader._ShowLoadingScreen = true;
  18964. // Members
  18965. SceneLoader._registeredPlugins = new Array();
  18966. return SceneLoader;
  18967. })();
  18968. BABYLON.SceneLoader = SceneLoader;
  18969. ;
  18970. })(BABYLON || (BABYLON = {}));
  18971. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18972. (function (BABYLON) {
  18973. var Internals;
  18974. (function (Internals) {
  18975. var checkColors4 = function (colors, count) {
  18976. // Check if color3 was used
  18977. if (colors.length === count * 3) {
  18978. var colors4 = [];
  18979. for (var index = 0; index < colors.length; index += 3) {
  18980. var newIndex = (index / 3) * 4;
  18981. colors4[newIndex] = colors[index];
  18982. colors4[newIndex + 1] = colors[index + 1];
  18983. colors4[newIndex + 2] = colors[index + 2];
  18984. colors4[newIndex + 3] = 1.0;
  18985. }
  18986. return colors4;
  18987. }
  18988. return colors;
  18989. };
  18990. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18991. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18992. texture.name = parsedTexture.name;
  18993. texture.hasAlpha = parsedTexture.hasAlpha;
  18994. texture.level = parsedTexture.level;
  18995. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18996. return texture;
  18997. };
  18998. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18999. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19000. return null;
  19001. }
  19002. if (parsedTexture.isCube) {
  19003. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19004. }
  19005. var texture;
  19006. if (parsedTexture.mirrorPlane) {
  19007. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19008. texture._waitingRenderList = parsedTexture.renderList;
  19009. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19010. }
  19011. else if (parsedTexture.isRenderTarget) {
  19012. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19013. texture._waitingRenderList = parsedTexture.renderList;
  19014. }
  19015. else {
  19016. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19017. }
  19018. texture.name = parsedTexture.name;
  19019. texture.hasAlpha = parsedTexture.hasAlpha;
  19020. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19021. texture.level = parsedTexture.level;
  19022. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19023. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19024. texture.uOffset = parsedTexture.uOffset;
  19025. texture.vOffset = parsedTexture.vOffset;
  19026. texture.uScale = parsedTexture.uScale;
  19027. texture.vScale = parsedTexture.vScale;
  19028. texture.uAng = parsedTexture.uAng;
  19029. texture.vAng = parsedTexture.vAng;
  19030. texture.wAng = parsedTexture.wAng;
  19031. texture.wrapU = parsedTexture.wrapU;
  19032. texture.wrapV = parsedTexture.wrapV;
  19033. // Animations
  19034. if (parsedTexture.animations) {
  19035. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19036. var parsedAnimation = parsedTexture.animations[animationIndex];
  19037. texture.animations.push(parseAnimation(parsedAnimation));
  19038. }
  19039. }
  19040. return texture;
  19041. };
  19042. var parseSkeleton = function (parsedSkeleton, scene) {
  19043. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19044. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19045. var parsedBone = parsedSkeleton.bones[index];
  19046. var parentBone = null;
  19047. if (parsedBone.parentBoneIndex > -1) {
  19048. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19049. }
  19050. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19051. if (parsedBone.animation) {
  19052. bone.animations.push(parseAnimation(parsedBone.animation));
  19053. }
  19054. }
  19055. return skeleton;
  19056. };
  19057. var parseFresnelParameters = function (parsedFresnelParameters) {
  19058. var fresnelParameters = new BABYLON.FresnelParameters();
  19059. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19060. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19061. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19062. fresnelParameters.bias = parsedFresnelParameters.bias;
  19063. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19064. return fresnelParameters;
  19065. };
  19066. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19067. var material;
  19068. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19069. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19070. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19071. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19072. material.specularPower = parsedMaterial.specularPower;
  19073. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19074. material.alpha = parsedMaterial.alpha;
  19075. material.id = parsedMaterial.id;
  19076. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19077. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19078. material.wireframe = parsedMaterial.wireframe;
  19079. if (parsedMaterial.diffuseTexture) {
  19080. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19081. }
  19082. if (parsedMaterial.diffuseFresnelParameters) {
  19083. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19084. }
  19085. if (parsedMaterial.ambientTexture) {
  19086. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19087. }
  19088. if (parsedMaterial.opacityTexture) {
  19089. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19090. }
  19091. if (parsedMaterial.opacityFresnelParameters) {
  19092. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19093. }
  19094. if (parsedMaterial.reflectionTexture) {
  19095. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19096. }
  19097. if (parsedMaterial.reflectionFresnelParameters) {
  19098. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19099. }
  19100. if (parsedMaterial.emissiveTexture) {
  19101. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19102. }
  19103. if (parsedMaterial.emissiveFresnelParameters) {
  19104. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19105. }
  19106. if (parsedMaterial.specularTexture) {
  19107. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19108. }
  19109. if (parsedMaterial.bumpTexture) {
  19110. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19111. }
  19112. return material;
  19113. };
  19114. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19115. for (var index = 0; index < parsedData.materials.length; index++) {
  19116. var parsedMaterial = parsedData.materials[index];
  19117. if (parsedMaterial.id === id) {
  19118. return parseMaterial(parsedMaterial, scene, rootUrl);
  19119. }
  19120. }
  19121. return null;
  19122. };
  19123. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19124. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19125. multiMaterial.id = parsedMultiMaterial.id;
  19126. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19127. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19128. var subMatId = parsedMultiMaterial.materials[matIndex];
  19129. if (subMatId) {
  19130. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19131. }
  19132. else {
  19133. multiMaterial.subMaterials.push(null);
  19134. }
  19135. }
  19136. return multiMaterial;
  19137. };
  19138. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19139. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19140. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19141. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19142. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19143. var parsedFlare = parsedLensFlareSystem.flares[index];
  19144. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19145. }
  19146. return lensFlareSystem;
  19147. };
  19148. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19149. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19150. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19151. if (parsedParticleSystem.textureName) {
  19152. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19153. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19154. }
  19155. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19156. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19157. particleSystem.minSize = parsedParticleSystem.minSize;
  19158. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19159. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19160. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19161. particleSystem.emitter = emitter;
  19162. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19163. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19164. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19165. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19166. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19167. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19168. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19169. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19170. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19171. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19172. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19173. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19174. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19175. particleSystem.start();
  19176. return particleSystem;
  19177. };
  19178. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19179. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19180. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19181. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19182. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19183. shadowGenerator.getShadowMap().renderList.push(mesh);
  19184. }
  19185. if (parsedShadowGenerator.usePoissonSampling) {
  19186. shadowGenerator.usePoissonSampling = true;
  19187. }
  19188. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19189. shadowGenerator.useVarianceShadowMap = true;
  19190. }
  19191. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19192. shadowGenerator.useBlurVarianceShadowMap = true;
  19193. if (parsedShadowGenerator.blurScale) {
  19194. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19195. }
  19196. if (parsedShadowGenerator.blurBoxOffset) {
  19197. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19198. }
  19199. }
  19200. if (parsedShadowGenerator.bias !== undefined) {
  19201. shadowGenerator.bias = parsedShadowGenerator.bias;
  19202. }
  19203. return shadowGenerator;
  19204. };
  19205. var parseAnimation = function (parsedAnimation) {
  19206. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19207. var dataType = parsedAnimation.dataType;
  19208. var keys = [];
  19209. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19210. var key = parsedAnimation.keys[index];
  19211. var data;
  19212. switch (dataType) {
  19213. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19214. data = key.values[0];
  19215. break;
  19216. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19217. data = BABYLON.Quaternion.FromArray(key.values);
  19218. break;
  19219. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19220. data = BABYLON.Matrix.FromArray(key.values);
  19221. break;
  19222. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19223. default:
  19224. data = BABYLON.Vector3.FromArray(key.values);
  19225. break;
  19226. }
  19227. keys.push({
  19228. frame: key.frame,
  19229. value: data
  19230. });
  19231. }
  19232. animation.setKeys(keys);
  19233. return animation;
  19234. };
  19235. var parseLight = function (parsedLight, scene) {
  19236. var light;
  19237. switch (parsedLight.type) {
  19238. case 0:
  19239. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19240. break;
  19241. case 1:
  19242. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19243. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19244. break;
  19245. case 2:
  19246. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19247. break;
  19248. case 3:
  19249. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19250. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19251. break;
  19252. }
  19253. light.id = parsedLight.id;
  19254. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19255. if (parsedLight.intensity !== undefined) {
  19256. light.intensity = parsedLight.intensity;
  19257. }
  19258. if (parsedLight.range) {
  19259. light.range = parsedLight.range;
  19260. }
  19261. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19262. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19263. if (parsedLight.excludedMeshesIds) {
  19264. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19265. }
  19266. // Parent
  19267. if (parsedLight.parentId) {
  19268. light._waitingParentId = parsedLight.parentId;
  19269. }
  19270. if (parsedLight.includedOnlyMeshesIds) {
  19271. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19272. }
  19273. // Animations
  19274. if (parsedLight.animations) {
  19275. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19276. var parsedAnimation = parsedLight.animations[animationIndex];
  19277. light.animations.push(parseAnimation(parsedAnimation));
  19278. }
  19279. }
  19280. if (parsedLight.autoAnimate) {
  19281. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19282. }
  19283. };
  19284. var parseCamera = function (parsedCamera, scene) {
  19285. var camera;
  19286. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19287. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19288. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19289. var alpha = parsedCamera.alpha;
  19290. var beta = parsedCamera.beta;
  19291. var radius = parsedCamera.radius;
  19292. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19293. var eye_space = parsedCamera.eye_space;
  19294. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19295. }
  19296. else {
  19297. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19298. }
  19299. }
  19300. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19301. eye_space = parsedCamera.eye_space;
  19302. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19303. }
  19304. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19305. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19306. }
  19307. else if (parsedCamera.type === "FollowCamera") {
  19308. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19309. camera.heightOffset = parsedCamera.heightOffset;
  19310. camera.radius = parsedCamera.radius;
  19311. camera.rotationOffset = parsedCamera.rotationOffset;
  19312. if (lockedTargetMesh)
  19313. camera.target = lockedTargetMesh;
  19314. }
  19315. else if (parsedCamera.type === "GamepadCamera") {
  19316. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19317. }
  19318. else if (parsedCamera.type === "OculusCamera") {
  19319. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19320. }
  19321. else if (parsedCamera.type === "OculusGamepadCamera") {
  19322. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19323. }
  19324. else if (parsedCamera.type === "TouchCamera") {
  19325. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19326. }
  19327. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19328. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19329. }
  19330. else if (parsedCamera.type === "WebVRCamera") {
  19331. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19332. }
  19333. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19334. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19335. }
  19336. else {
  19337. // Free Camera is the default value
  19338. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19339. }
  19340. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19341. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19342. camera.lockedTarget = lockedTargetMesh;
  19343. }
  19344. camera.id = parsedCamera.id;
  19345. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19346. // Parent
  19347. if (parsedCamera.parentId) {
  19348. camera._waitingParentId = parsedCamera.parentId;
  19349. }
  19350. // Target
  19351. if (parsedCamera.target) {
  19352. if (camera.setTarget) {
  19353. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19354. }
  19355. else {
  19356. //For ArcRotate
  19357. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19358. }
  19359. }
  19360. else {
  19361. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19362. }
  19363. camera.fov = parsedCamera.fov;
  19364. camera.minZ = parsedCamera.minZ;
  19365. camera.maxZ = parsedCamera.maxZ;
  19366. camera.speed = parsedCamera.speed;
  19367. camera.inertia = parsedCamera.inertia;
  19368. camera.checkCollisions = parsedCamera.checkCollisions;
  19369. camera.applyGravity = parsedCamera.applyGravity;
  19370. if (parsedCamera.ellipsoid) {
  19371. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19372. }
  19373. // Animations
  19374. if (parsedCamera.animations) {
  19375. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19376. var parsedAnimation = parsedCamera.animations[animationIndex];
  19377. camera.animations.push(parseAnimation(parsedAnimation));
  19378. }
  19379. }
  19380. if (parsedCamera.autoAnimate) {
  19381. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19382. }
  19383. // Layer Mask
  19384. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19385. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19386. }
  19387. else {
  19388. camera.layerMask = 0xFFFFFFFF;
  19389. }
  19390. return camera;
  19391. };
  19392. var parseGeometry = function (parsedGeometry, scene) {
  19393. var id = parsedGeometry.id;
  19394. return scene.getGeometryByID(id);
  19395. };
  19396. var parseBox = function (parsedBox, scene) {
  19397. if (parseGeometry(parsedBox, scene)) {
  19398. return null; // null since geometry could be something else than a box...
  19399. }
  19400. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19401. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19402. scene.pushGeometry(box, true);
  19403. return box;
  19404. };
  19405. var parseSphere = function (parsedSphere, scene) {
  19406. if (parseGeometry(parsedSphere, scene)) {
  19407. return null; // null since geometry could be something else than a sphere...
  19408. }
  19409. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19410. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19411. scene.pushGeometry(sphere, true);
  19412. return sphere;
  19413. };
  19414. var parseCylinder = function (parsedCylinder, scene) {
  19415. if (parseGeometry(parsedCylinder, scene)) {
  19416. return null; // null since geometry could be something else than a cylinder...
  19417. }
  19418. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19419. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19420. scene.pushGeometry(cylinder, true);
  19421. return cylinder;
  19422. };
  19423. var parseTorus = function (parsedTorus, scene) {
  19424. if (parseGeometry(parsedTorus, scene)) {
  19425. return null; // null since geometry could be something else than a torus...
  19426. }
  19427. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19428. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19429. scene.pushGeometry(torus, true);
  19430. return torus;
  19431. };
  19432. var parseGround = function (parsedGround, scene) {
  19433. if (parseGeometry(parsedGround, scene)) {
  19434. return null; // null since geometry could be something else than a ground...
  19435. }
  19436. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19437. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19438. scene.pushGeometry(ground, true);
  19439. return ground;
  19440. };
  19441. var parsePlane = function (parsedPlane, scene) {
  19442. if (parseGeometry(parsedPlane, scene)) {
  19443. return null; // null since geometry could be something else than a plane...
  19444. }
  19445. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19446. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19447. scene.pushGeometry(plane, true);
  19448. return plane;
  19449. };
  19450. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19451. if (parseGeometry(parsedTorusKnot, scene)) {
  19452. return null; // null since geometry could be something else than a torusKnot...
  19453. }
  19454. 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);
  19455. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19456. scene.pushGeometry(torusKnot, true);
  19457. return torusKnot;
  19458. };
  19459. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19460. if (parseGeometry(parsedVertexData, scene)) {
  19461. return null; // null since geometry could be a primitive
  19462. }
  19463. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19464. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19465. if (parsedVertexData.delayLoadingFile) {
  19466. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19467. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19468. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19469. geometry._delayInfo = [];
  19470. if (parsedVertexData.hasUVs) {
  19471. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19472. }
  19473. if (parsedVertexData.hasUVs2) {
  19474. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19475. }
  19476. if (parsedVertexData.hasColors) {
  19477. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19478. }
  19479. if (parsedVertexData.hasMatricesIndices) {
  19480. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19481. }
  19482. if (parsedVertexData.hasMatricesWeights) {
  19483. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19484. }
  19485. geometry._delayLoadingFunction = importVertexData;
  19486. }
  19487. else {
  19488. importVertexData(parsedVertexData, geometry);
  19489. }
  19490. scene.pushGeometry(geometry, true);
  19491. return geometry;
  19492. };
  19493. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19494. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19495. mesh.id = parsedMesh.id;
  19496. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19497. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19498. if (parsedMesh.rotationQuaternion) {
  19499. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19500. }
  19501. else if (parsedMesh.rotation) {
  19502. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19503. }
  19504. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19505. if (parsedMesh.localMatrix) {
  19506. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19507. }
  19508. else if (parsedMesh.pivotMatrix) {
  19509. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19510. }
  19511. mesh.setEnabled(parsedMesh.isEnabled);
  19512. mesh.isVisible = parsedMesh.isVisible;
  19513. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19514. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19515. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19516. if (parsedMesh.applyFog !== undefined) {
  19517. mesh.applyFog = parsedMesh.applyFog;
  19518. }
  19519. if (parsedMesh.pickable !== undefined) {
  19520. mesh.isPickable = parsedMesh.pickable;
  19521. }
  19522. if (parsedMesh.alphaIndex !== undefined) {
  19523. mesh.alphaIndex = parsedMesh.alphaIndex;
  19524. }
  19525. mesh.receiveShadows = parsedMesh.receiveShadows;
  19526. mesh.billboardMode = parsedMesh.billboardMode;
  19527. if (parsedMesh.visibility !== undefined) {
  19528. mesh.visibility = parsedMesh.visibility;
  19529. }
  19530. mesh.checkCollisions = parsedMesh.checkCollisions;
  19531. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19532. // Parent
  19533. if (parsedMesh.parentId) {
  19534. mesh._waitingParentId = parsedMesh.parentId;
  19535. }
  19536. // Actions
  19537. if (parsedMesh.actions !== undefined) {
  19538. mesh._waitingActions = parsedMesh.actions;
  19539. }
  19540. // Geometry
  19541. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19542. if (parsedMesh.delayLoadingFile) {
  19543. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19544. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19545. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19546. if (parsedMesh._binaryInfo) {
  19547. mesh._binaryInfo = parsedMesh._binaryInfo;
  19548. }
  19549. mesh._delayInfo = [];
  19550. if (parsedMesh.hasUVs) {
  19551. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19552. }
  19553. if (parsedMesh.hasUVs2) {
  19554. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19555. }
  19556. if (parsedMesh.hasColors) {
  19557. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19558. }
  19559. if (parsedMesh.hasMatricesIndices) {
  19560. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19561. }
  19562. if (parsedMesh.hasMatricesWeights) {
  19563. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19564. }
  19565. mesh._delayLoadingFunction = importGeometry;
  19566. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19567. mesh._checkDelayState();
  19568. }
  19569. }
  19570. else {
  19571. importGeometry(parsedMesh, mesh);
  19572. }
  19573. // Material
  19574. if (parsedMesh.materialId) {
  19575. mesh.setMaterialByID(parsedMesh.materialId);
  19576. }
  19577. else {
  19578. mesh.material = null;
  19579. }
  19580. // Skeleton
  19581. if (parsedMesh.skeletonId > -1) {
  19582. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19583. }
  19584. // Physics
  19585. if (parsedMesh.physicsImpostor) {
  19586. if (!scene.isPhysicsEnabled()) {
  19587. scene.enablePhysics();
  19588. }
  19589. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19590. }
  19591. // Animations
  19592. if (parsedMesh.animations) {
  19593. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19594. var parsedAnimation = parsedMesh.animations[animationIndex];
  19595. mesh.animations.push(parseAnimation(parsedAnimation));
  19596. }
  19597. }
  19598. if (parsedMesh.autoAnimate) {
  19599. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19600. }
  19601. // Layer Mask
  19602. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19603. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19604. }
  19605. else {
  19606. mesh.layerMask = 0xFFFFFFFF;
  19607. }
  19608. // Instances
  19609. if (parsedMesh.instances) {
  19610. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19611. var parsedInstance = parsedMesh.instances[index];
  19612. var instance = mesh.createInstance(parsedInstance.name);
  19613. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19614. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19615. if (parsedInstance.rotationQuaternion) {
  19616. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19617. }
  19618. else if (parsedInstance.rotation) {
  19619. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19620. }
  19621. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19622. instance.checkCollisions = mesh.checkCollisions;
  19623. if (parsedMesh.animations) {
  19624. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19625. parsedAnimation = parsedMesh.animations[animationIndex];
  19626. instance.animations.push(parseAnimation(parsedAnimation));
  19627. }
  19628. }
  19629. }
  19630. }
  19631. return mesh;
  19632. };
  19633. var parseActions = function (parsedActions, object, scene) {
  19634. var actionManager = new BABYLON.ActionManager(scene);
  19635. if (object === null)
  19636. scene.actionManager = actionManager;
  19637. else
  19638. object.actionManager = actionManager;
  19639. // instanciate a new object
  19640. var instanciate = function (name, params) {
  19641. var newInstance = Object.create(BABYLON[name].prototype);
  19642. newInstance.constructor.apply(newInstance, params);
  19643. return newInstance;
  19644. };
  19645. var parseParameter = function (name, value, target, propertyPath) {
  19646. if (propertyPath === null) {
  19647. // String, boolean or float
  19648. var floatValue = parseFloat(value);
  19649. if (value === "true" || value === "false")
  19650. return value === "true";
  19651. else
  19652. return isNaN(floatValue) ? value : floatValue;
  19653. }
  19654. var effectiveTarget = propertyPath.split(".");
  19655. var values = value.split(",");
  19656. for (var i = 0; i < effectiveTarget.length; i++) {
  19657. target = target[effectiveTarget[i]];
  19658. }
  19659. // Return appropriate value with its type
  19660. if (target instanceof Boolean)
  19661. return values[0] === "true";
  19662. if (target instanceof String)
  19663. return values[0];
  19664. // Parameters with multiple values such as Vector3 etc.
  19665. var split = new Array();
  19666. for (var i = 0; i < values.length; i++)
  19667. split.push(parseFloat(values[i]));
  19668. if (target instanceof BABYLON.Vector3)
  19669. return BABYLON.Vector3.FromArray(split);
  19670. if (target instanceof BABYLON.Vector4)
  19671. return BABYLON.Vector4.FromArray(split);
  19672. if (target instanceof BABYLON.Color3)
  19673. return BABYLON.Color3.FromArray(split);
  19674. if (target instanceof BABYLON.Color4)
  19675. return BABYLON.Color4.FromArray(split);
  19676. return parseFloat(values[0]);
  19677. };
  19678. // traverse graph per trigger
  19679. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19680. if (combineArray === void 0) { combineArray = null; }
  19681. if (parsedAction.detached)
  19682. return;
  19683. var parameters = new Array();
  19684. var target = null;
  19685. var propertyPath = null;
  19686. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19687. // Parameters
  19688. if (parsedAction.type === 2)
  19689. parameters.push(actionManager);
  19690. else
  19691. parameters.push(trigger);
  19692. if (combine) {
  19693. var actions = new Array();
  19694. for (var j = 0; j < parsedAction.combine.length; j++) {
  19695. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19696. }
  19697. parameters.push(actions);
  19698. }
  19699. else {
  19700. for (var i = 0; i < parsedAction.properties.length; i++) {
  19701. var value = parsedAction.properties[i].value;
  19702. var name = parsedAction.properties[i].name;
  19703. if (name === "target")
  19704. value = target = scene.getNodeByName(value);
  19705. else if (name === "parent")
  19706. value = scene.getNodeByName(value);
  19707. else if (name === "sound")
  19708. value = scene.getSoundByName(value);
  19709. else if (name !== "propertyPath") {
  19710. if (parsedAction.type === 2 && name === "operator")
  19711. value = BABYLON.ValueCondition[value];
  19712. else
  19713. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19714. }
  19715. else {
  19716. propertyPath = value;
  19717. }
  19718. parameters.push(value);
  19719. }
  19720. }
  19721. parameters.push(condition);
  19722. // If interpolate value action
  19723. if (parsedAction.name === "InterpolateValueAction") {
  19724. var param = parameters[parameters.length - 2];
  19725. parameters[parameters.length - 1] = param;
  19726. parameters[parameters.length - 2] = condition;
  19727. }
  19728. // Action or condition(s) and not CombineAction
  19729. var newAction = instanciate(parsedAction.name, parameters);
  19730. if (combineArray === null) {
  19731. if (newAction instanceof BABYLON.Condition) {
  19732. condition = newAction;
  19733. newAction = action;
  19734. }
  19735. else {
  19736. condition = null;
  19737. if (action)
  19738. action.then(newAction);
  19739. else
  19740. actionManager.registerAction(newAction);
  19741. }
  19742. }
  19743. else {
  19744. combineArray.push(newAction);
  19745. }
  19746. for (var i = 0; i < parsedAction.children.length; i++)
  19747. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19748. };
  19749. for (var i = 0; i < parsedActions.children.length; i++) {
  19750. var triggerParams;
  19751. var trigger = parsedActions.children[i];
  19752. if (trigger.properties.length > 0) {
  19753. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19754. }
  19755. else
  19756. triggerParams = BABYLON.ActionManager[trigger.name];
  19757. for (var j = 0; j < trigger.children.length; j++) {
  19758. if (!trigger.detached)
  19759. traverse(trigger.children[j], triggerParams, null, null);
  19760. }
  19761. }
  19762. };
  19763. var parseSound = function (parsedSound, scene, rootUrl) {
  19764. var soundName = parsedSound.name;
  19765. var soundUrl = rootUrl + soundName;
  19766. var options = {
  19767. autoplay: parsedSound.autoplay,
  19768. loop: parsedSound.loop,
  19769. volume: parsedSound.volume,
  19770. spatialSound: parsedSound.spatialSound,
  19771. maxDistance: parsedSound.maxDistance,
  19772. rolloffFactor: parsedSound.rolloffFactor,
  19773. refDistance: parsedSound.refDistance,
  19774. distanceModel: parsedSound.distanceModel,
  19775. playbackRate: parsedSound.playbackRate
  19776. };
  19777. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19778. scene._removePendingData(newSound);
  19779. }, options);
  19780. scene._addPendingData(newSound);
  19781. if (parsedSound.position) {
  19782. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19783. newSound.setPosition(soundPosition);
  19784. }
  19785. if (parsedSound.isDirectional) {
  19786. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19787. if (parsedSound.localDirectionToMesh) {
  19788. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19789. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19790. }
  19791. }
  19792. if (parsedSound.connectedMeshId) {
  19793. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19794. if (connectedMesh) {
  19795. newSound.attachToMesh(connectedMesh);
  19796. }
  19797. }
  19798. };
  19799. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19800. names = (names instanceof Array) ? names : [names];
  19801. for (var i in names) {
  19802. if (mesh.name === names[i]) {
  19803. hierarchyIds.push(mesh.id);
  19804. return true;
  19805. }
  19806. }
  19807. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19808. hierarchyIds.push(mesh.id);
  19809. return true;
  19810. }
  19811. return false;
  19812. };
  19813. var importVertexData = function (parsedVertexData, geometry) {
  19814. var vertexData = new BABYLON.VertexData();
  19815. // positions
  19816. var positions = parsedVertexData.positions;
  19817. if (positions) {
  19818. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19819. }
  19820. // normals
  19821. var normals = parsedVertexData.normals;
  19822. if (normals) {
  19823. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19824. }
  19825. // uvs
  19826. var uvs = parsedVertexData.uvs;
  19827. if (uvs) {
  19828. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19829. }
  19830. // uv2s
  19831. var uv2s = parsedVertexData.uv2s;
  19832. if (uv2s) {
  19833. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19834. }
  19835. // colors
  19836. var colors = parsedVertexData.colors;
  19837. if (colors) {
  19838. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19839. }
  19840. // matricesIndices
  19841. var matricesIndices = parsedVertexData.matricesIndices;
  19842. if (matricesIndices) {
  19843. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19844. }
  19845. // matricesWeights
  19846. var matricesWeights = parsedVertexData.matricesWeights;
  19847. if (matricesWeights) {
  19848. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19849. }
  19850. // indices
  19851. var indices = parsedVertexData.indices;
  19852. if (indices) {
  19853. vertexData.indices = indices;
  19854. }
  19855. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19856. };
  19857. var importGeometry = function (parsedGeometry, mesh) {
  19858. var scene = mesh.getScene();
  19859. // Geometry
  19860. var geometryId = parsedGeometry.geometryId;
  19861. if (geometryId) {
  19862. var geometry = scene.getGeometryByID(geometryId);
  19863. if (geometry) {
  19864. geometry.applyToMesh(mesh);
  19865. }
  19866. }
  19867. else if (parsedGeometry instanceof ArrayBuffer) {
  19868. var binaryInfo = mesh._binaryInfo;
  19869. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19870. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19871. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19872. }
  19873. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19874. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19875. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19876. }
  19877. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19878. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19879. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19880. }
  19881. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19882. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19883. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19884. }
  19885. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19886. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19887. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19888. }
  19889. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19890. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19891. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19892. }
  19893. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19894. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19895. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19896. }
  19897. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19898. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19899. mesh.setIndices(indicesData);
  19900. }
  19901. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19902. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19903. mesh.subMeshes = [];
  19904. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19905. var materialIndex = subMeshesData[(i * 5) + 0];
  19906. var verticesStart = subMeshesData[(i * 5) + 1];
  19907. var verticesCount = subMeshesData[(i * 5) + 2];
  19908. var indexStart = subMeshesData[(i * 5) + 3];
  19909. var indexCount = subMeshesData[(i * 5) + 4];
  19910. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19911. }
  19912. }
  19913. }
  19914. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19915. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19916. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19917. if (parsedGeometry.uvs) {
  19918. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19919. }
  19920. if (parsedGeometry.uvs2) {
  19921. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19922. }
  19923. if (parsedGeometry.colors) {
  19924. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19925. }
  19926. if (parsedGeometry.matricesIndices) {
  19927. if (!parsedGeometry.matricesIndices._isExpanded) {
  19928. var floatIndices = [];
  19929. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19930. var matricesIndex = parsedGeometry.matricesIndices[i];
  19931. floatIndices.push(matricesIndex & 0x000000FF);
  19932. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19933. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19934. floatIndices.push(matricesIndex >> 24);
  19935. }
  19936. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19937. }
  19938. else {
  19939. delete parsedGeometry.matricesIndices._isExpanded;
  19940. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19941. }
  19942. }
  19943. if (parsedGeometry.matricesWeights) {
  19944. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19945. }
  19946. mesh.setIndices(parsedGeometry.indices);
  19947. // SubMeshes
  19948. if (parsedGeometry.subMeshes) {
  19949. mesh.subMeshes = [];
  19950. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19951. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19952. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19953. }
  19954. }
  19955. }
  19956. // Flat shading
  19957. if (mesh._shouldGenerateFlatShading) {
  19958. mesh.convertToFlatShadedMesh();
  19959. delete mesh._shouldGenerateFlatShading;
  19960. }
  19961. // Update
  19962. mesh.computeWorldMatrix(true);
  19963. // Octree
  19964. if (scene._selectionOctree) {
  19965. scene._selectionOctree.addMesh(mesh);
  19966. }
  19967. };
  19968. BABYLON.SceneLoader.RegisterPlugin({
  19969. extensions: ".babylon",
  19970. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19971. var parsedData = JSON.parse(data);
  19972. var loadedSkeletonsIds = [];
  19973. var loadedMaterialsIds = [];
  19974. var hierarchyIds = [];
  19975. for (var index = 0; index < parsedData.meshes.length; index++) {
  19976. var parsedMesh = parsedData.meshes[index];
  19977. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19978. if (meshesNames instanceof Array) {
  19979. // Remove found mesh name from list.
  19980. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19981. }
  19982. // Material ?
  19983. if (parsedMesh.materialId) {
  19984. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19985. if (!materialFound) {
  19986. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19987. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19988. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19989. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19990. var subMatId = parsedMultiMaterial.materials[matIndex];
  19991. loadedMaterialsIds.push(subMatId);
  19992. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19993. }
  19994. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19995. parseMultiMaterial(parsedMultiMaterial, scene);
  19996. materialFound = true;
  19997. break;
  19998. }
  19999. }
  20000. }
  20001. if (!materialFound) {
  20002. loadedMaterialsIds.push(parsedMesh.materialId);
  20003. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20004. }
  20005. }
  20006. // Skeleton ?
  20007. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20008. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20009. if (!skeletonAlreadyLoaded) {
  20010. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20011. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20012. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20013. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20014. loadedSkeletonsIds.push(parsedSkeleton.id);
  20015. }
  20016. }
  20017. }
  20018. }
  20019. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20020. meshes.push(mesh);
  20021. }
  20022. }
  20023. for (index = 0; index < scene.meshes.length; index++) {
  20024. var currentMesh = scene.meshes[index];
  20025. if (currentMesh._waitingParentId) {
  20026. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20027. currentMesh._waitingParentId = undefined;
  20028. }
  20029. }
  20030. // Particles
  20031. if (parsedData.particleSystems) {
  20032. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20033. var parsedParticleSystem = parsedData.particleSystems[index];
  20034. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20035. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20036. }
  20037. }
  20038. }
  20039. return true;
  20040. },
  20041. load: function (scene, data, rootUrl) {
  20042. var parsedData = JSON.parse(data);
  20043. // Scene
  20044. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20045. scene.autoClear = parsedData.autoClear;
  20046. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20047. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20048. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20049. // Fog
  20050. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20051. scene.fogMode = parsedData.fogMode;
  20052. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20053. scene.fogStart = parsedData.fogStart;
  20054. scene.fogEnd = parsedData.fogEnd;
  20055. scene.fogDensity = parsedData.fogDensity;
  20056. }
  20057. for (var index = 0; index < parsedData.lights.length; index++) {
  20058. var parsedLight = parsedData.lights[index];
  20059. parseLight(parsedLight, scene);
  20060. }
  20061. // Materials
  20062. if (parsedData.materials) {
  20063. for (index = 0; index < parsedData.materials.length; index++) {
  20064. var parsedMaterial = parsedData.materials[index];
  20065. parseMaterial(parsedMaterial, scene, rootUrl);
  20066. }
  20067. }
  20068. if (parsedData.multiMaterials) {
  20069. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20070. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20071. parseMultiMaterial(parsedMultiMaterial, scene);
  20072. }
  20073. }
  20074. // Skeletons
  20075. if (parsedData.skeletons) {
  20076. for (index = 0; index < parsedData.skeletons.length; index++) {
  20077. var parsedSkeleton = parsedData.skeletons[index];
  20078. parseSkeleton(parsedSkeleton, scene);
  20079. }
  20080. }
  20081. // Geometries
  20082. var geometries = parsedData.geometries;
  20083. if (geometries) {
  20084. // Boxes
  20085. var boxes = geometries.boxes;
  20086. if (boxes) {
  20087. for (index = 0; index < boxes.length; index++) {
  20088. var parsedBox = boxes[index];
  20089. parseBox(parsedBox, scene);
  20090. }
  20091. }
  20092. // Spheres
  20093. var spheres = geometries.spheres;
  20094. if (spheres) {
  20095. for (index = 0; index < spheres.length; index++) {
  20096. var parsedSphere = spheres[index];
  20097. parseSphere(parsedSphere, scene);
  20098. }
  20099. }
  20100. // Cylinders
  20101. var cylinders = geometries.cylinders;
  20102. if (cylinders) {
  20103. for (index = 0; index < cylinders.length; index++) {
  20104. var parsedCylinder = cylinders[index];
  20105. parseCylinder(parsedCylinder, scene);
  20106. }
  20107. }
  20108. // Toruses
  20109. var toruses = geometries.toruses;
  20110. if (toruses) {
  20111. for (index = 0; index < toruses.length; index++) {
  20112. var parsedTorus = toruses[index];
  20113. parseTorus(parsedTorus, scene);
  20114. }
  20115. }
  20116. // Grounds
  20117. var grounds = geometries.grounds;
  20118. if (grounds) {
  20119. for (index = 0; index < grounds.length; index++) {
  20120. var parsedGround = grounds[index];
  20121. parseGround(parsedGround, scene);
  20122. }
  20123. }
  20124. // Planes
  20125. var planes = geometries.planes;
  20126. if (planes) {
  20127. for (index = 0; index < planes.length; index++) {
  20128. var parsedPlane = planes[index];
  20129. parsePlane(parsedPlane, scene);
  20130. }
  20131. }
  20132. // TorusKnots
  20133. var torusKnots = geometries.torusKnots;
  20134. if (torusKnots) {
  20135. for (index = 0; index < torusKnots.length; index++) {
  20136. var parsedTorusKnot = torusKnots[index];
  20137. parseTorusKnot(parsedTorusKnot, scene);
  20138. }
  20139. }
  20140. // VertexData
  20141. var vertexData = geometries.vertexData;
  20142. if (vertexData) {
  20143. for (index = 0; index < vertexData.length; index++) {
  20144. var parsedVertexData = vertexData[index];
  20145. parseVertexData(parsedVertexData, scene, rootUrl);
  20146. }
  20147. }
  20148. }
  20149. for (index = 0; index < parsedData.meshes.length; index++) {
  20150. var parsedMesh = parsedData.meshes[index];
  20151. parseMesh(parsedMesh, scene, rootUrl);
  20152. }
  20153. for (index = 0; index < parsedData.cameras.length; index++) {
  20154. var parsedCamera = parsedData.cameras[index];
  20155. parseCamera(parsedCamera, scene);
  20156. }
  20157. if (parsedData.activeCameraID) {
  20158. scene.setActiveCameraByID(parsedData.activeCameraID);
  20159. }
  20160. for (index = 0; index < scene.cameras.length; index++) {
  20161. var camera = scene.cameras[index];
  20162. if (camera._waitingParentId) {
  20163. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20164. camera._waitingParentId = undefined;
  20165. }
  20166. }
  20167. for (index = 0; index < scene.lights.length; index++) {
  20168. var light = scene.lights[index];
  20169. if (light._waitingParentId) {
  20170. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20171. light._waitingParentId = undefined;
  20172. }
  20173. }
  20174. // Sounds
  20175. if (parsedData.sounds) {
  20176. for (index = 0; index < parsedData.sounds.length; index++) {
  20177. var parsedSound = parsedData.sounds[index];
  20178. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20179. parseSound(parsedSound, scene, rootUrl);
  20180. }
  20181. else {
  20182. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20183. }
  20184. }
  20185. }
  20186. for (index = 0; index < scene.meshes.length; index++) {
  20187. var mesh = scene.meshes[index];
  20188. if (mesh._waitingParentId) {
  20189. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20190. mesh._waitingParentId = undefined;
  20191. }
  20192. if (mesh._waitingActions) {
  20193. parseActions(mesh._waitingActions, mesh, scene);
  20194. mesh._waitingActions = undefined;
  20195. }
  20196. }
  20197. // Particles Systems
  20198. if (parsedData.particleSystems) {
  20199. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20200. var parsedParticleSystem = parsedData.particleSystems[index];
  20201. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20202. }
  20203. }
  20204. // Lens flares
  20205. if (parsedData.lensFlareSystems) {
  20206. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20207. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20208. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20209. }
  20210. }
  20211. // Shadows
  20212. if (parsedData.shadowGenerators) {
  20213. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20214. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20215. parseShadowGenerator(parsedShadowGenerator, scene);
  20216. }
  20217. }
  20218. // Actions (scene)
  20219. if (parsedData.actions) {
  20220. parseActions(parsedData.actions, null, scene);
  20221. }
  20222. // Finish
  20223. return true;
  20224. }
  20225. });
  20226. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20227. })(BABYLON || (BABYLON = {}));
  20228. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20229. (function (BABYLON) {
  20230. // Unique ID when we import meshes from Babylon to CSG
  20231. var currentCSGMeshId = 0;
  20232. // # class Vertex
  20233. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20234. // one to provide additional features like texture coordinates and vertex
  20235. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20236. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20237. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20238. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20239. // is not used anywhere else.
  20240. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20241. var Vertex = (function () {
  20242. function Vertex(pos, normal, uv) {
  20243. this.pos = pos;
  20244. this.normal = normal;
  20245. this.uv = uv;
  20246. }
  20247. Vertex.prototype.clone = function () {
  20248. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20249. };
  20250. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20251. // orientation of a polygon is flipped.
  20252. Vertex.prototype.flip = function () {
  20253. this.normal = this.normal.scale(-1);
  20254. };
  20255. // Create a new vertex between this vertex and `other` by linearly
  20256. // interpolating all properties using a parameter of `t`. Subclasses should
  20257. // override this to interpolate additional properties.
  20258. Vertex.prototype.interpolate = function (other, t) {
  20259. 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));
  20260. };
  20261. return Vertex;
  20262. })();
  20263. // # class Plane
  20264. // Represents a plane in 3D space.
  20265. var Plane = (function () {
  20266. function Plane(normal, w) {
  20267. this.normal = normal;
  20268. this.w = w;
  20269. }
  20270. Plane.FromPoints = function (a, b, c) {
  20271. var v0 = c.subtract(a);
  20272. var v1 = b.subtract(a);
  20273. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20274. return null;
  20275. }
  20276. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20277. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20278. };
  20279. Plane.prototype.clone = function () {
  20280. return new Plane(this.normal.clone(), this.w);
  20281. };
  20282. Plane.prototype.flip = function () {
  20283. this.normal.scaleInPlace(-1);
  20284. this.w = -this.w;
  20285. };
  20286. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20287. // fragments in the appropriate lists. Coplanar polygons go into either
  20288. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20289. // respect to this plane. Polygons in front or in back of this plane go into
  20290. // either `front` or `back`.
  20291. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20292. var COPLANAR = 0;
  20293. var FRONT = 1;
  20294. var BACK = 2;
  20295. var SPANNING = 3;
  20296. // Classify each point as well as the entire polygon into one of the above
  20297. // four classes.
  20298. var polygonType = 0;
  20299. var types = [];
  20300. for (var i = 0; i < polygon.vertices.length; i++) {
  20301. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20302. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20303. polygonType |= type;
  20304. types.push(type);
  20305. }
  20306. switch (polygonType) {
  20307. case COPLANAR:
  20308. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20309. break;
  20310. case FRONT:
  20311. front.push(polygon);
  20312. break;
  20313. case BACK:
  20314. back.push(polygon);
  20315. break;
  20316. case SPANNING:
  20317. var f = [], b = [];
  20318. for (i = 0; i < polygon.vertices.length; i++) {
  20319. var j = (i + 1) % polygon.vertices.length;
  20320. var ti = types[i], tj = types[j];
  20321. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20322. if (ti != BACK)
  20323. f.push(vi);
  20324. if (ti != FRONT)
  20325. b.push(ti != BACK ? vi.clone() : vi);
  20326. if ((ti | tj) == SPANNING) {
  20327. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20328. var v = vi.interpolate(vj, t);
  20329. f.push(v);
  20330. b.push(v.clone());
  20331. }
  20332. }
  20333. if (f.length >= 3) {
  20334. var poly = new Polygon(f, polygon.shared);
  20335. if (poly.plane)
  20336. front.push(poly);
  20337. }
  20338. if (b.length >= 3) {
  20339. poly = new Polygon(b, polygon.shared);
  20340. if (poly.plane)
  20341. back.push(poly);
  20342. }
  20343. break;
  20344. }
  20345. };
  20346. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20347. // point is on the plane.
  20348. Plane.EPSILON = 1e-5;
  20349. return Plane;
  20350. })();
  20351. // # class Polygon
  20352. // Represents a convex polygon. The vertices used to initialize a polygon must
  20353. // be coplanar and form a convex loop.
  20354. //
  20355. // Each convex polygon has a `shared` property, which is shared between all
  20356. // polygons that are clones of each other or were split from the same polygon.
  20357. // This can be used to define per-polygon properties (such as surface color).
  20358. var Polygon = (function () {
  20359. function Polygon(vertices, shared) {
  20360. this.vertices = vertices;
  20361. this.shared = shared;
  20362. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20363. }
  20364. Polygon.prototype.clone = function () {
  20365. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20366. return new Polygon(vertices, this.shared);
  20367. };
  20368. Polygon.prototype.flip = function () {
  20369. this.vertices.reverse().map(function (v) {
  20370. v.flip();
  20371. });
  20372. this.plane.flip();
  20373. };
  20374. return Polygon;
  20375. })();
  20376. // # class Node
  20377. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20378. // by picking a polygon to split along. That polygon (and all other coplanar
  20379. // polygons) are added directly to that node and the other polygons are added to
  20380. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20381. // no distinction between internal and leaf nodes.
  20382. var Node = (function () {
  20383. function Node(polygons) {
  20384. this.plane = null;
  20385. this.front = null;
  20386. this.back = null;
  20387. this.polygons = [];
  20388. if (polygons) {
  20389. this.build(polygons);
  20390. }
  20391. }
  20392. Node.prototype.clone = function () {
  20393. var node = new Node();
  20394. node.plane = this.plane && this.plane.clone();
  20395. node.front = this.front && this.front.clone();
  20396. node.back = this.back && this.back.clone();
  20397. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20398. return node;
  20399. };
  20400. // Convert solid space to empty space and empty space to solid space.
  20401. Node.prototype.invert = function () {
  20402. for (var i = 0; i < this.polygons.length; i++) {
  20403. this.polygons[i].flip();
  20404. }
  20405. if (this.plane) {
  20406. this.plane.flip();
  20407. }
  20408. if (this.front) {
  20409. this.front.invert();
  20410. }
  20411. if (this.back) {
  20412. this.back.invert();
  20413. }
  20414. var temp = this.front;
  20415. this.front = this.back;
  20416. this.back = temp;
  20417. };
  20418. // Recursively remove all polygons in `polygons` that are inside this BSP
  20419. // tree.
  20420. Node.prototype.clipPolygons = function (polygons) {
  20421. if (!this.plane)
  20422. return polygons.slice();
  20423. var front = [], back = [];
  20424. for (var i = 0; i < polygons.length; i++) {
  20425. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20426. }
  20427. if (this.front) {
  20428. front = this.front.clipPolygons(front);
  20429. }
  20430. if (this.back) {
  20431. back = this.back.clipPolygons(back);
  20432. }
  20433. else {
  20434. back = [];
  20435. }
  20436. return front.concat(back);
  20437. };
  20438. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20439. // `bsp`.
  20440. Node.prototype.clipTo = function (bsp) {
  20441. this.polygons = bsp.clipPolygons(this.polygons);
  20442. if (this.front)
  20443. this.front.clipTo(bsp);
  20444. if (this.back)
  20445. this.back.clipTo(bsp);
  20446. };
  20447. // Return a list of all polygons in this BSP tree.
  20448. Node.prototype.allPolygons = function () {
  20449. var polygons = this.polygons.slice();
  20450. if (this.front)
  20451. polygons = polygons.concat(this.front.allPolygons());
  20452. if (this.back)
  20453. polygons = polygons.concat(this.back.allPolygons());
  20454. return polygons;
  20455. };
  20456. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20457. // new polygons are filtered down to the bottom of the tree and become new
  20458. // nodes there. Each set of polygons is partitioned using the first polygon
  20459. // (no heuristic is used to pick a good split).
  20460. Node.prototype.build = function (polygons) {
  20461. if (!polygons.length)
  20462. return;
  20463. if (!this.plane)
  20464. this.plane = polygons[0].plane.clone();
  20465. var front = [], back = [];
  20466. for (var i = 0; i < polygons.length; i++) {
  20467. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20468. }
  20469. if (front.length) {
  20470. if (!this.front)
  20471. this.front = new Node();
  20472. this.front.build(front);
  20473. }
  20474. if (back.length) {
  20475. if (!this.back)
  20476. this.back = new Node();
  20477. this.back.build(back);
  20478. }
  20479. };
  20480. return Node;
  20481. })();
  20482. var CSG = (function () {
  20483. function CSG() {
  20484. this.polygons = new Array();
  20485. }
  20486. // Convert BABYLON.Mesh to BABYLON.CSG
  20487. CSG.FromMesh = function (mesh) {
  20488. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20489. if (mesh instanceof BABYLON.Mesh) {
  20490. mesh.computeWorldMatrix(true);
  20491. var matrix = mesh.getWorldMatrix();
  20492. var meshPosition = mesh.position.clone();
  20493. var meshRotation = mesh.rotation.clone();
  20494. var meshScaling = mesh.scaling.clone();
  20495. }
  20496. else {
  20497. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20498. }
  20499. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20500. var subMeshes = mesh.subMeshes;
  20501. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20502. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20503. vertices = [];
  20504. for (var j = 0; j < 3; j++) {
  20505. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20506. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20507. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20508. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20509. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20510. vertex = new Vertex(position, normal, uv);
  20511. vertices.push(vertex);
  20512. }
  20513. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20514. // To handle the case of degenerated triangle
  20515. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20516. if (polygon.plane)
  20517. polygons.push(polygon);
  20518. }
  20519. }
  20520. var csg = CSG.FromPolygons(polygons);
  20521. csg.matrix = matrix;
  20522. csg.position = meshPosition;
  20523. csg.rotation = meshRotation;
  20524. csg.scaling = meshScaling;
  20525. currentCSGMeshId++;
  20526. return csg;
  20527. };
  20528. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20529. CSG.FromPolygons = function (polygons) {
  20530. var csg = new BABYLON.CSG();
  20531. csg.polygons = polygons;
  20532. return csg;
  20533. };
  20534. CSG.prototype.clone = function () {
  20535. var csg = new BABYLON.CSG();
  20536. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20537. csg.copyTransformAttributes(this);
  20538. return csg;
  20539. };
  20540. CSG.prototype.toPolygons = function () {
  20541. return this.polygons;
  20542. };
  20543. CSG.prototype.union = function (csg) {
  20544. var a = new Node(this.clone().polygons);
  20545. var b = new Node(csg.clone().polygons);
  20546. a.clipTo(b);
  20547. b.clipTo(a);
  20548. b.invert();
  20549. b.clipTo(a);
  20550. b.invert();
  20551. a.build(b.allPolygons());
  20552. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20553. };
  20554. CSG.prototype.unionInPlace = function (csg) {
  20555. var a = new Node(this.polygons);
  20556. var b = new Node(csg.polygons);
  20557. a.clipTo(b);
  20558. b.clipTo(a);
  20559. b.invert();
  20560. b.clipTo(a);
  20561. b.invert();
  20562. a.build(b.allPolygons());
  20563. this.polygons = a.allPolygons();
  20564. };
  20565. CSG.prototype.subtract = function (csg) {
  20566. var a = new Node(this.clone().polygons);
  20567. var b = new Node(csg.clone().polygons);
  20568. a.invert();
  20569. a.clipTo(b);
  20570. b.clipTo(a);
  20571. b.invert();
  20572. b.clipTo(a);
  20573. b.invert();
  20574. a.build(b.allPolygons());
  20575. a.invert();
  20576. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20577. };
  20578. CSG.prototype.subtractInPlace = function (csg) {
  20579. var a = new Node(this.polygons);
  20580. var b = new Node(csg.polygons);
  20581. a.invert();
  20582. a.clipTo(b);
  20583. b.clipTo(a);
  20584. b.invert();
  20585. b.clipTo(a);
  20586. b.invert();
  20587. a.build(b.allPolygons());
  20588. a.invert();
  20589. this.polygons = a.allPolygons();
  20590. };
  20591. CSG.prototype.intersect = function (csg) {
  20592. var a = new Node(this.clone().polygons);
  20593. var b = new Node(csg.clone().polygons);
  20594. a.invert();
  20595. b.clipTo(a);
  20596. b.invert();
  20597. a.clipTo(b);
  20598. b.clipTo(a);
  20599. a.build(b.allPolygons());
  20600. a.invert();
  20601. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20602. };
  20603. CSG.prototype.intersectInPlace = function (csg) {
  20604. var a = new Node(this.polygons);
  20605. var b = new Node(csg.polygons);
  20606. a.invert();
  20607. b.clipTo(a);
  20608. b.invert();
  20609. a.clipTo(b);
  20610. b.clipTo(a);
  20611. a.build(b.allPolygons());
  20612. a.invert();
  20613. this.polygons = a.allPolygons();
  20614. };
  20615. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20616. // not modified.
  20617. CSG.prototype.inverse = function () {
  20618. var csg = this.clone();
  20619. csg.inverseInPlace();
  20620. return csg;
  20621. };
  20622. CSG.prototype.inverseInPlace = function () {
  20623. this.polygons.map(function (p) {
  20624. p.flip();
  20625. });
  20626. };
  20627. // This is used to keep meshes transformations so they can be restored
  20628. // when we build back a Babylon Mesh
  20629. // NB : All CSG operations are performed in world coordinates
  20630. CSG.prototype.copyTransformAttributes = function (csg) {
  20631. this.matrix = csg.matrix;
  20632. this.position = csg.position;
  20633. this.rotation = csg.rotation;
  20634. this.scaling = csg.scaling;
  20635. return this;
  20636. };
  20637. // Build Raw mesh from CSG
  20638. // Coordinates here are in world space
  20639. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20640. var matrix = this.matrix.clone();
  20641. matrix.invert();
  20642. 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;
  20643. if (keepSubMeshes) {
  20644. // Sort Polygons, since subMeshes are indices range
  20645. polygons.sort(function (a, b) {
  20646. if (a.shared.meshId === b.shared.meshId) {
  20647. return a.shared.subMeshId - b.shared.subMeshId;
  20648. }
  20649. else {
  20650. return a.shared.meshId - b.shared.meshId;
  20651. }
  20652. });
  20653. }
  20654. for (var i = 0, il = polygons.length; i < il; i++) {
  20655. polygon = polygons[i];
  20656. // Building SubMeshes
  20657. if (!subMesh_dict[polygon.shared.meshId]) {
  20658. subMesh_dict[polygon.shared.meshId] = {};
  20659. }
  20660. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20661. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20662. indexStart: +Infinity,
  20663. indexEnd: -Infinity,
  20664. materialIndex: polygon.shared.materialIndex
  20665. };
  20666. }
  20667. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20668. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20669. polygonIndices[0] = 0;
  20670. polygonIndices[1] = j - 1;
  20671. polygonIndices[2] = j;
  20672. for (var k = 0; k < 3; k++) {
  20673. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20674. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20675. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20676. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20677. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20678. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20679. // Check if 2 points can be merged
  20680. 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)) {
  20681. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20682. uvs.push(uv.x, uv.y);
  20683. normals.push(normal.x, normal.y, normal.z);
  20684. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20685. }
  20686. indices.push(vertex_idx);
  20687. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20688. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20689. currentIndex++;
  20690. }
  20691. }
  20692. }
  20693. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20694. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20695. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20696. mesh.setIndices(indices);
  20697. if (keepSubMeshes) {
  20698. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20699. var materialIndexOffset = 0, materialMaxIndex;
  20700. mesh.subMeshes.length = 0;
  20701. for (var m in subMesh_dict) {
  20702. materialMaxIndex = -1;
  20703. for (var sm in subMesh_dict[m]) {
  20704. subMesh_obj = subMesh_dict[m][sm];
  20705. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20706. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20707. }
  20708. materialIndexOffset += ++materialMaxIndex;
  20709. }
  20710. }
  20711. return mesh;
  20712. };
  20713. // Build Mesh from CSG taking material and transforms into account
  20714. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20715. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20716. mesh.material = material;
  20717. mesh.position.copyFrom(this.position);
  20718. mesh.rotation.copyFrom(this.rotation);
  20719. mesh.scaling.copyFrom(this.scaling);
  20720. mesh.computeWorldMatrix(true);
  20721. return mesh;
  20722. };
  20723. return CSG;
  20724. })();
  20725. BABYLON.CSG = CSG;
  20726. })(BABYLON || (BABYLON = {}));
  20727. //# sourceMappingURL=babylon.csg.js.map
  20728. var BABYLON;
  20729. (function (BABYLON) {
  20730. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20731. __extends(OculusDistortionCorrectionPostProcess, _super);
  20732. //ANY
  20733. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20734. var _this = this;
  20735. _super.call(this, name, "oculusDistortionCorrection", [
  20736. 'LensCenter',
  20737. 'Scale',
  20738. 'ScaleIn',
  20739. 'HmdWarpParam'
  20740. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20741. this._isRightEye = isRightEye;
  20742. this._distortionFactors = cameraSettings.DistortionK;
  20743. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20744. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20745. this.onSizeChanged = function () {
  20746. _this.aspectRatio = _this.width * .5 / _this.height;
  20747. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20748. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20749. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20750. };
  20751. this.onApply = function (effect) {
  20752. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20753. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20754. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20755. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20756. };
  20757. }
  20758. return OculusDistortionCorrectionPostProcess;
  20759. })(BABYLON.PostProcess);
  20760. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20761. })(BABYLON || (BABYLON = {}));
  20762. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20763. // 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
  20764. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20765. var BABYLON;
  20766. (function (BABYLON) {
  20767. (function (JoystickAxis) {
  20768. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20769. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20770. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20771. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20772. var JoystickAxis = BABYLON.JoystickAxis;
  20773. var VirtualJoystick = (function () {
  20774. function VirtualJoystick(leftJoystick) {
  20775. var _this = this;
  20776. if (leftJoystick) {
  20777. this._leftJoystick = true;
  20778. }
  20779. else {
  20780. this._leftJoystick = false;
  20781. }
  20782. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20783. VirtualJoystick._globalJoystickIndex++;
  20784. // By default left & right arrow keys are moving the X
  20785. // and up & down keys are moving the Y
  20786. this._axisTargetedByLeftAndRight = 0 /* X */;
  20787. this._axisTargetedByUpAndDown = 1 /* Y */;
  20788. this.reverseLeftRight = false;
  20789. this.reverseUpDown = false;
  20790. // collections of pointers
  20791. this._touches = new BABYLON.VirtualJoystick.Collection();
  20792. this.deltaPosition = BABYLON.Vector3.Zero();
  20793. this._joystickSensibility = 25;
  20794. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20795. this._rotationSpeed = 25;
  20796. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20797. this._rotateOnAxisRelativeToMesh = false;
  20798. // injecting a canvas element on top of the canvas 3D game
  20799. if (!VirtualJoystick.vjCanvas) {
  20800. window.addEventListener("resize", function () {
  20801. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20802. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20803. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20804. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20805. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20806. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20807. }, false);
  20808. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20809. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20810. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20811. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20812. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20813. VirtualJoystick.vjCanvas.style.width = "100%";
  20814. VirtualJoystick.vjCanvas.style.height = "100%";
  20815. VirtualJoystick.vjCanvas.style.position = "absolute";
  20816. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20817. VirtualJoystick.vjCanvas.style.top = "0px";
  20818. VirtualJoystick.vjCanvas.style.left = "0px";
  20819. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20820. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20821. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20822. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20823. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20824. document.body.appendChild(VirtualJoystick.vjCanvas);
  20825. }
  20826. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20827. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20828. this.pressed = false;
  20829. // default joystick color
  20830. this._joystickColor = "cyan";
  20831. this._joystickPointerID = -1;
  20832. // current joystick position
  20833. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20834. // origin joystick position
  20835. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20836. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20837. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20838. _this._onPointerDown(evt);
  20839. }, false);
  20840. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20841. _this._onPointerMove(evt);
  20842. }, false);
  20843. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20844. _this._onPointerUp(evt);
  20845. }, false);
  20846. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20847. _this._onPointerUp(evt);
  20848. }, false);
  20849. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20850. evt.preventDefault(); // Disables system menu
  20851. }, false);
  20852. requestAnimationFrame(function () {
  20853. _this._drawVirtualJoystick();
  20854. });
  20855. }
  20856. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20857. this._joystickSensibility = newJoystickSensibility;
  20858. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20859. };
  20860. VirtualJoystick.prototype._onPointerDown = function (e) {
  20861. var positionOnScreenCondition;
  20862. e.preventDefault();
  20863. if (this._leftJoystick === true) {
  20864. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20865. }
  20866. else {
  20867. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20868. }
  20869. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20870. // First contact will be dedicated to the virtual joystick
  20871. this._joystickPointerID = e.pointerId;
  20872. this._joystickPointerStartPos.x = e.clientX;
  20873. this._joystickPointerStartPos.y = e.clientY;
  20874. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20875. this._deltaJoystickVector.x = 0;
  20876. this._deltaJoystickVector.y = 0;
  20877. this.pressed = true;
  20878. this._touches.add(e.pointerId.toString(), e);
  20879. }
  20880. else {
  20881. // You can only trigger the action buttons with a joystick declared
  20882. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20883. this._action();
  20884. this._touches.add(e.pointerId.toString(), e);
  20885. }
  20886. }
  20887. };
  20888. VirtualJoystick.prototype._onPointerMove = function (e) {
  20889. // If the current pointer is the one associated to the joystick (first touch contact)
  20890. if (this._joystickPointerID == e.pointerId) {
  20891. this._joystickPointerPos.x = e.clientX;
  20892. this._joystickPointerPos.y = e.clientY;
  20893. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20894. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20895. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20896. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20897. switch (this._axisTargetedByLeftAndRight) {
  20898. case 0 /* X */:
  20899. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20900. break;
  20901. case 1 /* Y */:
  20902. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20903. break;
  20904. case 2 /* Z */:
  20905. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20906. break;
  20907. }
  20908. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20909. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20910. switch (this._axisTargetedByUpAndDown) {
  20911. case 0 /* X */:
  20912. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20913. break;
  20914. case 1 /* Y */:
  20915. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20916. break;
  20917. case 2 /* Z */:
  20918. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20919. break;
  20920. }
  20921. }
  20922. else {
  20923. if (this._touches.item(e.pointerId.toString())) {
  20924. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20925. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20926. }
  20927. }
  20928. };
  20929. VirtualJoystick.prototype._onPointerUp = function (e) {
  20930. this._clearCanvas();
  20931. if (this._joystickPointerID == e.pointerId) {
  20932. this._joystickPointerID = -1;
  20933. this.pressed = false;
  20934. }
  20935. this._deltaJoystickVector.x = 0;
  20936. this._deltaJoystickVector.y = 0;
  20937. this._touches.remove(e.pointerId.toString());
  20938. };
  20939. /**
  20940. * Change the color of the virtual joystick
  20941. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20942. */
  20943. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20944. this._joystickColor = newColor;
  20945. };
  20946. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20947. this._action = action;
  20948. };
  20949. // Define which axis you'd like to control for left & right
  20950. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20951. switch (axis) {
  20952. case 0 /* X */:
  20953. case 1 /* Y */:
  20954. case 2 /* Z */:
  20955. this._axisTargetedByLeftAndRight = axis;
  20956. break;
  20957. default:
  20958. this._axisTargetedByLeftAndRight = 0 /* X */;
  20959. break;
  20960. }
  20961. };
  20962. // Define which axis you'd like to control for up & down
  20963. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20964. switch (axis) {
  20965. case 0 /* X */:
  20966. case 1 /* Y */:
  20967. case 2 /* Z */:
  20968. this._axisTargetedByUpAndDown = axis;
  20969. break;
  20970. default:
  20971. this._axisTargetedByUpAndDown = 1 /* Y */;
  20972. break;
  20973. }
  20974. };
  20975. VirtualJoystick.prototype._clearCanvas = function () {
  20976. if (this._leftJoystick) {
  20977. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20978. }
  20979. else {
  20980. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20981. }
  20982. };
  20983. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20984. var _this = this;
  20985. if (this.pressed) {
  20986. this._clearCanvas();
  20987. this._touches.forEach(function (touch) {
  20988. if (touch.pointerId === _this._joystickPointerID) {
  20989. VirtualJoystick.vjCanvasContext.beginPath();
  20990. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20991. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20992. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20993. VirtualJoystick.vjCanvasContext.stroke();
  20994. VirtualJoystick.vjCanvasContext.beginPath();
  20995. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20996. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20997. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20998. VirtualJoystick.vjCanvasContext.stroke();
  20999. VirtualJoystick.vjCanvasContext.beginPath();
  21000. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21001. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21002. VirtualJoystick.vjCanvasContext.stroke();
  21003. }
  21004. else {
  21005. VirtualJoystick.vjCanvasContext.beginPath();
  21006. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21007. VirtualJoystick.vjCanvasContext.beginPath();
  21008. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21009. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21010. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21011. VirtualJoystick.vjCanvasContext.stroke();
  21012. }
  21013. ;
  21014. });
  21015. }
  21016. requestAnimationFrame(function () {
  21017. _this._drawVirtualJoystick();
  21018. });
  21019. };
  21020. VirtualJoystick.prototype.releaseCanvas = function () {
  21021. if (VirtualJoystick.vjCanvas) {
  21022. document.body.removeChild(VirtualJoystick.vjCanvas);
  21023. VirtualJoystick.vjCanvas = null;
  21024. }
  21025. };
  21026. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21027. VirtualJoystick._globalJoystickIndex = 0;
  21028. return VirtualJoystick;
  21029. })();
  21030. BABYLON.VirtualJoystick = VirtualJoystick;
  21031. })(BABYLON || (BABYLON = {}));
  21032. var BABYLON;
  21033. (function (BABYLON) {
  21034. var VirtualJoystick;
  21035. (function (VirtualJoystick) {
  21036. var Collection = (function () {
  21037. function Collection() {
  21038. this._count = 0;
  21039. this._collection = new Array();
  21040. }
  21041. Collection.prototype.Count = function () {
  21042. return this._count;
  21043. };
  21044. Collection.prototype.add = function (key, item) {
  21045. if (this._collection[key] != undefined) {
  21046. return undefined;
  21047. }
  21048. this._collection[key] = item;
  21049. return ++this._count;
  21050. };
  21051. Collection.prototype.remove = function (key) {
  21052. if (this._collection[key] == undefined) {
  21053. return undefined;
  21054. }
  21055. delete this._collection[key];
  21056. return --this._count;
  21057. };
  21058. Collection.prototype.item = function (key) {
  21059. return this._collection[key];
  21060. };
  21061. Collection.prototype.forEach = function (block) {
  21062. var key;
  21063. for (key in this._collection) {
  21064. if (this._collection.hasOwnProperty(key)) {
  21065. block(this._collection[key]);
  21066. }
  21067. }
  21068. };
  21069. return Collection;
  21070. })();
  21071. VirtualJoystick.Collection = Collection;
  21072. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  21073. })(BABYLON || (BABYLON = {}));
  21074. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21075. var BABYLON;
  21076. (function (BABYLON) {
  21077. var OculusRiftDevKit2013_Metric = {
  21078. HResolution: 1280,
  21079. VResolution: 800,
  21080. HScreenSize: 0.149759993,
  21081. VScreenSize: 0.0935999975,
  21082. VScreenCenter: 0.0467999987,
  21083. EyeToScreenDistance: 0.0410000011,
  21084. LensSeparationDistance: 0.0635000020,
  21085. InterpupillaryDistance: 0.0640000030,
  21086. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21087. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21088. PostProcessScaleFactor: 1.714605507808412,
  21089. LensCenterOffset: 0.151976421
  21090. };
  21091. var _OculusInnerCamera = (function (_super) {
  21092. __extends(_OculusInnerCamera, _super);
  21093. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21094. _super.call(this, name, position, scene);
  21095. this._workMatrix = new BABYLON.Matrix();
  21096. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21097. // Constants
  21098. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21099. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21100. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21101. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21102. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21103. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21104. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21105. // Postprocess
  21106. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21107. }
  21108. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21109. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21110. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21111. return this._projectionMatrix;
  21112. };
  21113. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21114. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21115. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21116. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21117. // Computing target and final matrix
  21118. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21119. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21120. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21121. return this._viewMatrix;
  21122. };
  21123. return _OculusInnerCamera;
  21124. })(BABYLON.FreeCamera);
  21125. var OculusCamera = (function (_super) {
  21126. __extends(OculusCamera, _super);
  21127. function OculusCamera(name, position, scene) {
  21128. _super.call(this, name, position, scene);
  21129. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21130. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21131. this.subCameras.push(this._leftCamera);
  21132. this.subCameras.push(this._rightCamera);
  21133. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21134. }
  21135. OculusCamera.prototype._update = function () {
  21136. this._leftCamera.position.copyFrom(this.position);
  21137. this._rightCamera.position.copyFrom(this.position);
  21138. this._updateCamera(this._leftCamera);
  21139. this._updateCamera(this._rightCamera);
  21140. _super.prototype._update.call(this);
  21141. };
  21142. OculusCamera.prototype._updateCamera = function (camera) {
  21143. camera.minZ = this.minZ;
  21144. camera.maxZ = this.maxZ;
  21145. camera.rotation.x = this.rotation.x;
  21146. camera.rotation.y = this.rotation.y;
  21147. camera.rotation.z = this.rotation.z;
  21148. };
  21149. // Oculus events
  21150. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21151. var yaw = evt.alpha / 180 * Math.PI;
  21152. var pitch = evt.beta / 180 * Math.PI;
  21153. var roll = evt.gamma / 180 * Math.PI;
  21154. if (!this._offsetOrientation) {
  21155. this._offsetOrientation = {
  21156. yaw: yaw,
  21157. pitch: pitch,
  21158. roll: roll
  21159. };
  21160. return;
  21161. }
  21162. else {
  21163. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21164. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21165. this.rotation.z += this._offsetOrientation.roll - roll;
  21166. this._offsetOrientation.yaw = yaw;
  21167. this._offsetOrientation.pitch = pitch;
  21168. this._offsetOrientation.roll = roll;
  21169. }
  21170. };
  21171. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21172. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21173. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21174. };
  21175. OculusCamera.prototype.detachControl = function (element) {
  21176. _super.prototype.detachControl.call(this, element);
  21177. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21178. };
  21179. return OculusCamera;
  21180. })(BABYLON.FreeCamera);
  21181. BABYLON.OculusCamera = OculusCamera;
  21182. })(BABYLON || (BABYLON = {}));
  21183. //# sourceMappingURL=babylon.oculusCamera.js.map
  21184. var BABYLON;
  21185. (function (BABYLON) {
  21186. var OculusRiftDevKit2013_Metric = {
  21187. HResolution: 1280,
  21188. VResolution: 800,
  21189. HScreenSize: 0.149759993,
  21190. VScreenSize: 0.0935999975,
  21191. VScreenCenter: 0.0467999987,
  21192. EyeToScreenDistance: 0.0410000011,
  21193. LensSeparationDistance: 0.0635000020,
  21194. InterpupillaryDistance: 0.0640000030,
  21195. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21196. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21197. PostProcessScaleFactor: 1.714605507808412,
  21198. LensCenterOffset: 0.151976421
  21199. };
  21200. var _OculusInnerGamepadCamera = (function (_super) {
  21201. __extends(_OculusInnerGamepadCamera, _super);
  21202. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21203. _super.call(this, name, position, scene);
  21204. this._workMatrix = new BABYLON.Matrix();
  21205. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21206. // Constants
  21207. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21208. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21209. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21210. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21211. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21212. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21213. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21214. // Postprocess
  21215. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21216. }
  21217. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21218. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21219. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21220. return this._projectionMatrix;
  21221. };
  21222. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21223. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21224. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21225. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21226. // Computing target and final matrix
  21227. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21228. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21229. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21230. return this._viewMatrix;
  21231. };
  21232. return _OculusInnerGamepadCamera;
  21233. })(BABYLON.FreeCamera);
  21234. var OculusGamepadCamera = (function (_super) {
  21235. __extends(OculusGamepadCamera, _super);
  21236. function OculusGamepadCamera(name, position, scene) {
  21237. var _this = this;
  21238. _super.call(this, name, position, scene);
  21239. this.angularSensibility = 200;
  21240. this.moveSensibility = 75;
  21241. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21242. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21243. this.subCameras.push(this._leftCamera);
  21244. this.subCameras.push(this._rightCamera);
  21245. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21246. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21247. _this._onNewGameConnected(gamepad);
  21248. });
  21249. }
  21250. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21251. // Only the first gamepad can control the camera
  21252. if (gamepad.index === 0) {
  21253. this._gamepad = gamepad;
  21254. }
  21255. };
  21256. OculusGamepadCamera.prototype._update = function () {
  21257. this._leftCamera.position.copyFrom(this.position);
  21258. this._rightCamera.position.copyFrom(this.position);
  21259. this._updateCamera(this._leftCamera);
  21260. this._updateCamera(this._rightCamera);
  21261. _super.prototype._update.call(this);
  21262. };
  21263. OculusGamepadCamera.prototype._checkInputs = function () {
  21264. if (!this._gamepad) {
  21265. return;
  21266. }
  21267. var LSValues = this._gamepad.leftStick;
  21268. var normalizedLX = LSValues.x / this.moveSensibility;
  21269. var normalizedLY = LSValues.y / this.moveSensibility;
  21270. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21271. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21272. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21273. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21274. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21275. };
  21276. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21277. camera.minZ = this.minZ;
  21278. camera.maxZ = this.maxZ;
  21279. camera.rotation.x = this.rotation.x;
  21280. camera.rotation.y = this.rotation.y;
  21281. camera.rotation.z = this.rotation.z;
  21282. };
  21283. // Oculus events
  21284. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21285. var yaw = evt.alpha / 180 * Math.PI;
  21286. var pitch = evt.beta / 180 * Math.PI;
  21287. var roll = evt.gamma / 180 * Math.PI;
  21288. if (!this._offsetOrientation) {
  21289. this._offsetOrientation = {
  21290. yaw: yaw,
  21291. pitch: pitch,
  21292. roll: roll
  21293. };
  21294. return;
  21295. }
  21296. else {
  21297. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21298. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21299. this.rotation.z += this._offsetOrientation.roll - roll;
  21300. this._offsetOrientation.yaw = yaw;
  21301. this._offsetOrientation.pitch = pitch;
  21302. this._offsetOrientation.roll = roll;
  21303. }
  21304. };
  21305. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21306. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21307. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21308. };
  21309. OculusGamepadCamera.prototype.detachControl = function (element) {
  21310. _super.prototype.detachControl.call(this, element);
  21311. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21312. };
  21313. OculusGamepadCamera.prototype.dispose = function () {
  21314. this._gamepads.dispose();
  21315. _super.prototype.dispose.call(this);
  21316. };
  21317. return OculusGamepadCamera;
  21318. })(BABYLON.FreeCamera);
  21319. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21320. })(BABYLON || (BABYLON = {}));
  21321. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21322. var BABYLON;
  21323. (function (BABYLON) {
  21324. // We're mainly based on the logic defined into the FreeCamera code
  21325. var VirtualJoysticksCamera = (function (_super) {
  21326. __extends(VirtualJoysticksCamera, _super);
  21327. function VirtualJoysticksCamera(name, position, scene) {
  21328. _super.call(this, name, position, scene);
  21329. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21330. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21331. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21332. this._leftjoystick.setJoystickSensibility(0.15);
  21333. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21334. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21335. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21336. this._rightjoystick.reverseUpDown = true;
  21337. this._rightjoystick.setJoystickSensibility(0.05);
  21338. this._rightjoystick.setJoystickColor("yellow");
  21339. }
  21340. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21341. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21342. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21343. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21344. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21345. if (!this._leftjoystick.pressed) {
  21346. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21347. }
  21348. if (!this._rightjoystick.pressed) {
  21349. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21350. }
  21351. };
  21352. VirtualJoysticksCamera.prototype.dispose = function () {
  21353. this._leftjoystick.releaseCanvas();
  21354. _super.prototype.dispose.call(this);
  21355. };
  21356. return VirtualJoysticksCamera;
  21357. })(BABYLON.FreeCamera);
  21358. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21359. })(BABYLON || (BABYLON = {}));
  21360. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21361. var BABYLON;
  21362. (function (BABYLON) {
  21363. var ShaderMaterial = (function (_super) {
  21364. __extends(ShaderMaterial, _super);
  21365. function ShaderMaterial(name, scene, shaderPath, options) {
  21366. _super.call(this, name, scene);
  21367. this._textures = new Array();
  21368. this._floats = new Array();
  21369. this._floatsArrays = {};
  21370. this._colors3 = new Array();
  21371. this._colors4 = new Array();
  21372. this._vectors2 = new Array();
  21373. this._vectors3 = new Array();
  21374. this._matrices = new Array();
  21375. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21376. this._shaderPath = shaderPath;
  21377. options.needAlphaBlending = options.needAlphaBlending || false;
  21378. options.needAlphaTesting = options.needAlphaTesting || false;
  21379. options.attributes = options.attributes || ["position", "normal", "uv"];
  21380. options.uniforms = options.uniforms || ["worldViewProjection"];
  21381. options.samplers = options.samplers || [];
  21382. this._options = options;
  21383. }
  21384. ShaderMaterial.prototype.needAlphaBlending = function () {
  21385. return this._options.needAlphaBlending;
  21386. };
  21387. ShaderMaterial.prototype.needAlphaTesting = function () {
  21388. return this._options.needAlphaTesting;
  21389. };
  21390. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21391. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21392. this._options.uniforms.push(uniformName);
  21393. }
  21394. };
  21395. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21396. if (this._options.samplers.indexOf(name) === -1) {
  21397. this._options.samplers.push(name);
  21398. }
  21399. this._textures[name] = texture;
  21400. return this;
  21401. };
  21402. ShaderMaterial.prototype.setFloat = function (name, value) {
  21403. this._checkUniform(name);
  21404. this._floats[name] = value;
  21405. return this;
  21406. };
  21407. ShaderMaterial.prototype.setFloats = function (name, value) {
  21408. this._checkUniform(name);
  21409. this._floatsArrays[name] = value;
  21410. return this;
  21411. };
  21412. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21413. this._checkUniform(name);
  21414. this._colors3[name] = value;
  21415. return this;
  21416. };
  21417. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21418. this._checkUniform(name);
  21419. this._colors4[name] = value;
  21420. return this;
  21421. };
  21422. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21423. this._checkUniform(name);
  21424. this._vectors2[name] = value;
  21425. return this;
  21426. };
  21427. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21428. this._checkUniform(name);
  21429. this._vectors3[name] = value;
  21430. return this;
  21431. };
  21432. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21433. this._checkUniform(name);
  21434. this._matrices[name] = value;
  21435. return this;
  21436. };
  21437. ShaderMaterial.prototype.isReady = function () {
  21438. var scene = this.getScene();
  21439. var engine = scene.getEngine();
  21440. if (!this.checkReadyOnEveryCall) {
  21441. if (this._renderId === scene.getRenderId()) {
  21442. return true;
  21443. }
  21444. }
  21445. var previousEffect = this._effect;
  21446. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21447. if (!this._effect.isReady()) {
  21448. return false;
  21449. }
  21450. if (previousEffect !== this._effect) {
  21451. scene.resetCachedMaterial();
  21452. }
  21453. this._renderId = scene.getRenderId();
  21454. return true;
  21455. };
  21456. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21457. var scene = this.getScene();
  21458. if (this._options.uniforms.indexOf("world") !== -1) {
  21459. this._effect.setMatrix("world", world);
  21460. }
  21461. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21462. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21463. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21464. }
  21465. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21466. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21467. }
  21468. };
  21469. ShaderMaterial.prototype.bind = function (world) {
  21470. // Std values
  21471. this.bindOnlyWorldMatrix(world);
  21472. if (this.getScene().getCachedMaterial() !== this) {
  21473. if (this._options.uniforms.indexOf("view") !== -1) {
  21474. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21475. }
  21476. if (this._options.uniforms.indexOf("projection") !== -1) {
  21477. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21478. }
  21479. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21480. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21481. }
  21482. for (var name in this._textures) {
  21483. this._effect.setTexture(name, this._textures[name]);
  21484. }
  21485. for (name in this._floats) {
  21486. this._effect.setFloat(name, this._floats[name]);
  21487. }
  21488. for (name in this._floatsArrays) {
  21489. this._effect.setArray(name, this._floatsArrays[name]);
  21490. }
  21491. for (name in this._colors3) {
  21492. this._effect.setColor3(name, this._colors3[name]);
  21493. }
  21494. for (name in this._colors4) {
  21495. var color = this._colors4[name];
  21496. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21497. }
  21498. for (name in this._vectors2) {
  21499. this._effect.setVector2(name, this._vectors2[name]);
  21500. }
  21501. for (name in this._vectors3) {
  21502. this._effect.setVector3(name, this._vectors3[name]);
  21503. }
  21504. for (name in this._matrices) {
  21505. this._effect.setMatrix(name, this._matrices[name]);
  21506. }
  21507. }
  21508. _super.prototype.bind.call(this, world, null);
  21509. };
  21510. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21511. for (var name in this._textures) {
  21512. this._textures[name].dispose();
  21513. }
  21514. this._textures = [];
  21515. _super.prototype.dispose.call(this, forceDisposeEffect);
  21516. };
  21517. return ShaderMaterial;
  21518. })(BABYLON.Material);
  21519. BABYLON.ShaderMaterial = ShaderMaterial;
  21520. })(BABYLON || (BABYLON = {}));
  21521. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21522. (function (BABYLON) {
  21523. var VertexData = (function () {
  21524. function VertexData() {
  21525. }
  21526. VertexData.prototype.set = function (data, kind) {
  21527. switch (kind) {
  21528. case BABYLON.VertexBuffer.PositionKind:
  21529. this.positions = data;
  21530. break;
  21531. case BABYLON.VertexBuffer.NormalKind:
  21532. this.normals = data;
  21533. break;
  21534. case BABYLON.VertexBuffer.UVKind:
  21535. this.uvs = data;
  21536. break;
  21537. case BABYLON.VertexBuffer.UV2Kind:
  21538. this.uv2s = data;
  21539. break;
  21540. case BABYLON.VertexBuffer.ColorKind:
  21541. this.colors = data;
  21542. break;
  21543. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21544. this.matricesIndices = data;
  21545. break;
  21546. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21547. this.matricesWeights = data;
  21548. break;
  21549. }
  21550. };
  21551. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21552. this._applyTo(mesh, updatable);
  21553. };
  21554. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21555. this._applyTo(geometry, updatable);
  21556. };
  21557. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21558. this._update(mesh);
  21559. };
  21560. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21561. this._update(geometry);
  21562. };
  21563. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21564. if (this.positions) {
  21565. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21566. }
  21567. if (this.normals) {
  21568. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21569. }
  21570. if (this.uvs) {
  21571. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21572. }
  21573. if (this.uv2s) {
  21574. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21575. }
  21576. if (this.colors) {
  21577. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21578. }
  21579. if (this.matricesIndices) {
  21580. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21581. }
  21582. if (this.matricesWeights) {
  21583. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21584. }
  21585. if (this.indices) {
  21586. meshOrGeometry.setIndices(this.indices);
  21587. }
  21588. };
  21589. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21590. if (this.positions) {
  21591. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21592. }
  21593. if (this.normals) {
  21594. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21595. }
  21596. if (this.uvs) {
  21597. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21598. }
  21599. if (this.uv2s) {
  21600. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21601. }
  21602. if (this.colors) {
  21603. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21604. }
  21605. if (this.matricesIndices) {
  21606. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21607. }
  21608. if (this.matricesWeights) {
  21609. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21610. }
  21611. if (this.indices) {
  21612. meshOrGeometry.setIndices(this.indices);
  21613. }
  21614. };
  21615. VertexData.prototype.transform = function (matrix) {
  21616. var transformed = BABYLON.Vector3.Zero();
  21617. if (this.positions) {
  21618. var position = BABYLON.Vector3.Zero();
  21619. for (var index = 0; index < this.positions.length; index += 3) {
  21620. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21621. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21622. this.positions[index] = transformed.x;
  21623. this.positions[index + 1] = transformed.y;
  21624. this.positions[index + 2] = transformed.z;
  21625. }
  21626. }
  21627. if (this.normals) {
  21628. var normal = BABYLON.Vector3.Zero();
  21629. for (index = 0; index < this.normals.length; index += 3) {
  21630. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21631. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21632. this.normals[index] = transformed.x;
  21633. this.normals[index + 1] = transformed.y;
  21634. this.normals[index + 2] = transformed.z;
  21635. }
  21636. }
  21637. };
  21638. VertexData.prototype.merge = function (other) {
  21639. if (other.indices) {
  21640. if (!this.indices) {
  21641. this.indices = [];
  21642. }
  21643. var offset = this.positions ? this.positions.length / 3 : 0;
  21644. for (var index = 0; index < other.indices.length; index++) {
  21645. this.indices.push(other.indices[index] + offset);
  21646. }
  21647. }
  21648. if (other.positions) {
  21649. if (!this.positions) {
  21650. this.positions = [];
  21651. }
  21652. for (index = 0; index < other.positions.length; index++) {
  21653. this.positions.push(other.positions[index]);
  21654. }
  21655. }
  21656. if (other.normals) {
  21657. if (!this.normals) {
  21658. this.normals = [];
  21659. }
  21660. for (index = 0; index < other.normals.length; index++) {
  21661. this.normals.push(other.normals[index]);
  21662. }
  21663. }
  21664. if (other.uvs) {
  21665. if (!this.uvs) {
  21666. this.uvs = [];
  21667. }
  21668. for (index = 0; index < other.uvs.length; index++) {
  21669. this.uvs.push(other.uvs[index]);
  21670. }
  21671. }
  21672. if (other.uv2s) {
  21673. if (!this.uv2s) {
  21674. this.uv2s = [];
  21675. }
  21676. for (index = 0; index < other.uv2s.length; index++) {
  21677. this.uv2s.push(other.uv2s[index]);
  21678. }
  21679. }
  21680. if (other.matricesIndices) {
  21681. if (!this.matricesIndices) {
  21682. this.matricesIndices = [];
  21683. }
  21684. for (index = 0; index < other.matricesIndices.length; index++) {
  21685. this.matricesIndices.push(other.matricesIndices[index]);
  21686. }
  21687. }
  21688. if (other.matricesWeights) {
  21689. if (!this.matricesWeights) {
  21690. this.matricesWeights = [];
  21691. }
  21692. for (index = 0; index < other.matricesWeights.length; index++) {
  21693. this.matricesWeights.push(other.matricesWeights[index]);
  21694. }
  21695. }
  21696. if (other.colors) {
  21697. if (!this.colors) {
  21698. this.colors = [];
  21699. }
  21700. for (index = 0; index < other.colors.length; index++) {
  21701. this.colors.push(other.colors[index]);
  21702. }
  21703. }
  21704. };
  21705. // Statics
  21706. VertexData.ExtractFromMesh = function (mesh) {
  21707. return VertexData._ExtractFrom(mesh);
  21708. };
  21709. VertexData.ExtractFromGeometry = function (geometry) {
  21710. return VertexData._ExtractFrom(geometry);
  21711. };
  21712. VertexData._ExtractFrom = function (meshOrGeometry) {
  21713. var result = new VertexData();
  21714. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21715. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21716. }
  21717. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21718. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21719. }
  21720. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21721. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21722. }
  21723. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21724. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21725. }
  21726. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21727. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21728. }
  21729. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21730. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21731. }
  21732. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21733. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21734. }
  21735. result.indices = meshOrGeometry.getIndices();
  21736. return result;
  21737. };
  21738. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21739. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21740. closeArray = closeArray || false;
  21741. closePath = closePath || false;
  21742. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21743. offset = offset || defaultOffset;
  21744. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21745. var positions = [];
  21746. var indices = [];
  21747. var normals = [];
  21748. var uvs = [];
  21749. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21750. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21751. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21752. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21753. var minlg; // minimal length among all paths from pathArray
  21754. var lg = []; // array of path lengths : nb of vertex per path
  21755. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21756. var p; // path iterator
  21757. var i; // point iterator
  21758. var j; // point iterator
  21759. // if single path in pathArray
  21760. if (pathArray.length < 2) {
  21761. var ar1 = [];
  21762. var ar2 = [];
  21763. for (i = 0; i < pathArray[0].length - offset; i++) {
  21764. ar1.push(pathArray[0][i]);
  21765. ar2.push(pathArray[0][i + offset]);
  21766. }
  21767. pathArray = [ar1, ar2];
  21768. }
  21769. // positions and horizontal distances (u)
  21770. var idc = 0;
  21771. minlg = pathArray[0].length;
  21772. for (p = 0; p < pathArray.length; p++) {
  21773. uTotalDistance[p] = 0;
  21774. us[p] = [0];
  21775. var path = pathArray[p];
  21776. var l = path.length;
  21777. minlg = (minlg < l) ? minlg : l;
  21778. lg[p] = l;
  21779. idx[p] = idc;
  21780. j = 0;
  21781. while (j < l) {
  21782. positions.push(path[j].x, path[j].y, path[j].z);
  21783. if (j > 0) {
  21784. var vectlg = path[j].subtract(path[j - 1]).length();
  21785. var dist = vectlg + uTotalDistance[p];
  21786. us[p].push(dist);
  21787. uTotalDistance[p] = dist;
  21788. }
  21789. j++;
  21790. }
  21791. if (closePath) {
  21792. vectlg = path[0].subtract(path[j - 1]).length();
  21793. dist = vectlg + uTotalDistance[p];
  21794. uTotalDistance[p] = dist;
  21795. }
  21796. idc += l;
  21797. }
  21798. for (i = 0; i < minlg; i++) {
  21799. vTotalDistance[i] = 0;
  21800. vs[i] = [0];
  21801. var path1;
  21802. var path2;
  21803. for (p = 0; p < pathArray.length - 1; p++) {
  21804. path1 = pathArray[p];
  21805. path2 = pathArray[p + 1];
  21806. vectlg = path2[i].subtract(path1[i]).length();
  21807. dist = vectlg + vTotalDistance[i];
  21808. vs[i].push(dist);
  21809. vTotalDistance[i] = dist;
  21810. }
  21811. if (closeArray) {
  21812. path1 = pathArray[p];
  21813. path2 = pathArray[0];
  21814. vectlg = path2[i].subtract(path1[i]).length();
  21815. dist = vectlg + vTotalDistance[i];
  21816. vTotalDistance[i] = dist;
  21817. }
  21818. }
  21819. // uvs
  21820. var u;
  21821. var v;
  21822. for (p = 0; p < pathArray.length; p++) {
  21823. for (i = 0; i < minlg; i++) {
  21824. u = us[p][i] / uTotalDistance[p];
  21825. v = vs[i][p] / vTotalDistance[i];
  21826. uvs.push(u, v);
  21827. }
  21828. }
  21829. // indices
  21830. p = 0; // path index
  21831. var pi = 0; // positions array index
  21832. var l1 = lg[p] - 1; // path1 length
  21833. var l2 = lg[p + 1] - 1; // path2 length
  21834. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21835. var shft = idx[1] - idx[0]; // shift
  21836. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21837. var t1; // two consecutive triangles, so 4 points : point1
  21838. var t2; // point2
  21839. var t3; // point3
  21840. var t4; // point4
  21841. while (pi <= min && p < path1nb) {
  21842. // 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
  21843. t1 = pi;
  21844. t2 = pi + shft;
  21845. t3 = pi + 1;
  21846. t4 = pi + shft + 1;
  21847. indices.push(pi, pi + shft, pi + 1);
  21848. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21849. pi += 1;
  21850. if (pi === min) {
  21851. if (closePath) {
  21852. indices.push(pi, pi + shft, idx[p]);
  21853. indices.push(idx[p] + shft, idx[p], pi + shft);
  21854. t3 = idx[p];
  21855. t4 = idx[p] + shft;
  21856. }
  21857. p++;
  21858. if (p === lg.length - 1) {
  21859. shft = idx[0] - idx[p];
  21860. l1 = lg[p] - 1;
  21861. l2 = lg[0] - 1;
  21862. }
  21863. else {
  21864. shft = idx[p + 1] - idx[p];
  21865. l1 = lg[p] - 1;
  21866. l2 = lg[p + 1] - 1;
  21867. }
  21868. pi = idx[p];
  21869. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21870. }
  21871. }
  21872. // normals
  21873. VertexData.ComputeNormals(positions, indices, normals);
  21874. // sides
  21875. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21876. // Result
  21877. var vertexData = new VertexData();
  21878. vertexData.indices = indices;
  21879. vertexData.positions = positions;
  21880. vertexData.normals = normals;
  21881. vertexData.uvs = uvs;
  21882. return vertexData;
  21883. };
  21884. VertexData.CreateBox = function (size, sideOrientation) {
  21885. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21886. var normalsSource = [
  21887. new BABYLON.Vector3(0, 0, 1),
  21888. new BABYLON.Vector3(0, 0, -1),
  21889. new BABYLON.Vector3(1, 0, 0),
  21890. new BABYLON.Vector3(-1, 0, 0),
  21891. new BABYLON.Vector3(0, 1, 0),
  21892. new BABYLON.Vector3(0, -1, 0)
  21893. ];
  21894. var indices = [];
  21895. var positions = [];
  21896. var normals = [];
  21897. var uvs = [];
  21898. size = size || 1;
  21899. for (var index = 0; index < normalsSource.length; index++) {
  21900. var normal = normalsSource[index];
  21901. // Get two vectors perpendicular to the face normal and to each other.
  21902. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21903. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21904. // Six indices (two triangles) per face.
  21905. var verticesLength = positions.length / 3;
  21906. indices.push(verticesLength);
  21907. indices.push(verticesLength + 1);
  21908. indices.push(verticesLength + 2);
  21909. indices.push(verticesLength);
  21910. indices.push(verticesLength + 2);
  21911. indices.push(verticesLength + 3);
  21912. // Four vertices per face.
  21913. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21914. positions.push(vertex.x, vertex.y, vertex.z);
  21915. normals.push(normal.x, normal.y, normal.z);
  21916. uvs.push(1.0, 1.0);
  21917. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21918. positions.push(vertex.x, vertex.y, vertex.z);
  21919. normals.push(normal.x, normal.y, normal.z);
  21920. uvs.push(0.0, 1.0);
  21921. vertex = normal.add(side1).add(side2).scale(size / 2);
  21922. positions.push(vertex.x, vertex.y, vertex.z);
  21923. normals.push(normal.x, normal.y, normal.z);
  21924. uvs.push(0.0, 0.0);
  21925. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21926. positions.push(vertex.x, vertex.y, vertex.z);
  21927. normals.push(normal.x, normal.y, normal.z);
  21928. uvs.push(1.0, 0.0);
  21929. }
  21930. // sides
  21931. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21932. // Result
  21933. var vertexData = new VertexData();
  21934. vertexData.indices = indices;
  21935. vertexData.positions = positions;
  21936. vertexData.normals = normals;
  21937. vertexData.uvs = uvs;
  21938. return vertexData;
  21939. };
  21940. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21941. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21942. segments = segments || 32;
  21943. diameter = diameter || 1;
  21944. var radius = diameter / 2;
  21945. var totalZRotationSteps = 2 + segments;
  21946. var totalYRotationSteps = 2 * totalZRotationSteps;
  21947. var indices = [];
  21948. var positions = [];
  21949. var normals = [];
  21950. var uvs = [];
  21951. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21952. var normalizedZ = zRotationStep / totalZRotationSteps;
  21953. var angleZ = (normalizedZ * Math.PI);
  21954. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21955. var normalizedY = yRotationStep / totalYRotationSteps;
  21956. var angleY = normalizedY * Math.PI * 2;
  21957. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21958. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21959. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21960. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21961. var vertex = complete.scale(radius);
  21962. var normal = BABYLON.Vector3.Normalize(vertex);
  21963. positions.push(vertex.x, vertex.y, vertex.z);
  21964. normals.push(normal.x, normal.y, normal.z);
  21965. uvs.push(normalizedZ, normalizedY);
  21966. }
  21967. if (zRotationStep > 0) {
  21968. var verticesCount = positions.length / 3;
  21969. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21970. indices.push((firstIndex));
  21971. indices.push((firstIndex + 1));
  21972. indices.push(firstIndex + totalYRotationSteps + 1);
  21973. indices.push((firstIndex + totalYRotationSteps + 1));
  21974. indices.push((firstIndex + 1));
  21975. indices.push((firstIndex + totalYRotationSteps + 2));
  21976. }
  21977. }
  21978. }
  21979. // Sides
  21980. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21981. // Result
  21982. var vertexData = new VertexData();
  21983. vertexData.indices = indices;
  21984. vertexData.positions = positions;
  21985. vertexData.normals = normals;
  21986. vertexData.uvs = uvs;
  21987. return vertexData;
  21988. };
  21989. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21990. if (subdivisions === void 0) { subdivisions = 1; }
  21991. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21992. var radiusTop = diameterTop / 2;
  21993. var radiusBottom = diameterBottom / 2;
  21994. var indices = [];
  21995. var positions = [];
  21996. var normals = [];
  21997. var uvs = [];
  21998. height = height || 1;
  21999. diameterTop = diameterTop || 0.5;
  22000. diameterBottom = diameterBottom || 1;
  22001. tessellation = tessellation || 16;
  22002. subdivisions = subdivisions || 1;
  22003. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22004. var getCircleVector = function (i) {
  22005. var angle = (i * 2.0 * Math.PI / tessellation);
  22006. var dx = Math.cos(angle);
  22007. var dz = Math.sin(angle);
  22008. return new BABYLON.Vector3(dx, 0, dz);
  22009. };
  22010. var createCylinderCap = function (isTop) {
  22011. var radius = isTop ? radiusTop : radiusBottom;
  22012. if (radius === 0) {
  22013. return;
  22014. }
  22015. var vbase = positions.length / 3;
  22016. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22017. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22018. if (!isTop) {
  22019. offset.scaleInPlace(-1);
  22020. textureScale.x = -textureScale.x;
  22021. }
  22022. for (var i = 0; i < tessellation; i++) {
  22023. var circleVector = getCircleVector(i);
  22024. var position = circleVector.scale(radius).add(offset);
  22025. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22026. positions.push(position.x, position.y, position.z);
  22027. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22028. }
  22029. for (i = 0; i < tessellation - 2; i++) {
  22030. if (!isTop) {
  22031. indices.push(vbase);
  22032. indices.push(vbase + (i + 2) % tessellation);
  22033. indices.push(vbase + (i + 1) % tessellation);
  22034. }
  22035. else {
  22036. indices.push(vbase);
  22037. indices.push(vbase + (i + 1) % tessellation);
  22038. indices.push(vbase + (i + 2) % tessellation);
  22039. }
  22040. }
  22041. };
  22042. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22043. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22044. var stride = tessellation + 1;
  22045. for (var i = 0; i <= tessellation; i++) {
  22046. var circleVector = getCircleVector(i);
  22047. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22048. var position, radius = radiusBottom;
  22049. for (var s = 0; s <= subdivisions; s++) {
  22050. // Update variables
  22051. position = circleVector.scale(radius);
  22052. position.addInPlace(base.add(offset.scale(s)));
  22053. textureCoordinate.y += 1 / subdivisions;
  22054. radius += (radiusTop - radiusBottom) / subdivisions;
  22055. // Push in arrays
  22056. positions.push(position.x, position.y, position.z);
  22057. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22058. }
  22059. }
  22060. subdivisions += 1;
  22061. for (s = 0; s < subdivisions - 1; s++) {
  22062. for (i = 0; i <= tessellation; i++) {
  22063. indices.push(i * subdivisions + s);
  22064. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22065. indices.push(i * subdivisions + (s + 1));
  22066. indices.push(i * subdivisions + (s + 1));
  22067. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22068. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22069. }
  22070. }
  22071. // Create flat triangle fan caps to seal the top and bottom.
  22072. createCylinderCap(true);
  22073. createCylinderCap(false);
  22074. // Normals
  22075. VertexData.ComputeNormals(positions, indices, normals);
  22076. // Sides
  22077. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22078. // Result
  22079. var vertexData = new VertexData();
  22080. vertexData.indices = indices;
  22081. vertexData.positions = positions;
  22082. vertexData.normals = normals;
  22083. vertexData.uvs = uvs;
  22084. return vertexData;
  22085. };
  22086. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22087. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22088. var indices = [];
  22089. var positions = [];
  22090. var normals = [];
  22091. var uvs = [];
  22092. diameter = diameter || 1;
  22093. thickness = thickness || 0.5;
  22094. tessellation = tessellation || 16;
  22095. var stride = tessellation + 1;
  22096. for (var i = 0; i <= tessellation; i++) {
  22097. var u = i / tessellation;
  22098. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22099. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22100. for (var j = 0; j <= tessellation; j++) {
  22101. var v = 1 - j / tessellation;
  22102. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22103. var dx = Math.cos(innerAngle);
  22104. var dy = Math.sin(innerAngle);
  22105. // Create a vertex.
  22106. var normal = new BABYLON.Vector3(dx, dy, 0);
  22107. var position = normal.scale(thickness / 2);
  22108. var textureCoordinate = new BABYLON.Vector2(u, v);
  22109. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22110. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22111. positions.push(position.x, position.y, position.z);
  22112. normals.push(normal.x, normal.y, normal.z);
  22113. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22114. // And create indices for two triangles.
  22115. var nextI = (i + 1) % stride;
  22116. var nextJ = (j + 1) % stride;
  22117. indices.push(i * stride + j);
  22118. indices.push(i * stride + nextJ);
  22119. indices.push(nextI * stride + j);
  22120. indices.push(i * stride + nextJ);
  22121. indices.push(nextI * stride + nextJ);
  22122. indices.push(nextI * stride + j);
  22123. }
  22124. }
  22125. // Sides
  22126. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22127. // Result
  22128. var vertexData = new VertexData();
  22129. vertexData.indices = indices;
  22130. vertexData.positions = positions;
  22131. vertexData.normals = normals;
  22132. vertexData.uvs = uvs;
  22133. return vertexData;
  22134. };
  22135. VertexData.CreateLines = function (points) {
  22136. var indices = [];
  22137. var positions = [];
  22138. for (var index = 0; index < points.length; index++) {
  22139. positions.push(points[index].x, points[index].y, points[index].z);
  22140. if (index > 0) {
  22141. indices.push(index - 1);
  22142. indices.push(index);
  22143. }
  22144. }
  22145. // Result
  22146. var vertexData = new VertexData();
  22147. vertexData.indices = indices;
  22148. vertexData.positions = positions;
  22149. return vertexData;
  22150. };
  22151. VertexData.CreateGround = function (width, height, subdivisions) {
  22152. var indices = [];
  22153. var positions = [];
  22154. var normals = [];
  22155. var uvs = [];
  22156. var row, col;
  22157. width = width || 1;
  22158. height = height || 1;
  22159. subdivisions = subdivisions || 1;
  22160. for (row = 0; row <= subdivisions; row++) {
  22161. for (col = 0; col <= subdivisions; col++) {
  22162. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22163. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22164. positions.push(position.x, position.y, position.z);
  22165. normals.push(normal.x, normal.y, normal.z);
  22166. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22167. }
  22168. }
  22169. for (row = 0; row < subdivisions; row++) {
  22170. for (col = 0; col < subdivisions; col++) {
  22171. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22172. indices.push(col + 1 + row * (subdivisions + 1));
  22173. indices.push(col + row * (subdivisions + 1));
  22174. indices.push(col + (row + 1) * (subdivisions + 1));
  22175. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22176. indices.push(col + row * (subdivisions + 1));
  22177. }
  22178. }
  22179. // Result
  22180. var vertexData = new VertexData();
  22181. vertexData.indices = indices;
  22182. vertexData.positions = positions;
  22183. vertexData.normals = normals;
  22184. vertexData.uvs = uvs;
  22185. return vertexData;
  22186. };
  22187. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22188. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22189. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22190. var indices = [];
  22191. var positions = [];
  22192. var normals = [];
  22193. var uvs = [];
  22194. var row, col, tileRow, tileCol;
  22195. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22196. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22197. precision.w = (precision.w < 1) ? 1 : precision.w;
  22198. precision.h = (precision.h < 1) ? 1 : precision.h;
  22199. var tileSize = {
  22200. 'w': (xmax - xmin) / subdivisions.w,
  22201. 'h': (zmax - zmin) / subdivisions.h
  22202. };
  22203. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22204. // Indices
  22205. var base = positions.length / 3;
  22206. var rowLength = precision.w + 1;
  22207. for (row = 0; row < precision.h; row++) {
  22208. for (col = 0; col < precision.w; col++) {
  22209. var square = [
  22210. base + col + row * rowLength,
  22211. base + (col + 1) + row * rowLength,
  22212. base + (col + 1) + (row + 1) * rowLength,
  22213. base + col + (row + 1) * rowLength
  22214. ];
  22215. indices.push(square[1]);
  22216. indices.push(square[2]);
  22217. indices.push(square[3]);
  22218. indices.push(square[0]);
  22219. indices.push(square[1]);
  22220. indices.push(square[3]);
  22221. }
  22222. }
  22223. // Position, normals and uvs
  22224. var position = BABYLON.Vector3.Zero();
  22225. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22226. for (row = 0; row <= precision.h; row++) {
  22227. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22228. for (col = 0; col <= precision.w; col++) {
  22229. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22230. position.y = 0;
  22231. positions.push(position.x, position.y, position.z);
  22232. normals.push(normal.x, normal.y, normal.z);
  22233. uvs.push(col / precision.w, row / precision.h);
  22234. }
  22235. }
  22236. }
  22237. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22238. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22239. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22240. }
  22241. }
  22242. // Result
  22243. var vertexData = new VertexData();
  22244. vertexData.indices = indices;
  22245. vertexData.positions = positions;
  22246. vertexData.normals = normals;
  22247. vertexData.uvs = uvs;
  22248. return vertexData;
  22249. };
  22250. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22251. var indices = [];
  22252. var positions = [];
  22253. var normals = [];
  22254. var uvs = [];
  22255. var row, col;
  22256. for (row = 0; row <= subdivisions; row++) {
  22257. for (col = 0; col <= subdivisions; col++) {
  22258. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22259. // Compute height
  22260. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22261. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22262. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22263. var r = buffer[pos] / 255.0;
  22264. var g = buffer[pos + 1] / 255.0;
  22265. var b = buffer[pos + 2] / 255.0;
  22266. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22267. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22268. // Add vertex
  22269. positions.push(position.x, position.y, position.z);
  22270. normals.push(0, 0, 0);
  22271. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22272. }
  22273. }
  22274. for (row = 0; row < subdivisions; row++) {
  22275. for (col = 0; col < subdivisions; col++) {
  22276. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22277. indices.push(col + 1 + row * (subdivisions + 1));
  22278. indices.push(col + row * (subdivisions + 1));
  22279. indices.push(col + (row + 1) * (subdivisions + 1));
  22280. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22281. indices.push(col + row * (subdivisions + 1));
  22282. }
  22283. }
  22284. // Normals
  22285. VertexData.ComputeNormals(positions, indices, normals);
  22286. // Result
  22287. var vertexData = new VertexData();
  22288. vertexData.indices = indices;
  22289. vertexData.positions = positions;
  22290. vertexData.normals = normals;
  22291. vertexData.uvs = uvs;
  22292. return vertexData;
  22293. };
  22294. VertexData.CreatePlane = function (size, sideOrientation) {
  22295. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22296. var indices = [];
  22297. var positions = [];
  22298. var normals = [];
  22299. var uvs = [];
  22300. size = size || 1;
  22301. // Vertices
  22302. var halfSize = size / 2.0;
  22303. positions.push(-halfSize, -halfSize, 0);
  22304. normals.push(0, 0, -1.0);
  22305. uvs.push(0.0, 0.0);
  22306. positions.push(halfSize, -halfSize, 0);
  22307. normals.push(0, 0, -1.0);
  22308. uvs.push(1.0, 0.0);
  22309. positions.push(halfSize, halfSize, 0);
  22310. normals.push(0, 0, -1.0);
  22311. uvs.push(1.0, 1.0);
  22312. positions.push(-halfSize, halfSize, 0);
  22313. normals.push(0, 0, -1.0);
  22314. uvs.push(0.0, 1.0);
  22315. // Indices
  22316. indices.push(0);
  22317. indices.push(1);
  22318. indices.push(2);
  22319. indices.push(0);
  22320. indices.push(2);
  22321. indices.push(3);
  22322. // Sides
  22323. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22324. // Result
  22325. var vertexData = new VertexData();
  22326. vertexData.indices = indices;
  22327. vertexData.positions = positions;
  22328. vertexData.normals = normals;
  22329. vertexData.uvs = uvs;
  22330. return vertexData;
  22331. };
  22332. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22333. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22334. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22335. var indices = [];
  22336. var positions = [];
  22337. var normals = [];
  22338. var uvs = [];
  22339. radius = radius || 2;
  22340. tube = tube || 0.5;
  22341. radialSegments = radialSegments || 32;
  22342. tubularSegments = tubularSegments || 32;
  22343. p = p || 2;
  22344. q = q || 3;
  22345. // Helper
  22346. var getPos = function (angle) {
  22347. var cu = Math.cos(angle);
  22348. var su = Math.sin(angle);
  22349. var quOverP = q / p * angle;
  22350. var cs = Math.cos(quOverP);
  22351. var tx = radius * (2 + cs) * 0.5 * cu;
  22352. var ty = radius * (2 + cs) * su * 0.5;
  22353. var tz = radius * Math.sin(quOverP) * 0.5;
  22354. return new BABYLON.Vector3(tx, ty, tz);
  22355. };
  22356. for (var i = 0; i <= radialSegments; i++) {
  22357. var modI = i % radialSegments;
  22358. var u = modI / radialSegments * 2 * p * Math.PI;
  22359. var p1 = getPos(u);
  22360. var p2 = getPos(u + 0.01);
  22361. var tang = p2.subtract(p1);
  22362. var n = p2.add(p1);
  22363. var bitan = BABYLON.Vector3.Cross(tang, n);
  22364. n = BABYLON.Vector3.Cross(bitan, tang);
  22365. bitan.normalize();
  22366. n.normalize();
  22367. for (var j = 0; j < tubularSegments; j++) {
  22368. var modJ = j % tubularSegments;
  22369. var v = modJ / tubularSegments * 2 * Math.PI;
  22370. var cx = -tube * Math.cos(v);
  22371. var cy = tube * Math.sin(v);
  22372. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22373. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22374. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22375. uvs.push(i / radialSegments);
  22376. uvs.push(j / tubularSegments);
  22377. }
  22378. }
  22379. for (i = 0; i < radialSegments; i++) {
  22380. for (j = 0; j < tubularSegments; j++) {
  22381. var jNext = (j + 1) % tubularSegments;
  22382. var a = i * tubularSegments + j;
  22383. var b = (i + 1) * tubularSegments + j;
  22384. var c = (i + 1) * tubularSegments + jNext;
  22385. var d = i * tubularSegments + jNext;
  22386. indices.push(d);
  22387. indices.push(b);
  22388. indices.push(a);
  22389. indices.push(d);
  22390. indices.push(c);
  22391. indices.push(b);
  22392. }
  22393. }
  22394. // Normals
  22395. VertexData.ComputeNormals(positions, indices, normals);
  22396. // Sides
  22397. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22398. // Result
  22399. var vertexData = new VertexData();
  22400. vertexData.indices = indices;
  22401. vertexData.positions = positions;
  22402. vertexData.normals = normals;
  22403. vertexData.uvs = uvs;
  22404. return vertexData;
  22405. };
  22406. // Tools
  22407. VertexData.ComputeNormals = function (positions, indices, normals) {
  22408. var positionVectors = [];
  22409. var facesOfVertices = [];
  22410. var index;
  22411. for (index = 0; index < positions.length; index += 3) {
  22412. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22413. positionVectors.push(vector3);
  22414. facesOfVertices.push([]);
  22415. }
  22416. // Compute normals
  22417. var facesNormals = [];
  22418. for (index = 0; index < indices.length / 3; index++) {
  22419. var i1 = indices[index * 3];
  22420. var i2 = indices[index * 3 + 1];
  22421. var i3 = indices[index * 3 + 2];
  22422. var p1 = positionVectors[i1];
  22423. var p2 = positionVectors[i2];
  22424. var p3 = positionVectors[i3];
  22425. var p1p2 = p1.subtract(p2);
  22426. var p3p2 = p3.subtract(p2);
  22427. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22428. facesOfVertices[i1].push(index);
  22429. facesOfVertices[i2].push(index);
  22430. facesOfVertices[i3].push(index);
  22431. }
  22432. for (index = 0; index < positionVectors.length; index++) {
  22433. var faces = facesOfVertices[index];
  22434. var normal = BABYLON.Vector3.Zero();
  22435. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22436. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22437. }
  22438. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22439. normals[index * 3] = normal.x;
  22440. normals[index * 3 + 1] = normal.y;
  22441. normals[index * 3 + 2] = normal.z;
  22442. }
  22443. };
  22444. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22445. var li = indices.length;
  22446. var ln = normals.length;
  22447. var i;
  22448. var n;
  22449. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22450. switch (sideOrientation) {
  22451. case BABYLON.Mesh.FRONTSIDE:
  22452. break;
  22453. case BABYLON.Mesh.BACKSIDE:
  22454. var tmp;
  22455. for (i = 0; i < li; i += 3) {
  22456. tmp = indices[i];
  22457. indices[i] = indices[i + 2];
  22458. indices[i + 2] = tmp;
  22459. }
  22460. for (n = 0; n < ln; n++) {
  22461. normals[n] = -normals[n];
  22462. }
  22463. break;
  22464. case BABYLON.Mesh.DOUBLESIDE:
  22465. // positions
  22466. var lp = positions.length;
  22467. var l = lp / 3;
  22468. for (var p = 0; p < lp; p++) {
  22469. positions[lp + p] = positions[p];
  22470. }
  22471. for (i = 0; i < li; i += 3) {
  22472. indices[i + li] = indices[i + 2] + l;
  22473. indices[i + 1 + li] = indices[i + 1] + l;
  22474. indices[i + 2 + li] = indices[i] + l;
  22475. }
  22476. for (n = 0; n < ln; n++) {
  22477. normals[ln + n] = -normals[n];
  22478. }
  22479. // uvs
  22480. var lu = uvs.length;
  22481. for (var u = 0; u < lu; u++) {
  22482. uvs[u + lu] = uvs[u];
  22483. }
  22484. break;
  22485. }
  22486. };
  22487. return VertexData;
  22488. })();
  22489. BABYLON.VertexData = VertexData;
  22490. })(BABYLON || (BABYLON = {}));
  22491. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22492. var BABYLON;
  22493. (function (BABYLON) {
  22494. var buildCamera = function (that, name) {
  22495. that._leftCamera.isIntermediate = true;
  22496. that.subCameras.push(that._leftCamera);
  22497. that.subCameras.push(that._rightCamera);
  22498. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22499. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22500. that._anaglyphPostProcess.onApply = function (effect) {
  22501. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22502. };
  22503. that._update();
  22504. };
  22505. var AnaglyphArcRotateCamera = (function (_super) {
  22506. __extends(AnaglyphArcRotateCamera, _super);
  22507. // ANY
  22508. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22509. _super.call(this, name, alpha, beta, radius, target, scene);
  22510. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22511. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22512. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22513. buildCamera(this, name);
  22514. }
  22515. AnaglyphArcRotateCamera.prototype._update = function () {
  22516. this._updateCamera(this._leftCamera);
  22517. this._updateCamera(this._rightCamera);
  22518. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22519. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22520. _super.prototype._update.call(this);
  22521. };
  22522. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22523. camera.beta = this.beta;
  22524. camera.radius = this.radius;
  22525. camera.minZ = this.minZ;
  22526. camera.maxZ = this.maxZ;
  22527. camera.fov = this.fov;
  22528. camera.target = this.target;
  22529. };
  22530. return AnaglyphArcRotateCamera;
  22531. })(BABYLON.ArcRotateCamera);
  22532. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22533. var AnaglyphFreeCamera = (function (_super) {
  22534. __extends(AnaglyphFreeCamera, _super);
  22535. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22536. _super.call(this, name, position, scene);
  22537. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22538. this._transformMatrix = new BABYLON.Matrix();
  22539. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22540. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22541. buildCamera(this, name);
  22542. }
  22543. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22544. var target = this.getTarget();
  22545. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22546. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22547. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22548. };
  22549. AnaglyphFreeCamera.prototype._update = function () {
  22550. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22551. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22552. this._updateCamera(this._leftCamera);
  22553. this._updateCamera(this._rightCamera);
  22554. _super.prototype._update.call(this);
  22555. };
  22556. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22557. camera.minZ = this.minZ;
  22558. camera.maxZ = this.maxZ;
  22559. camera.fov = this.fov;
  22560. camera.viewport = this.viewport;
  22561. camera.setTarget(this.getTarget());
  22562. };
  22563. return AnaglyphFreeCamera;
  22564. })(BABYLON.FreeCamera);
  22565. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22566. })(BABYLON || (BABYLON = {}));
  22567. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22568. var BABYLON;
  22569. (function (BABYLON) {
  22570. var AnaglyphPostProcess = (function (_super) {
  22571. __extends(AnaglyphPostProcess, _super);
  22572. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22573. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22574. }
  22575. return AnaglyphPostProcess;
  22576. })(BABYLON.PostProcess);
  22577. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22578. })(BABYLON || (BABYLON = {}));
  22579. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22580. (function (BABYLON) {
  22581. var Tags = (function () {
  22582. function Tags() {
  22583. }
  22584. Tags.EnableFor = function (obj) {
  22585. obj._tags = obj._tags || {};
  22586. obj.hasTags = function () {
  22587. return Tags.HasTags(obj);
  22588. };
  22589. obj.addTags = function (tagsString) {
  22590. return Tags.AddTagsTo(obj, tagsString);
  22591. };
  22592. obj.removeTags = function (tagsString) {
  22593. return Tags.RemoveTagsFrom(obj, tagsString);
  22594. };
  22595. obj.matchesTagsQuery = function (tagsQuery) {
  22596. return Tags.MatchesQuery(obj, tagsQuery);
  22597. };
  22598. };
  22599. Tags.DisableFor = function (obj) {
  22600. delete obj._tags;
  22601. delete obj.hasTags;
  22602. delete obj.addTags;
  22603. delete obj.removeTags;
  22604. delete obj.matchesTagsQuery;
  22605. };
  22606. Tags.HasTags = function (obj) {
  22607. if (!obj._tags) {
  22608. return false;
  22609. }
  22610. return !BABYLON.Tools.IsEmpty(obj._tags);
  22611. };
  22612. Tags.GetTags = function (obj) {
  22613. if (!obj._tags) {
  22614. return null;
  22615. }
  22616. return obj._tags;
  22617. };
  22618. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22619. // a tag cannot start with '||', '&&', and '!'
  22620. // it cannot contain whitespaces
  22621. Tags.AddTagsTo = function (obj, tagsString) {
  22622. if (!tagsString) {
  22623. return;
  22624. }
  22625. var tags = tagsString.split(" ");
  22626. for (var t in tags) {
  22627. Tags._AddTagTo(obj, tags[t]);
  22628. }
  22629. };
  22630. Tags._AddTagTo = function (obj, tag) {
  22631. tag = tag.trim();
  22632. if (tag === "" || tag === "true" || tag === "false") {
  22633. return;
  22634. }
  22635. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22636. return;
  22637. }
  22638. Tags.EnableFor(obj);
  22639. obj._tags[tag] = true;
  22640. };
  22641. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22642. if (!Tags.HasTags(obj)) {
  22643. return;
  22644. }
  22645. var tags = tagsString.split(" ");
  22646. for (var t in tags) {
  22647. Tags._RemoveTagFrom(obj, tags[t]);
  22648. }
  22649. };
  22650. Tags._RemoveTagFrom = function (obj, tag) {
  22651. delete obj._tags[tag];
  22652. };
  22653. Tags.MatchesQuery = function (obj, tagsQuery) {
  22654. if (tagsQuery === undefined) {
  22655. return true;
  22656. }
  22657. if (tagsQuery === "") {
  22658. return Tags.HasTags(obj);
  22659. }
  22660. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22661. };
  22662. return Tags;
  22663. })();
  22664. BABYLON.Tags = Tags;
  22665. })(BABYLON || (BABYLON = {}));
  22666. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22667. (function (BABYLON) {
  22668. var Internals;
  22669. (function (Internals) {
  22670. var AndOrNotEvaluator = (function () {
  22671. function AndOrNotEvaluator() {
  22672. }
  22673. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22674. if (!query.match(/\([^\(\)]*\)/g)) {
  22675. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22676. }
  22677. else {
  22678. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22679. // remove parenthesis
  22680. r = r.slice(1, r.length - 1);
  22681. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22682. });
  22683. }
  22684. if (query === "true") {
  22685. return true;
  22686. }
  22687. if (query === "false") {
  22688. return false;
  22689. }
  22690. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22691. };
  22692. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22693. evaluateCallback = evaluateCallback || (function (r) {
  22694. return r === "true" ? true : false;
  22695. });
  22696. var result;
  22697. var or = parenthesisContent.split("||");
  22698. for (var i in or) {
  22699. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22700. var and = ori.split("&&");
  22701. if (and.length > 1) {
  22702. for (var j = 0; j < and.length; ++j) {
  22703. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22704. if (andj !== "true" && andj !== "false") {
  22705. if (andj[0] === "!") {
  22706. result = !evaluateCallback(andj.substring(1));
  22707. }
  22708. else {
  22709. result = evaluateCallback(andj);
  22710. }
  22711. }
  22712. else {
  22713. result = andj === "true" ? true : false;
  22714. }
  22715. if (!result) {
  22716. ori = "false";
  22717. break;
  22718. }
  22719. }
  22720. }
  22721. if (result || ori === "true") {
  22722. result = true;
  22723. break;
  22724. }
  22725. // result equals false (or undefined)
  22726. if (ori !== "true" && ori !== "false") {
  22727. if (ori[0] === "!") {
  22728. result = !evaluateCallback(ori.substring(1));
  22729. }
  22730. else {
  22731. result = evaluateCallback(ori);
  22732. }
  22733. }
  22734. else {
  22735. result = ori === "true" ? true : false;
  22736. }
  22737. }
  22738. // the whole parenthesis scope is replaced by 'true' or 'false'
  22739. return result ? "true" : "false";
  22740. };
  22741. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22742. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22743. // remove whitespaces
  22744. r = r.replace(/[\s]/g, function () { return ""; });
  22745. return r.length % 2 ? "!" : "";
  22746. });
  22747. booleanString = booleanString.trim();
  22748. if (booleanString === "!true") {
  22749. booleanString = "false";
  22750. }
  22751. else if (booleanString === "!false") {
  22752. booleanString = "true";
  22753. }
  22754. return booleanString;
  22755. };
  22756. return AndOrNotEvaluator;
  22757. })();
  22758. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22759. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22760. })(BABYLON || (BABYLON = {}));
  22761. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22762. (function (BABYLON) {
  22763. var PostProcessRenderPass = (function () {
  22764. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22765. this._enabled = true;
  22766. this._refCount = 0;
  22767. this._name = name;
  22768. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22769. this.setRenderList(renderList);
  22770. this._renderTexture.onBeforeRender = beforeRender;
  22771. this._renderTexture.onAfterRender = afterRender;
  22772. this._scene = scene;
  22773. this._renderList = renderList;
  22774. }
  22775. // private
  22776. PostProcessRenderPass.prototype._incRefCount = function () {
  22777. if (this._refCount === 0) {
  22778. this._scene.customRenderTargets.push(this._renderTexture);
  22779. }
  22780. return ++this._refCount;
  22781. };
  22782. PostProcessRenderPass.prototype._decRefCount = function () {
  22783. this._refCount--;
  22784. if (this._refCount <= 0) {
  22785. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22786. }
  22787. return this._refCount;
  22788. };
  22789. PostProcessRenderPass.prototype._update = function () {
  22790. this.setRenderList(this._renderList);
  22791. };
  22792. // public
  22793. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22794. this._renderTexture.renderList = renderList;
  22795. };
  22796. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22797. return this._renderTexture;
  22798. };
  22799. return PostProcessRenderPass;
  22800. })();
  22801. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22802. })(BABYLON || (BABYLON = {}));
  22803. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22804. (function (BABYLON) {
  22805. var PostProcessRenderEffect = (function () {
  22806. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22807. this._engine = engine;
  22808. this._name = name;
  22809. this._singleInstance = singleInstance || true;
  22810. this._getPostProcess = getPostProcess;
  22811. this._cameras = [];
  22812. this._indicesForCamera = [];
  22813. this._postProcesses = {};
  22814. this._renderPasses = {};
  22815. this._renderEffectAsPasses = {};
  22816. }
  22817. PostProcessRenderEffect.prototype._update = function () {
  22818. for (var renderPassName in this._renderPasses) {
  22819. this._renderPasses[renderPassName]._update();
  22820. }
  22821. };
  22822. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22823. this._renderPasses[renderPass._name] = renderPass;
  22824. this._linkParameters();
  22825. };
  22826. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22827. delete this._renderPasses[renderPass._name];
  22828. this._linkParameters();
  22829. };
  22830. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22831. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22832. this._linkParameters();
  22833. };
  22834. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22835. for (var renderPassName in this._renderPasses) {
  22836. if (renderPassName === passName) {
  22837. return this._renderPasses[passName];
  22838. }
  22839. }
  22840. };
  22841. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22842. this._renderPasses = {};
  22843. this._linkParameters();
  22844. };
  22845. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22846. var cameraKey;
  22847. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22848. for (var i = 0; i < _cam.length; i++) {
  22849. var camera = _cam[i];
  22850. var cameraName = camera.name;
  22851. if (this._singleInstance) {
  22852. cameraKey = 0;
  22853. }
  22854. else {
  22855. cameraKey = cameraName;
  22856. }
  22857. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22858. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22859. if (!this._indicesForCamera[cameraName]) {
  22860. this._indicesForCamera[cameraName] = [];
  22861. }
  22862. this._indicesForCamera[cameraName].push(index);
  22863. if (this._cameras.indexOf(camera) === -1) {
  22864. this._cameras[cameraName] = camera;
  22865. }
  22866. for (var passName in this._renderPasses) {
  22867. this._renderPasses[passName]._incRefCount();
  22868. }
  22869. }
  22870. this._linkParameters();
  22871. };
  22872. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22873. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22874. for (var i = 0; i < _cam.length; i++) {
  22875. var camera = _cam[i];
  22876. var cameraName = camera.name;
  22877. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22878. var index = this._cameras.indexOf(cameraName);
  22879. this._indicesForCamera.splice(index, 1);
  22880. this._cameras.splice(index, 1);
  22881. for (var passName in this._renderPasses) {
  22882. this._renderPasses[passName]._decRefCount();
  22883. }
  22884. }
  22885. };
  22886. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22887. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22888. for (var i = 0; i < _cam.length; i++) {
  22889. var camera = _cam[i];
  22890. var cameraName = camera.name;
  22891. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22892. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22893. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22894. }
  22895. }
  22896. for (var passName in this._renderPasses) {
  22897. this._renderPasses[passName]._incRefCount();
  22898. }
  22899. }
  22900. };
  22901. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22902. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22903. for (var i = 0; i < _cam.length; i++) {
  22904. var camera = _cam[i];
  22905. var cameraName = camera.Name;
  22906. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22907. for (var passName in this._renderPasses) {
  22908. this._renderPasses[passName]._decRefCount();
  22909. }
  22910. }
  22911. };
  22912. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22913. if (this._singleInstance) {
  22914. return this._postProcesses[0];
  22915. }
  22916. else {
  22917. return this._postProcesses[camera.name];
  22918. }
  22919. };
  22920. PostProcessRenderEffect.prototype._linkParameters = function () {
  22921. var _this = this;
  22922. for (var index in this._postProcesses) {
  22923. if (this.applyParameters) {
  22924. this.applyParameters(this._postProcesses[index]);
  22925. }
  22926. this._postProcesses[index].onBeforeRender = function (effect) {
  22927. _this._linkTextures(effect);
  22928. };
  22929. }
  22930. };
  22931. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22932. for (var renderPassName in this._renderPasses) {
  22933. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22934. }
  22935. for (var renderEffectName in this._renderEffectAsPasses) {
  22936. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22937. }
  22938. };
  22939. return PostProcessRenderEffect;
  22940. })();
  22941. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22942. })(BABYLON || (BABYLON = {}));
  22943. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22944. (function (BABYLON) {
  22945. var PostProcessRenderPipeline = (function () {
  22946. function PostProcessRenderPipeline(engine, name) {
  22947. this._engine = engine;
  22948. this._name = name;
  22949. this._renderEffects = {};
  22950. this._renderEffectsForIsolatedPass = {};
  22951. this._cameras = [];
  22952. }
  22953. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22954. this._renderEffects[renderEffect._name] = renderEffect;
  22955. };
  22956. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22957. var renderEffects = this._renderEffects[renderEffectName];
  22958. if (!renderEffects) {
  22959. return;
  22960. }
  22961. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22962. };
  22963. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22964. var renderEffects = this._renderEffects[renderEffectName];
  22965. if (!renderEffects) {
  22966. return;
  22967. }
  22968. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22969. };
  22970. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22971. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22972. var indicesToDelete = [];
  22973. for (var i = 0; i < _cam.length; i++) {
  22974. var camera = _cam[i];
  22975. var cameraName = camera.name;
  22976. if (this._cameras.indexOf(camera) === -1) {
  22977. this._cameras[cameraName] = camera;
  22978. }
  22979. else if (unique) {
  22980. indicesToDelete.push(i);
  22981. }
  22982. }
  22983. for (var i = 0; i < indicesToDelete.length; i++) {
  22984. cameras.splice(indicesToDelete[i], 1);
  22985. }
  22986. for (var renderEffectName in this._renderEffects) {
  22987. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22988. }
  22989. };
  22990. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22991. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22992. for (var renderEffectName in this._renderEffects) {
  22993. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22994. }
  22995. for (var i = 0; i < _cam.length; i++) {
  22996. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22997. }
  22998. };
  22999. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23000. var _this = this;
  23001. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23002. var pass = null;
  23003. for (var renderEffectName in this._renderEffects) {
  23004. pass = this._renderEffects[renderEffectName].getPass(passName);
  23005. if (pass != null) {
  23006. break;
  23007. }
  23008. }
  23009. if (pass === null) {
  23010. return;
  23011. }
  23012. for (var renderEffectName in this._renderEffects) {
  23013. this._renderEffects[renderEffectName]._disable(_cam);
  23014. }
  23015. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23016. for (var i = 0; i < _cam.length; i++) {
  23017. var camera = _cam[i];
  23018. var cameraName = camera.name;
  23019. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23020. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23021. });
  23022. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23023. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23024. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23025. }
  23026. };
  23027. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23028. var _this = this;
  23029. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23030. for (var i = 0; i < _cam.length; i++) {
  23031. var camera = _cam[i];
  23032. var cameraName = camera.name;
  23033. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23034. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23035. });
  23036. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23037. }
  23038. for (var renderEffectName in this._renderEffects) {
  23039. this._renderEffects[renderEffectName]._enable(_cam);
  23040. }
  23041. };
  23042. PostProcessRenderPipeline.prototype._update = function () {
  23043. for (var renderEffectName in this._renderEffects) {
  23044. this._renderEffects[renderEffectName]._update();
  23045. }
  23046. for (var i = 0; i < this._cameras.length; i++) {
  23047. var cameraName = this._cameras[i].name;
  23048. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23049. this._renderEffectsForIsolatedPass[cameraName]._update();
  23050. }
  23051. }
  23052. };
  23053. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23054. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23055. return PostProcessRenderPipeline;
  23056. })();
  23057. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23058. })(BABYLON || (BABYLON = {}));
  23059. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23060. (function (BABYLON) {
  23061. var PostProcessRenderPipelineManager = (function () {
  23062. function PostProcessRenderPipelineManager() {
  23063. this._renderPipelines = {};
  23064. }
  23065. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23066. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23067. };
  23068. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23069. var renderPipeline = this._renderPipelines[renderPipelineName];
  23070. if (!renderPipeline) {
  23071. return;
  23072. }
  23073. renderPipeline._attachCameras(cameras, unique);
  23074. };
  23075. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23076. var renderPipeline = this._renderPipelines[renderPipelineName];
  23077. if (!renderPipeline) {
  23078. return;
  23079. }
  23080. renderPipeline._detachCameras(cameras);
  23081. };
  23082. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23083. var renderPipeline = this._renderPipelines[renderPipelineName];
  23084. if (!renderPipeline) {
  23085. return;
  23086. }
  23087. renderPipeline._enableEffect(renderEffectName, cameras);
  23088. };
  23089. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23090. var renderPipeline = this._renderPipelines[renderPipelineName];
  23091. if (!renderPipeline) {
  23092. return;
  23093. }
  23094. renderPipeline._disableEffect(renderEffectName, cameras);
  23095. };
  23096. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23097. var renderPipeline = this._renderPipelines[renderPipelineName];
  23098. if (!renderPipeline) {
  23099. return;
  23100. }
  23101. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23102. };
  23103. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23104. var renderPipeline = this._renderPipelines[renderPipelineName];
  23105. if (!renderPipeline) {
  23106. return;
  23107. }
  23108. renderPipeline._disableDisplayOnlyPass(cameras);
  23109. };
  23110. PostProcessRenderPipelineManager.prototype.update = function () {
  23111. for (var renderPipelineName in this._renderPipelines) {
  23112. this._renderPipelines[renderPipelineName]._update();
  23113. }
  23114. };
  23115. return PostProcessRenderPipelineManager;
  23116. })();
  23117. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23118. })(BABYLON || (BABYLON = {}));
  23119. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23120. var BABYLON;
  23121. (function (BABYLON) {
  23122. var DisplayPassPostProcess = (function (_super) {
  23123. __extends(DisplayPassPostProcess, _super);
  23124. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23125. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23126. }
  23127. return DisplayPassPostProcess;
  23128. })(BABYLON.PostProcess);
  23129. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23130. })(BABYLON || (BABYLON = {}));
  23131. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23132. (function (BABYLON) {
  23133. var BoundingBoxRenderer = (function () {
  23134. function BoundingBoxRenderer(scene) {
  23135. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23136. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23137. this.showBackLines = true;
  23138. this.renderList = new BABYLON.SmartArray(32);
  23139. this._scene = scene;
  23140. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23141. attributes: ["position"],
  23142. uniforms: ["worldViewProjection", "color"]
  23143. });
  23144. var engine = this._scene.getEngine();
  23145. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23146. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23147. 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]);
  23148. }
  23149. BoundingBoxRenderer.prototype.reset = function () {
  23150. this.renderList.reset();
  23151. };
  23152. BoundingBoxRenderer.prototype.render = function () {
  23153. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  23154. return;
  23155. }
  23156. var engine = this._scene.getEngine();
  23157. engine.setDepthWrite(false);
  23158. this._colorShader._preBind();
  23159. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23160. var boundingBox = this.renderList.data[boundingBoxIndex];
  23161. var min = boundingBox.minimum;
  23162. var max = boundingBox.maximum;
  23163. var diff = max.subtract(min);
  23164. var median = min.add(diff.scale(0.5));
  23165. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23166. // VBOs
  23167. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23168. if (this.showBackLines) {
  23169. // Back
  23170. engine.setDepthFunctionToGreaterOrEqual();
  23171. this._scene.resetCachedMaterial();
  23172. this._colorShader.setColor4("color", this.backColor.toColor4());
  23173. this._colorShader.bind(worldMatrix);
  23174. // Draw order
  23175. engine.draw(false, 0, 24);
  23176. }
  23177. // Front
  23178. engine.setDepthFunctionToLess();
  23179. this._scene.resetCachedMaterial();
  23180. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23181. this._colorShader.bind(worldMatrix);
  23182. // Draw order
  23183. engine.draw(false, 0, 24);
  23184. }
  23185. this._colorShader.unbind();
  23186. engine.setDepthFunctionToLessOrEqual();
  23187. engine.setDepthWrite(true);
  23188. };
  23189. BoundingBoxRenderer.prototype.dispose = function () {
  23190. this._colorShader.dispose();
  23191. this._vb.dispose();
  23192. this._scene.getEngine()._releaseBuffer(this._ib);
  23193. };
  23194. return BoundingBoxRenderer;
  23195. })();
  23196. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23197. })(BABYLON || (BABYLON = {}));
  23198. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23199. (function (BABYLON) {
  23200. var Internals;
  23201. (function (Internals) {
  23202. /*
  23203. * Based on jsTGALoader - Javascript loader for TGA file
  23204. * By Vincent Thibault
  23205. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23206. */
  23207. var TGATools = (function () {
  23208. function TGATools() {
  23209. }
  23210. TGATools.GetTGAHeader = function (data) {
  23211. var offset = 0;
  23212. var header = {
  23213. id_length: data[offset++],
  23214. colormap_type: data[offset++],
  23215. image_type: data[offset++],
  23216. colormap_index: data[offset++] | data[offset++] << 8,
  23217. colormap_length: data[offset++] | data[offset++] << 8,
  23218. colormap_size: data[offset++],
  23219. origin: [
  23220. data[offset++] | data[offset++] << 8,
  23221. data[offset++] | data[offset++] << 8
  23222. ],
  23223. width: data[offset++] | data[offset++] << 8,
  23224. height: data[offset++] | data[offset++] << 8,
  23225. pixel_size: data[offset++],
  23226. flags: data[offset++]
  23227. };
  23228. return header;
  23229. };
  23230. TGATools.UploadContent = function (gl, data) {
  23231. // Not enough data to contain header ?
  23232. if (data.length < 19) {
  23233. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23234. return;
  23235. }
  23236. // Read Header
  23237. var offset = 18;
  23238. var header = TGATools.GetTGAHeader(data);
  23239. // Assume it's a valid Targa file.
  23240. if (header.id_length + offset > data.length) {
  23241. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23242. return;
  23243. }
  23244. // Skip not needed data
  23245. offset += header.id_length;
  23246. var use_rle = false;
  23247. var use_pal = false;
  23248. var use_rgb = false;
  23249. var use_grey = false;
  23250. switch (header.image_type) {
  23251. case TGATools._TYPE_RLE_INDEXED:
  23252. use_rle = true;
  23253. case TGATools._TYPE_INDEXED:
  23254. use_pal = true;
  23255. break;
  23256. case TGATools._TYPE_RLE_RGB:
  23257. use_rle = true;
  23258. case TGATools._TYPE_RGB:
  23259. use_rgb = true;
  23260. break;
  23261. case TGATools._TYPE_RLE_GREY:
  23262. use_rle = true;
  23263. case TGATools._TYPE_GREY:
  23264. use_grey = true;
  23265. break;
  23266. }
  23267. var pixel_data;
  23268. var numAlphaBits = header.flags & 0xf;
  23269. var pixel_size = header.pixel_size >> 3;
  23270. var pixel_total = header.width * header.height * pixel_size;
  23271. // Read palettes
  23272. var palettes;
  23273. if (use_pal) {
  23274. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23275. }
  23276. // Read LRE
  23277. if (use_rle) {
  23278. pixel_data = new Uint8Array(pixel_total);
  23279. var c, count, i;
  23280. var localOffset = 0;
  23281. var pixels = new Uint8Array(pixel_size);
  23282. while (offset < pixel_total && localOffset < pixel_total) {
  23283. c = data[offset++];
  23284. count = (c & 0x7f) + 1;
  23285. // RLE pixels
  23286. if (c & 0x80) {
  23287. for (i = 0; i < pixel_size; ++i) {
  23288. pixels[i] = data[offset++];
  23289. }
  23290. for (i = 0; i < count; ++i) {
  23291. pixel_data.set(pixels, localOffset + i * pixel_size);
  23292. }
  23293. localOffset += pixel_size * count;
  23294. }
  23295. else {
  23296. count *= pixel_size;
  23297. for (i = 0; i < count; ++i) {
  23298. pixel_data[localOffset + i] = data[offset++];
  23299. }
  23300. localOffset += count;
  23301. }
  23302. }
  23303. }
  23304. else {
  23305. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23306. }
  23307. // Load to texture
  23308. var x_start, y_start, x_step, y_step, y_end, x_end;
  23309. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23310. default:
  23311. case TGATools._ORIGIN_UL:
  23312. x_start = 0;
  23313. x_step = 1;
  23314. x_end = header.width;
  23315. y_start = 0;
  23316. y_step = 1;
  23317. y_end = header.height;
  23318. break;
  23319. case TGATools._ORIGIN_BL:
  23320. x_start = 0;
  23321. x_step = 1;
  23322. x_end = header.width;
  23323. y_start = header.height - 1;
  23324. y_step = -1;
  23325. y_end = -1;
  23326. break;
  23327. case TGATools._ORIGIN_UR:
  23328. x_start = header.width - 1;
  23329. x_step = -1;
  23330. x_end = -1;
  23331. y_start = 0;
  23332. y_step = 1;
  23333. y_end = header.height;
  23334. break;
  23335. case TGATools._ORIGIN_BR:
  23336. x_start = header.width - 1;
  23337. x_step = -1;
  23338. x_end = -1;
  23339. y_start = header.height - 1;
  23340. y_step = -1;
  23341. y_end = -1;
  23342. break;
  23343. }
  23344. // Load the specify method
  23345. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23346. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23347. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23348. };
  23349. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23350. var image = pixel_data, colormap = palettes;
  23351. var width = header.width, height = header.height;
  23352. var color, i = 0, x, y;
  23353. var imageData = new Uint8Array(width * height * 4);
  23354. for (y = y_start; y !== y_end; y += y_step) {
  23355. for (x = x_start; x !== x_end; x += x_step, i++) {
  23356. color = image[i];
  23357. imageData[(x + width * y) * 4 + 3] = 255;
  23358. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23359. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23360. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23361. }
  23362. }
  23363. return imageData;
  23364. };
  23365. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23366. var image = pixel_data;
  23367. var width = header.width, height = header.height;
  23368. var color, i = 0, x, y;
  23369. var imageData = new Uint8Array(width * height * 4);
  23370. for (y = y_start; y !== y_end; y += y_step) {
  23371. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23372. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23373. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23374. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23375. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23376. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23377. }
  23378. }
  23379. return imageData;
  23380. };
  23381. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23382. var image = pixel_data;
  23383. var width = header.width, height = header.height;
  23384. var i = 0, x, y;
  23385. var imageData = new Uint8Array(width * height * 4);
  23386. for (y = y_start; y !== y_end; y += y_step) {
  23387. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23388. imageData[(x + width * y) * 4 + 3] = 255;
  23389. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23390. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23391. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23392. }
  23393. }
  23394. return imageData;
  23395. };
  23396. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23397. var image = pixel_data;
  23398. var width = header.width, height = header.height;
  23399. var i = 0, x, y;
  23400. var imageData = new Uint8Array(width * height * 4);
  23401. for (y = y_start; y !== y_end; y += y_step) {
  23402. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23403. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23404. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23405. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23406. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23407. }
  23408. }
  23409. return imageData;
  23410. };
  23411. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23412. var image = pixel_data;
  23413. var width = header.width, height = header.height;
  23414. var color, i = 0, x, y;
  23415. var imageData = new Uint8Array(width * height * 4);
  23416. for (y = y_start; y !== y_end; y += y_step) {
  23417. for (x = x_start; x !== x_end; x += x_step, i++) {
  23418. color = image[i];
  23419. imageData[(x + width * y) * 4 + 0] = color;
  23420. imageData[(x + width * y) * 4 + 1] = color;
  23421. imageData[(x + width * y) * 4 + 2] = color;
  23422. imageData[(x + width * y) * 4 + 3] = 255;
  23423. }
  23424. }
  23425. return imageData;
  23426. };
  23427. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23428. var image = pixel_data;
  23429. var width = header.width, height = header.height;
  23430. var i = 0, x, y;
  23431. var imageData = new Uint8Array(width * height * 4);
  23432. for (y = y_start; y !== y_end; y += y_step) {
  23433. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23434. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23435. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23436. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23437. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23438. }
  23439. }
  23440. return imageData;
  23441. };
  23442. TGATools._TYPE_NO_DATA = 0;
  23443. TGATools._TYPE_INDEXED = 1;
  23444. TGATools._TYPE_RGB = 2;
  23445. TGATools._TYPE_GREY = 3;
  23446. TGATools._TYPE_RLE_INDEXED = 9;
  23447. TGATools._TYPE_RLE_RGB = 10;
  23448. TGATools._TYPE_RLE_GREY = 11;
  23449. TGATools._ORIGIN_MASK = 0x30;
  23450. TGATools._ORIGIN_SHIFT = 0x04;
  23451. TGATools._ORIGIN_BL = 0x00;
  23452. TGATools._ORIGIN_BR = 0x01;
  23453. TGATools._ORIGIN_UL = 0x02;
  23454. TGATools._ORIGIN_UR = 0x03;
  23455. return TGATools;
  23456. })();
  23457. Internals.TGATools = TGATools;
  23458. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23459. })(BABYLON || (BABYLON = {}));
  23460. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23461. (function (BABYLON) {
  23462. var Internals;
  23463. (function (Internals) {
  23464. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23465. // All values and structures referenced from:
  23466. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23467. var DDS_MAGIC = 0x20534444;
  23468. 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;
  23469. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23470. 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;
  23471. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23472. function FourCCToInt32(value) {
  23473. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23474. }
  23475. function Int32ToFourCC(value) {
  23476. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23477. }
  23478. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23479. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23480. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23481. var headerLengthInt = 31; // The header length in 32 bit ints
  23482. // Offsets into the header array
  23483. var off_magic = 0;
  23484. var off_size = 1;
  23485. var off_flags = 2;
  23486. var off_height = 3;
  23487. var off_width = 4;
  23488. var off_mipmapCount = 7;
  23489. var off_pfFlags = 20;
  23490. var off_pfFourCC = 21;
  23491. var off_RGBbpp = 22;
  23492. var off_RMask = 23;
  23493. var off_GMask = 24;
  23494. var off_BMask = 25;
  23495. var off_AMask = 26;
  23496. var off_caps1 = 27;
  23497. var off_caps2 = 28;
  23498. ;
  23499. var DDSTools = (function () {
  23500. function DDSTools() {
  23501. }
  23502. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23503. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23504. var mipmapCount = 1;
  23505. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23506. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23507. }
  23508. return {
  23509. width: header[off_width],
  23510. height: header[off_height],
  23511. mipmapCount: mipmapCount,
  23512. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23513. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23514. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23515. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23516. };
  23517. };
  23518. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23519. var byteArray = new Uint8Array(dataLength);
  23520. var srcData = new Uint8Array(arrayBuffer);
  23521. var index = 0;
  23522. for (var y = height - 1; y >= 0; y--) {
  23523. for (var x = 0; x < width; x++) {
  23524. var srcPos = dataOffset + (x + y * width) * 4;
  23525. byteArray[index + 2] = srcData[srcPos];
  23526. byteArray[index + 1] = srcData[srcPos + 1];
  23527. byteArray[index] = srcData[srcPos + 2];
  23528. byteArray[index + 3] = srcData[srcPos + 3];
  23529. index += 4;
  23530. }
  23531. }
  23532. return byteArray;
  23533. };
  23534. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23535. var byteArray = new Uint8Array(dataLength);
  23536. var srcData = new Uint8Array(arrayBuffer);
  23537. var index = 0;
  23538. for (var y = height - 1; y >= 0; y--) {
  23539. for (var x = 0; x < width; x++) {
  23540. var srcPos = dataOffset + (x + y * width) * 3;
  23541. byteArray[index + 2] = srcData[srcPos];
  23542. byteArray[index + 1] = srcData[srcPos + 1];
  23543. byteArray[index] = srcData[srcPos + 2];
  23544. index += 3;
  23545. }
  23546. }
  23547. return byteArray;
  23548. };
  23549. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23550. var byteArray = new Uint8Array(dataLength);
  23551. var srcData = new Uint8Array(arrayBuffer);
  23552. var index = 0;
  23553. for (var y = height - 1; y >= 0; y--) {
  23554. for (var x = 0; x < width; x++) {
  23555. var srcPos = dataOffset + (x + y * width);
  23556. byteArray[index] = srcData[srcPos];
  23557. index++;
  23558. }
  23559. }
  23560. return byteArray;
  23561. };
  23562. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23563. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23564. if (header[off_magic] != DDS_MAGIC) {
  23565. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23566. return;
  23567. }
  23568. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23569. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23570. return;
  23571. }
  23572. if (info.isFourCC) {
  23573. fourCC = header[off_pfFourCC];
  23574. switch (fourCC) {
  23575. case FOURCC_DXT1:
  23576. blockBytes = 8;
  23577. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23578. break;
  23579. case FOURCC_DXT3:
  23580. blockBytes = 16;
  23581. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23582. break;
  23583. case FOURCC_DXT5:
  23584. blockBytes = 16;
  23585. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23586. break;
  23587. default:
  23588. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23589. return;
  23590. }
  23591. }
  23592. mipmapCount = 1;
  23593. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23594. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23595. }
  23596. var bpp = header[off_RGBbpp];
  23597. for (var face = 0; face < faces; face++) {
  23598. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23599. width = header[off_width];
  23600. height = header[off_height];
  23601. dataOffset = header[off_size] + 4;
  23602. for (i = 0; i < mipmapCount; ++i) {
  23603. if (info.isRGB) {
  23604. if (bpp == 24) {
  23605. dataLength = width * height * 3;
  23606. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23607. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23608. }
  23609. else {
  23610. dataLength = width * height * 4;
  23611. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23612. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23613. }
  23614. }
  23615. else if (info.isLuminance) {
  23616. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23617. var unpaddedRowSize = width;
  23618. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23619. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23620. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23621. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23622. }
  23623. else {
  23624. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23625. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23626. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23627. }
  23628. dataOffset += dataLength;
  23629. width *= 0.5;
  23630. height *= 0.5;
  23631. width = Math.max(1.0, width);
  23632. height = Math.max(1.0, height);
  23633. }
  23634. }
  23635. };
  23636. return DDSTools;
  23637. })();
  23638. Internals.DDSTools = DDSTools;
  23639. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23640. })(BABYLON || (BABYLON = {}));
  23641. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23642. (function (BABYLON) {
  23643. var SmartArray = (function () {
  23644. function SmartArray(capacity) {
  23645. this.length = 0;
  23646. this._duplicateId = 0;
  23647. this.data = new Array(capacity);
  23648. this._id = SmartArray._GlobalId++;
  23649. }
  23650. SmartArray.prototype.push = function (value) {
  23651. this.data[this.length++] = value;
  23652. if (this.length > this.data.length) {
  23653. this.data.length *= 2;
  23654. }
  23655. if (!value.__smartArrayFlags) {
  23656. value.__smartArrayFlags = {};
  23657. }
  23658. value.__smartArrayFlags[this._id] = this._duplicateId;
  23659. };
  23660. SmartArray.prototype.pushNoDuplicate = function (value) {
  23661. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23662. return;
  23663. }
  23664. this.push(value);
  23665. };
  23666. SmartArray.prototype.sort = function (compareFn) {
  23667. this.data.sort(compareFn);
  23668. };
  23669. SmartArray.prototype.reset = function () {
  23670. this.length = 0;
  23671. this._duplicateId++;
  23672. };
  23673. SmartArray.prototype.concat = function (array) {
  23674. if (array.length === 0) {
  23675. return;
  23676. }
  23677. if (this.length + array.length > this.data.length) {
  23678. this.data.length = (this.length + array.length) * 2;
  23679. }
  23680. for (var index = 0; index < array.length; index++) {
  23681. this.data[this.length++] = (array.data || array)[index];
  23682. }
  23683. };
  23684. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23685. if (array.length === 0) {
  23686. return;
  23687. }
  23688. if (this.length + array.length > this.data.length) {
  23689. this.data.length = (this.length + array.length) * 2;
  23690. }
  23691. for (var index = 0; index < array.length; index++) {
  23692. var item = (array.data || array)[index];
  23693. this.pushNoDuplicate(item);
  23694. }
  23695. };
  23696. SmartArray.prototype.indexOf = function (value) {
  23697. var position = this.data.indexOf(value);
  23698. if (position >= this.length) {
  23699. return -1;
  23700. }
  23701. return position;
  23702. };
  23703. // Statics
  23704. SmartArray._GlobalId = 0;
  23705. return SmartArray;
  23706. })();
  23707. BABYLON.SmartArray = SmartArray;
  23708. })(BABYLON || (BABYLON = {}));
  23709. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23710. (function (BABYLON) {
  23711. var CannonJSPlugin = (function () {
  23712. function CannonJSPlugin() {
  23713. this._registeredMeshes = [];
  23714. this._physicsMaterials = [];
  23715. this.updateBodyPosition = function (mesh) {
  23716. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23717. var registeredMesh = this._registeredMeshes[index];
  23718. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23719. var body = registeredMesh.body;
  23720. var center = mesh.getBoundingInfo().boundingBox.center;
  23721. body.position.set(center.x, center.z, center.y);
  23722. body.quaternion.x = mesh.rotationQuaternion.x;
  23723. body.quaternion.z = mesh.rotationQuaternion.y;
  23724. body.quaternion.y = mesh.rotationQuaternion.z;
  23725. body.quaternion.w = -mesh.rotationQuaternion.w;
  23726. return;
  23727. }
  23728. }
  23729. };
  23730. }
  23731. CannonJSPlugin.prototype.initialize = function (iterations) {
  23732. if (iterations === void 0) { iterations = 10; }
  23733. this._world = new CANNON.World();
  23734. this._world.broadphase = new CANNON.NaiveBroadphase();
  23735. this._world.solver.iterations = iterations;
  23736. };
  23737. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23738. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23739. };
  23740. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23741. this._world.step(delta);
  23742. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23743. var registeredMesh = this._registeredMeshes[index];
  23744. if (registeredMesh.isChild) {
  23745. continue;
  23746. }
  23747. // Body position
  23748. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23749. var deltaPos = registeredMesh.delta;
  23750. if (deltaPos) {
  23751. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23752. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23753. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23754. }
  23755. else {
  23756. registeredMesh.mesh.position.x = bodyX;
  23757. registeredMesh.mesh.position.y = bodyZ;
  23758. registeredMesh.mesh.position.z = bodyY;
  23759. }
  23760. if (!registeredMesh.mesh.rotationQuaternion) {
  23761. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23762. }
  23763. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23764. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23765. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23766. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23767. }
  23768. };
  23769. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23770. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23771. };
  23772. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23773. this.unregisterMesh(mesh);
  23774. mesh.computeWorldMatrix(true);
  23775. switch (impostor) {
  23776. case BABYLON.PhysicsEngine.SphereImpostor:
  23777. var bbox = mesh.getBoundingInfo().boundingBox;
  23778. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23779. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23780. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23781. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23782. case BABYLON.PhysicsEngine.BoxImpostor:
  23783. bbox = mesh.getBoundingInfo().boundingBox;
  23784. var min = bbox.minimumWorld;
  23785. var max = bbox.maximumWorld;
  23786. var box = max.subtract(min).scale(0.5);
  23787. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23788. case BABYLON.PhysicsEngine.PlaneImpostor:
  23789. return this._createPlane(mesh, options);
  23790. case BABYLON.PhysicsEngine.MeshImpostor:
  23791. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23792. var rawFaces = mesh.getIndices();
  23793. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23794. }
  23795. return null;
  23796. };
  23797. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23798. var shape = new CANNON.Sphere(radius);
  23799. if (!options) {
  23800. return shape;
  23801. }
  23802. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23803. };
  23804. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23805. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23806. if (!options) {
  23807. return shape;
  23808. }
  23809. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23810. };
  23811. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23812. var shape = new CANNON.Plane();
  23813. if (!options) {
  23814. return shape;
  23815. }
  23816. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23817. };
  23818. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23819. var verts = [], faces = [];
  23820. mesh.computeWorldMatrix(true);
  23821. for (var i = 0; i < rawVerts.length; i += 3) {
  23822. var transformed = BABYLON.Vector3.Zero();
  23823. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23824. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23825. }
  23826. for (var j = 0; j < rawFaces.length; j += 3) {
  23827. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23828. }
  23829. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23830. if (!options) {
  23831. return shape;
  23832. }
  23833. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23834. };
  23835. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23836. var index;
  23837. var mat;
  23838. for (index = 0; index < this._physicsMaterials.length; index++) {
  23839. mat = this._physicsMaterials[index];
  23840. if (mat.friction === friction && mat.restitution === restitution) {
  23841. return mat;
  23842. }
  23843. }
  23844. var currentMat = new CANNON.Material();
  23845. currentMat.friction = friction;
  23846. currentMat.restitution = restitution;
  23847. this._physicsMaterials.push(currentMat);
  23848. for (index = 0; index < this._physicsMaterials.length; index++) {
  23849. mat = this._physicsMaterials[index];
  23850. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23851. contactMaterial.contactEquationStiffness = 1e10;
  23852. contactMaterial.contactEquationRegularizationTime = 10;
  23853. this._world.addContactMaterial(contactMaterial);
  23854. }
  23855. return currentMat;
  23856. };
  23857. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23858. var initialRotation = null;
  23859. if (mesh.rotationQuaternion) {
  23860. initialRotation = mesh.rotationQuaternion.clone();
  23861. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23862. }
  23863. // The delta between the mesh position and the mesh bounding box center
  23864. var bbox = mesh.getBoundingInfo().boundingBox;
  23865. var deltaPosition = mesh.position.subtract(bbox.center);
  23866. var material = this._addMaterial(friction, restitution);
  23867. var body = new CANNON.RigidBody(mass, shape, material);
  23868. if (initialRotation) {
  23869. body.quaternion.x = initialRotation.x;
  23870. body.quaternion.z = initialRotation.y;
  23871. body.quaternion.y = initialRotation.z;
  23872. body.quaternion.w = -initialRotation.w;
  23873. }
  23874. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23875. this._world.add(body);
  23876. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23877. return body;
  23878. };
  23879. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23880. var compoundShape = new CANNON.Compound();
  23881. for (var index = 0; index < parts.length; index++) {
  23882. var mesh = parts[index].mesh;
  23883. var shape = this.registerMesh(mesh, parts[index].impostor);
  23884. if (index == 0) {
  23885. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23886. }
  23887. else {
  23888. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23889. }
  23890. }
  23891. var initialMesh = parts[0].mesh;
  23892. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23893. body.parts = parts;
  23894. return body;
  23895. };
  23896. CannonJSPlugin.prototype._unbindBody = function (body) {
  23897. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23898. var registeredMesh = this._registeredMeshes[index];
  23899. if (registeredMesh.body === body) {
  23900. registeredMesh.body = null;
  23901. registeredMesh.delta = 0;
  23902. }
  23903. }
  23904. };
  23905. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23906. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23907. var registeredMesh = this._registeredMeshes[index];
  23908. if (registeredMesh.mesh === mesh) {
  23909. // Remove body
  23910. if (registeredMesh.body) {
  23911. this._world.remove(registeredMesh.body);
  23912. this._unbindBody(registeredMesh.body);
  23913. }
  23914. this._registeredMeshes.splice(index, 1);
  23915. return;
  23916. }
  23917. }
  23918. };
  23919. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23920. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23921. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23922. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23923. var registeredMesh = this._registeredMeshes[index];
  23924. if (registeredMesh.mesh === mesh) {
  23925. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23926. return;
  23927. }
  23928. }
  23929. };
  23930. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23931. var body1 = null, body2 = null;
  23932. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23933. var registeredMesh = this._registeredMeshes[index];
  23934. if (registeredMesh.mesh === mesh1) {
  23935. body1 = registeredMesh.body;
  23936. }
  23937. else if (registeredMesh.mesh === mesh2) {
  23938. body2 = registeredMesh.body;
  23939. }
  23940. }
  23941. if (!body1 || !body2) {
  23942. return false;
  23943. }
  23944. 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));
  23945. this._world.addConstraint(constraint);
  23946. return true;
  23947. };
  23948. CannonJSPlugin.prototype.dispose = function () {
  23949. while (this._registeredMeshes.length) {
  23950. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23951. }
  23952. };
  23953. CannonJSPlugin.prototype.isSupported = function () {
  23954. return window.CANNON !== undefined;
  23955. };
  23956. return CannonJSPlugin;
  23957. })();
  23958. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23959. })(BABYLON || (BABYLON = {}));
  23960. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23961. var BABYLON;
  23962. (function (BABYLON) {
  23963. var Condition = (function () {
  23964. function Condition(actionManager) {
  23965. this._actionManager = actionManager;
  23966. }
  23967. Condition.prototype.isValid = function () {
  23968. return true;
  23969. };
  23970. Condition.prototype._getProperty = function (propertyPath) {
  23971. return this._actionManager._getProperty(propertyPath);
  23972. };
  23973. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23974. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23975. };
  23976. return Condition;
  23977. })();
  23978. BABYLON.Condition = Condition;
  23979. var ValueCondition = (function (_super) {
  23980. __extends(ValueCondition, _super);
  23981. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23982. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23983. _super.call(this, actionManager);
  23984. this.propertyPath = propertyPath;
  23985. this.value = value;
  23986. this.operator = operator;
  23987. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23988. this._property = this._getProperty(this.propertyPath);
  23989. }
  23990. Object.defineProperty(ValueCondition, "IsEqual", {
  23991. get: function () {
  23992. return ValueCondition._IsEqual;
  23993. },
  23994. enumerable: true,
  23995. configurable: true
  23996. });
  23997. Object.defineProperty(ValueCondition, "IsDifferent", {
  23998. get: function () {
  23999. return ValueCondition._IsDifferent;
  24000. },
  24001. enumerable: true,
  24002. configurable: true
  24003. });
  24004. Object.defineProperty(ValueCondition, "IsGreater", {
  24005. get: function () {
  24006. return ValueCondition._IsGreater;
  24007. },
  24008. enumerable: true,
  24009. configurable: true
  24010. });
  24011. Object.defineProperty(ValueCondition, "IsLesser", {
  24012. get: function () {
  24013. return ValueCondition._IsLesser;
  24014. },
  24015. enumerable: true,
  24016. configurable: true
  24017. });
  24018. // Methods
  24019. ValueCondition.prototype.isValid = function () {
  24020. switch (this.operator) {
  24021. case ValueCondition.IsGreater:
  24022. return this._target[this._property] > this.value;
  24023. case ValueCondition.IsLesser:
  24024. return this._target[this._property] < this.value;
  24025. case ValueCondition.IsEqual:
  24026. case ValueCondition.IsDifferent:
  24027. var check;
  24028. if (this.value.equals) {
  24029. check = this.value.equals(this._target[this._property]);
  24030. }
  24031. else {
  24032. check = this.value === this._target[this._property];
  24033. }
  24034. return this.operator === ValueCondition.IsEqual ? check : !check;
  24035. }
  24036. return false;
  24037. };
  24038. // Statics
  24039. ValueCondition._IsEqual = 0;
  24040. ValueCondition._IsDifferent = 1;
  24041. ValueCondition._IsGreater = 2;
  24042. ValueCondition._IsLesser = 3;
  24043. return ValueCondition;
  24044. })(Condition);
  24045. BABYLON.ValueCondition = ValueCondition;
  24046. var PredicateCondition = (function (_super) {
  24047. __extends(PredicateCondition, _super);
  24048. function PredicateCondition(actionManager, predicate) {
  24049. _super.call(this, actionManager);
  24050. this.predicate = predicate;
  24051. }
  24052. PredicateCondition.prototype.isValid = function () {
  24053. return this.predicate();
  24054. };
  24055. return PredicateCondition;
  24056. })(Condition);
  24057. BABYLON.PredicateCondition = PredicateCondition;
  24058. var StateCondition = (function (_super) {
  24059. __extends(StateCondition, _super);
  24060. function StateCondition(actionManager, target, value) {
  24061. _super.call(this, actionManager);
  24062. this.value = value;
  24063. this._target = target;
  24064. }
  24065. // Methods
  24066. StateCondition.prototype.isValid = function () {
  24067. return this._target.state === this.value;
  24068. };
  24069. return StateCondition;
  24070. })(Condition);
  24071. BABYLON.StateCondition = StateCondition;
  24072. })(BABYLON || (BABYLON = {}));
  24073. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24074. (function (BABYLON) {
  24075. var Action = (function () {
  24076. function Action(triggerOptions, condition) {
  24077. this.triggerOptions = triggerOptions;
  24078. if (triggerOptions.parameter) {
  24079. this.trigger = triggerOptions.trigger;
  24080. this._triggerParameter = triggerOptions.parameter;
  24081. }
  24082. else {
  24083. this.trigger = triggerOptions;
  24084. }
  24085. this._nextActiveAction = this;
  24086. this._condition = condition;
  24087. }
  24088. // Methods
  24089. Action.prototype._prepare = function () {
  24090. };
  24091. Action.prototype.getTriggerParameter = function () {
  24092. return this._triggerParameter;
  24093. };
  24094. Action.prototype._executeCurrent = function (evt) {
  24095. if (this._nextActiveAction._condition) {
  24096. var condition = this._nextActiveAction._condition;
  24097. var currentRenderId = this._actionManager.getScene().getRenderId();
  24098. // We cache the current evaluation for the current frame
  24099. if (condition._evaluationId === currentRenderId) {
  24100. if (!condition._currentResult) {
  24101. return;
  24102. }
  24103. }
  24104. else {
  24105. condition._evaluationId = currentRenderId;
  24106. if (!condition.isValid()) {
  24107. condition._currentResult = false;
  24108. return;
  24109. }
  24110. condition._currentResult = true;
  24111. }
  24112. }
  24113. this._nextActiveAction.execute(evt);
  24114. if (this._nextActiveAction._child) {
  24115. if (!this._nextActiveAction._child._actionManager) {
  24116. this._nextActiveAction._child._actionManager = this._actionManager;
  24117. }
  24118. this._nextActiveAction = this._nextActiveAction._child;
  24119. }
  24120. else {
  24121. this._nextActiveAction = this;
  24122. }
  24123. };
  24124. Action.prototype.execute = function (evt) {
  24125. };
  24126. Action.prototype.then = function (action) {
  24127. this._child = action;
  24128. action._actionManager = this._actionManager;
  24129. action._prepare();
  24130. return action;
  24131. };
  24132. Action.prototype._getProperty = function (propertyPath) {
  24133. return this._actionManager._getProperty(propertyPath);
  24134. };
  24135. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24136. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24137. };
  24138. return Action;
  24139. })();
  24140. BABYLON.Action = Action;
  24141. })(BABYLON || (BABYLON = {}));
  24142. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24143. (function (BABYLON) {
  24144. /**
  24145. * ActionEvent is the event beint sent when an action is triggered.
  24146. */
  24147. var ActionEvent = (function () {
  24148. /**
  24149. * @constructor
  24150. * @param source The mesh that triggered the action.
  24151. * @param pointerX the X mouse cursor position at the time of the event
  24152. * @param pointerY the Y mouse cursor position at the time of the event
  24153. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24154. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24155. */
  24156. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24157. this.source = source;
  24158. this.pointerX = pointerX;
  24159. this.pointerY = pointerY;
  24160. this.meshUnderPointer = meshUnderPointer;
  24161. this.sourceEvent = sourceEvent;
  24162. }
  24163. /**
  24164. * Helper function to auto-create an ActionEvent from a source mesh.
  24165. * @param source the source mesh that triggered the event
  24166. * @param evt {Event} The original (browser) event
  24167. */
  24168. ActionEvent.CreateNew = function (source, evt) {
  24169. var scene = source.getScene();
  24170. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24171. };
  24172. /**
  24173. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24174. * @param scene the scene where the event occurred
  24175. * @param evt {Event} The original (browser) event
  24176. */
  24177. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24178. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24179. };
  24180. return ActionEvent;
  24181. })();
  24182. BABYLON.ActionEvent = ActionEvent;
  24183. /**
  24184. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24185. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24186. */
  24187. var ActionManager = (function () {
  24188. function ActionManager(scene) {
  24189. // Members
  24190. this.actions = new Array();
  24191. this._scene = scene;
  24192. scene._actionManagers.push(this);
  24193. }
  24194. Object.defineProperty(ActionManager, "NothingTrigger", {
  24195. get: function () {
  24196. return ActionManager._NothingTrigger;
  24197. },
  24198. enumerable: true,
  24199. configurable: true
  24200. });
  24201. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24202. get: function () {
  24203. return ActionManager._OnPickTrigger;
  24204. },
  24205. enumerable: true,
  24206. configurable: true
  24207. });
  24208. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24209. get: function () {
  24210. return ActionManager._OnLeftPickTrigger;
  24211. },
  24212. enumerable: true,
  24213. configurable: true
  24214. });
  24215. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24216. get: function () {
  24217. return ActionManager._OnRightPickTrigger;
  24218. },
  24219. enumerable: true,
  24220. configurable: true
  24221. });
  24222. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24223. get: function () {
  24224. return ActionManager._OnCenterPickTrigger;
  24225. },
  24226. enumerable: true,
  24227. configurable: true
  24228. });
  24229. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24230. get: function () {
  24231. return ActionManager._OnPointerOverTrigger;
  24232. },
  24233. enumerable: true,
  24234. configurable: true
  24235. });
  24236. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24237. get: function () {
  24238. return ActionManager._OnPointerOutTrigger;
  24239. },
  24240. enumerable: true,
  24241. configurable: true
  24242. });
  24243. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24244. get: function () {
  24245. return ActionManager._OnEveryFrameTrigger;
  24246. },
  24247. enumerable: true,
  24248. configurable: true
  24249. });
  24250. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24251. get: function () {
  24252. return ActionManager._OnIntersectionEnterTrigger;
  24253. },
  24254. enumerable: true,
  24255. configurable: true
  24256. });
  24257. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24258. get: function () {
  24259. return ActionManager._OnIntersectionExitTrigger;
  24260. },
  24261. enumerable: true,
  24262. configurable: true
  24263. });
  24264. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24265. get: function () {
  24266. return ActionManager._OnKeyDownTrigger;
  24267. },
  24268. enumerable: true,
  24269. configurable: true
  24270. });
  24271. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24272. get: function () {
  24273. return ActionManager._OnKeyUpTrigger;
  24274. },
  24275. enumerable: true,
  24276. configurable: true
  24277. });
  24278. // Methods
  24279. ActionManager.prototype.dispose = function () {
  24280. var index = this._scene._actionManagers.indexOf(this);
  24281. if (index > -1) {
  24282. this._scene._actionManagers.splice(index, 1);
  24283. }
  24284. };
  24285. ActionManager.prototype.getScene = function () {
  24286. return this._scene;
  24287. };
  24288. /**
  24289. * Does this action manager handles actions of any of the given triggers
  24290. * @param {number[]} triggers - the triggers to be tested
  24291. * @return {boolean} whether one (or more) of the triggers is handeled
  24292. */
  24293. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24294. for (var index = 0; index < this.actions.length; index++) {
  24295. var action = this.actions[index];
  24296. if (triggers.indexOf(action.trigger) > -1) {
  24297. return true;
  24298. }
  24299. }
  24300. return false;
  24301. };
  24302. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24303. /**
  24304. * Does this action manager has pointer triggers
  24305. * @return {boolean} whether or not it has pointer triggers
  24306. */
  24307. get: function () {
  24308. for (var index = 0; index < this.actions.length; index++) {
  24309. var action = this.actions[index];
  24310. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24311. return true;
  24312. }
  24313. }
  24314. return false;
  24315. },
  24316. enumerable: true,
  24317. configurable: true
  24318. });
  24319. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24320. /**
  24321. * Does this action manager has pick triggers
  24322. * @return {boolean} whether or not it has pick triggers
  24323. */
  24324. get: function () {
  24325. for (var index = 0; index < this.actions.length; index++) {
  24326. var action = this.actions[index];
  24327. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24328. return true;
  24329. }
  24330. }
  24331. return false;
  24332. },
  24333. enumerable: true,
  24334. configurable: true
  24335. });
  24336. /**
  24337. * Registers an action to this action manager
  24338. * @param {BABYLON.Action} action - the action to be registered
  24339. * @return {BABYLON.Action} the action amended (prepared) after registration
  24340. */
  24341. ActionManager.prototype.registerAction = function (action) {
  24342. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24343. if (this.getScene().actionManager !== this) {
  24344. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24345. return null;
  24346. }
  24347. }
  24348. this.actions.push(action);
  24349. action._actionManager = this;
  24350. action._prepare();
  24351. return action;
  24352. };
  24353. /**
  24354. * Process a specific trigger
  24355. * @param {number} trigger - the trigger to process
  24356. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24357. */
  24358. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24359. for (var index = 0; index < this.actions.length; index++) {
  24360. var action = this.actions[index];
  24361. if (action.trigger === trigger) {
  24362. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24363. var parameter = action.getTriggerParameter();
  24364. if (parameter) {
  24365. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24366. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24367. if (actualkey !== parameter.toLowerCase()) {
  24368. continue;
  24369. }
  24370. }
  24371. }
  24372. action._executeCurrent(evt);
  24373. }
  24374. }
  24375. };
  24376. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24377. var properties = propertyPath.split(".");
  24378. for (var index = 0; index < properties.length - 1; index++) {
  24379. target = target[properties[index]];
  24380. }
  24381. return target;
  24382. };
  24383. ActionManager.prototype._getProperty = function (propertyPath) {
  24384. var properties = propertyPath.split(".");
  24385. return properties[properties.length - 1];
  24386. };
  24387. // Statics
  24388. ActionManager._NothingTrigger = 0;
  24389. ActionManager._OnPickTrigger = 1;
  24390. ActionManager._OnLeftPickTrigger = 2;
  24391. ActionManager._OnRightPickTrigger = 3;
  24392. ActionManager._OnCenterPickTrigger = 4;
  24393. ActionManager._OnPointerOverTrigger = 5;
  24394. ActionManager._OnPointerOutTrigger = 6;
  24395. ActionManager._OnEveryFrameTrigger = 7;
  24396. ActionManager._OnIntersectionEnterTrigger = 8;
  24397. ActionManager._OnIntersectionExitTrigger = 9;
  24398. ActionManager._OnKeyDownTrigger = 10;
  24399. ActionManager._OnKeyUpTrigger = 11;
  24400. return ActionManager;
  24401. })();
  24402. BABYLON.ActionManager = ActionManager;
  24403. })(BABYLON || (BABYLON = {}));
  24404. //# sourceMappingURL=babylon.actionManager.js.map
  24405. var BABYLON;
  24406. (function (BABYLON) {
  24407. var InterpolateValueAction = (function (_super) {
  24408. __extends(InterpolateValueAction, _super);
  24409. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24410. if (duration === void 0) { duration = 1000; }
  24411. _super.call(this, triggerOptions, condition);
  24412. this.propertyPath = propertyPath;
  24413. this.value = value;
  24414. this.duration = duration;
  24415. this.stopOtherAnimations = stopOtherAnimations;
  24416. this._target = target;
  24417. }
  24418. InterpolateValueAction.prototype._prepare = function () {
  24419. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24420. this._property = this._getProperty(this.propertyPath);
  24421. };
  24422. InterpolateValueAction.prototype.execute = function () {
  24423. var scene = this._actionManager.getScene();
  24424. var keys = [
  24425. {
  24426. frame: 0,
  24427. value: this._target[this._property]
  24428. },
  24429. {
  24430. frame: 100,
  24431. value: this.value
  24432. }
  24433. ];
  24434. var dataType;
  24435. if (typeof this.value === "number") {
  24436. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24437. }
  24438. else if (this.value instanceof BABYLON.Color3) {
  24439. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24440. }
  24441. else if (this.value instanceof BABYLON.Vector3) {
  24442. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24443. }
  24444. else if (this.value instanceof BABYLON.Matrix) {
  24445. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24446. }
  24447. else if (this.value instanceof BABYLON.Quaternion) {
  24448. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24449. }
  24450. else {
  24451. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24452. return;
  24453. }
  24454. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24455. animation.setKeys(keys);
  24456. if (this.stopOtherAnimations) {
  24457. scene.stopAnimation(this._target);
  24458. }
  24459. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24460. };
  24461. return InterpolateValueAction;
  24462. })(BABYLON.Action);
  24463. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24464. })(BABYLON || (BABYLON = {}));
  24465. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24466. var BABYLON;
  24467. (function (BABYLON) {
  24468. var SwitchBooleanAction = (function (_super) {
  24469. __extends(SwitchBooleanAction, _super);
  24470. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24471. _super.call(this, triggerOptions, condition);
  24472. this.propertyPath = propertyPath;
  24473. this._target = target;
  24474. }
  24475. SwitchBooleanAction.prototype._prepare = function () {
  24476. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24477. this._property = this._getProperty(this.propertyPath);
  24478. };
  24479. SwitchBooleanAction.prototype.execute = function () {
  24480. this._target[this._property] = !this._target[this._property];
  24481. };
  24482. return SwitchBooleanAction;
  24483. })(BABYLON.Action);
  24484. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24485. var SetStateAction = (function (_super) {
  24486. __extends(SetStateAction, _super);
  24487. function SetStateAction(triggerOptions, target, value, condition) {
  24488. _super.call(this, triggerOptions, condition);
  24489. this.value = value;
  24490. this._target = target;
  24491. }
  24492. SetStateAction.prototype.execute = function () {
  24493. this._target.state = this.value;
  24494. };
  24495. return SetStateAction;
  24496. })(BABYLON.Action);
  24497. BABYLON.SetStateAction = SetStateAction;
  24498. var SetValueAction = (function (_super) {
  24499. __extends(SetValueAction, _super);
  24500. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24501. _super.call(this, triggerOptions, condition);
  24502. this.propertyPath = propertyPath;
  24503. this.value = value;
  24504. this._target = target;
  24505. }
  24506. SetValueAction.prototype._prepare = function () {
  24507. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24508. this._property = this._getProperty(this.propertyPath);
  24509. };
  24510. SetValueAction.prototype.execute = function () {
  24511. this._target[this._property] = this.value;
  24512. };
  24513. return SetValueAction;
  24514. })(BABYLON.Action);
  24515. BABYLON.SetValueAction = SetValueAction;
  24516. var IncrementValueAction = (function (_super) {
  24517. __extends(IncrementValueAction, _super);
  24518. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24519. _super.call(this, triggerOptions, condition);
  24520. this.propertyPath = propertyPath;
  24521. this.value = value;
  24522. this._target = target;
  24523. }
  24524. IncrementValueAction.prototype._prepare = function () {
  24525. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24526. this._property = this._getProperty(this.propertyPath);
  24527. if (typeof this._target[this._property] !== "number") {
  24528. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24529. }
  24530. };
  24531. IncrementValueAction.prototype.execute = function () {
  24532. this._target[this._property] += this.value;
  24533. };
  24534. return IncrementValueAction;
  24535. })(BABYLON.Action);
  24536. BABYLON.IncrementValueAction = IncrementValueAction;
  24537. var PlayAnimationAction = (function (_super) {
  24538. __extends(PlayAnimationAction, _super);
  24539. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24540. _super.call(this, triggerOptions, condition);
  24541. this.from = from;
  24542. this.to = to;
  24543. this.loop = loop;
  24544. this._target = target;
  24545. }
  24546. PlayAnimationAction.prototype._prepare = function () {
  24547. };
  24548. PlayAnimationAction.prototype.execute = function () {
  24549. var scene = this._actionManager.getScene();
  24550. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24551. };
  24552. return PlayAnimationAction;
  24553. })(BABYLON.Action);
  24554. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24555. var StopAnimationAction = (function (_super) {
  24556. __extends(StopAnimationAction, _super);
  24557. function StopAnimationAction(triggerOptions, target, condition) {
  24558. _super.call(this, triggerOptions, condition);
  24559. this._target = target;
  24560. }
  24561. StopAnimationAction.prototype._prepare = function () {
  24562. };
  24563. StopAnimationAction.prototype.execute = function () {
  24564. var scene = this._actionManager.getScene();
  24565. scene.stopAnimation(this._target);
  24566. };
  24567. return StopAnimationAction;
  24568. })(BABYLON.Action);
  24569. BABYLON.StopAnimationAction = StopAnimationAction;
  24570. var DoNothingAction = (function (_super) {
  24571. __extends(DoNothingAction, _super);
  24572. function DoNothingAction(triggerOptions, condition) {
  24573. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24574. _super.call(this, triggerOptions, condition);
  24575. }
  24576. DoNothingAction.prototype.execute = function () {
  24577. };
  24578. return DoNothingAction;
  24579. })(BABYLON.Action);
  24580. BABYLON.DoNothingAction = DoNothingAction;
  24581. var CombineAction = (function (_super) {
  24582. __extends(CombineAction, _super);
  24583. function CombineAction(triggerOptions, children, condition) {
  24584. _super.call(this, triggerOptions, condition);
  24585. this.children = children;
  24586. }
  24587. CombineAction.prototype._prepare = function () {
  24588. for (var index = 0; index < this.children.length; index++) {
  24589. this.children[index]._actionManager = this._actionManager;
  24590. this.children[index]._prepare();
  24591. }
  24592. };
  24593. CombineAction.prototype.execute = function (evt) {
  24594. for (var index = 0; index < this.children.length; index++) {
  24595. this.children[index].execute(evt);
  24596. }
  24597. };
  24598. return CombineAction;
  24599. })(BABYLON.Action);
  24600. BABYLON.CombineAction = CombineAction;
  24601. var ExecuteCodeAction = (function (_super) {
  24602. __extends(ExecuteCodeAction, _super);
  24603. function ExecuteCodeAction(triggerOptions, func, condition) {
  24604. _super.call(this, triggerOptions, condition);
  24605. this.func = func;
  24606. }
  24607. ExecuteCodeAction.prototype.execute = function (evt) {
  24608. this.func(evt);
  24609. };
  24610. return ExecuteCodeAction;
  24611. })(BABYLON.Action);
  24612. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24613. var SetParentAction = (function (_super) {
  24614. __extends(SetParentAction, _super);
  24615. function SetParentAction(triggerOptions, target, parent, condition) {
  24616. _super.call(this, triggerOptions, condition);
  24617. this._target = target;
  24618. this._parent = parent;
  24619. }
  24620. SetParentAction.prototype._prepare = function () {
  24621. };
  24622. SetParentAction.prototype.execute = function () {
  24623. if (this._target.parent === this._parent) {
  24624. return;
  24625. }
  24626. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24627. invertParentWorldMatrix.invert();
  24628. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24629. this._target.parent = this._parent;
  24630. };
  24631. return SetParentAction;
  24632. })(BABYLON.Action);
  24633. BABYLON.SetParentAction = SetParentAction;
  24634. var PlaySoundAction = (function (_super) {
  24635. __extends(PlaySoundAction, _super);
  24636. function PlaySoundAction(triggerOptions, sound, condition) {
  24637. _super.call(this, triggerOptions, condition);
  24638. this._sound = sound;
  24639. }
  24640. PlaySoundAction.prototype._prepare = function () {
  24641. };
  24642. PlaySoundAction.prototype.execute = function () {
  24643. if (this._sound !== undefined)
  24644. this._sound.play();
  24645. };
  24646. return PlaySoundAction;
  24647. })(BABYLON.Action);
  24648. BABYLON.PlaySoundAction = PlaySoundAction;
  24649. var StopSoundAction = (function (_super) {
  24650. __extends(StopSoundAction, _super);
  24651. function StopSoundAction(triggerOptions, sound, condition) {
  24652. _super.call(this, triggerOptions, condition);
  24653. this._sound = sound;
  24654. }
  24655. StopSoundAction.prototype._prepare = function () {
  24656. };
  24657. StopSoundAction.prototype.execute = function () {
  24658. if (this._sound !== undefined)
  24659. this._sound.stop();
  24660. };
  24661. return StopSoundAction;
  24662. })(BABYLON.Action);
  24663. BABYLON.StopSoundAction = StopSoundAction;
  24664. })(BABYLON || (BABYLON = {}));
  24665. //# sourceMappingURL=babylon.directActions.js.map
  24666. var BABYLON;
  24667. (function (BABYLON) {
  24668. var Geometry = (function () {
  24669. function Geometry(id, scene, vertexData, updatable, mesh) {
  24670. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24671. this._totalVertices = 0;
  24672. this._indices = [];
  24673. this.id = id;
  24674. this._engine = scene.getEngine();
  24675. this._meshes = [];
  24676. this._scene = scene;
  24677. // vertexData
  24678. if (vertexData) {
  24679. this.setAllVerticesData(vertexData, updatable);
  24680. }
  24681. else {
  24682. this._totalVertices = 0;
  24683. this._indices = [];
  24684. }
  24685. // applyToMesh
  24686. if (mesh) {
  24687. this.applyToMesh(mesh);
  24688. mesh.computeWorldMatrix(true);
  24689. }
  24690. }
  24691. Geometry.prototype.getScene = function () {
  24692. return this._scene;
  24693. };
  24694. Geometry.prototype.getEngine = function () {
  24695. return this._engine;
  24696. };
  24697. Geometry.prototype.isReady = function () {
  24698. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24699. };
  24700. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24701. vertexData.applyToGeometry(this, updatable);
  24702. };
  24703. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24704. this._vertexBuffers = this._vertexBuffers || {};
  24705. if (this._vertexBuffers[kind]) {
  24706. this._vertexBuffers[kind].dispose();
  24707. }
  24708. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24709. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24710. stride = this._vertexBuffers[kind].getStrideSize();
  24711. this._totalVertices = data.length / stride;
  24712. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24713. var meshes = this._meshes;
  24714. var numOfMeshes = meshes.length;
  24715. for (var index = 0; index < numOfMeshes; index++) {
  24716. var mesh = meshes[index];
  24717. mesh._resetPointsArrayCache();
  24718. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24719. mesh._createGlobalSubMesh();
  24720. mesh.computeWorldMatrix(true);
  24721. }
  24722. }
  24723. };
  24724. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24725. var vertexBuffer = this.getVertexBuffer(kind);
  24726. if (!vertexBuffer) {
  24727. return;
  24728. }
  24729. vertexBuffer.updateDirectly(data, offset);
  24730. };
  24731. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24732. var vertexBuffer = this.getVertexBuffer(kind);
  24733. if (!vertexBuffer) {
  24734. return;
  24735. }
  24736. vertexBuffer.update(data);
  24737. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24738. var extend;
  24739. var stride = vertexBuffer.getStrideSize();
  24740. this._totalVertices = data.length / stride;
  24741. if (updateExtends) {
  24742. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24743. }
  24744. var meshes = this._meshes;
  24745. var numOfMeshes = meshes.length;
  24746. for (var index = 0; index < numOfMeshes; index++) {
  24747. var mesh = meshes[index];
  24748. mesh._resetPointsArrayCache();
  24749. if (updateExtends) {
  24750. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24751. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24752. var subMesh = mesh.subMeshes[subIndex];
  24753. subMesh.refreshBoundingInfo();
  24754. }
  24755. }
  24756. }
  24757. }
  24758. };
  24759. Geometry.prototype.getTotalVertices = function () {
  24760. if (!this.isReady()) {
  24761. return 0;
  24762. }
  24763. return this._totalVertices;
  24764. };
  24765. Geometry.prototype.getVerticesData = function (kind) {
  24766. var vertexBuffer = this.getVertexBuffer(kind);
  24767. if (!vertexBuffer) {
  24768. return null;
  24769. }
  24770. return vertexBuffer.getData();
  24771. };
  24772. Geometry.prototype.getVertexBuffer = function (kind) {
  24773. if (!this.isReady()) {
  24774. return null;
  24775. }
  24776. return this._vertexBuffers[kind];
  24777. };
  24778. Geometry.prototype.getVertexBuffers = function () {
  24779. if (!this.isReady()) {
  24780. return null;
  24781. }
  24782. return this._vertexBuffers;
  24783. };
  24784. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24785. if (!this._vertexBuffers) {
  24786. if (this._delayInfo) {
  24787. return this._delayInfo.indexOf(kind) !== -1;
  24788. }
  24789. return false;
  24790. }
  24791. return this._vertexBuffers[kind] !== undefined;
  24792. };
  24793. Geometry.prototype.getVerticesDataKinds = function () {
  24794. var result = [];
  24795. if (!this._vertexBuffers && this._delayInfo) {
  24796. for (var kind in this._delayInfo) {
  24797. result.push(kind);
  24798. }
  24799. }
  24800. else {
  24801. for (kind in this._vertexBuffers) {
  24802. result.push(kind);
  24803. }
  24804. }
  24805. return result;
  24806. };
  24807. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24808. if (this._indexBuffer) {
  24809. this._engine._releaseBuffer(this._indexBuffer);
  24810. }
  24811. this._indices = indices;
  24812. if (this._meshes.length !== 0 && this._indices) {
  24813. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24814. }
  24815. if (totalVertices !== undefined) {
  24816. this._totalVertices = totalVertices;
  24817. }
  24818. var meshes = this._meshes;
  24819. var numOfMeshes = meshes.length;
  24820. for (var index = 0; index < numOfMeshes; index++) {
  24821. meshes[index]._createGlobalSubMesh();
  24822. }
  24823. };
  24824. Geometry.prototype.getTotalIndices = function () {
  24825. if (!this.isReady()) {
  24826. return 0;
  24827. }
  24828. return this._indices.length;
  24829. };
  24830. Geometry.prototype.getIndices = function () {
  24831. if (!this.isReady()) {
  24832. return null;
  24833. }
  24834. return this._indices;
  24835. };
  24836. Geometry.prototype.getIndexBuffer = function () {
  24837. if (!this.isReady()) {
  24838. return null;
  24839. }
  24840. return this._indexBuffer;
  24841. };
  24842. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24843. var meshes = this._meshes;
  24844. var index = meshes.indexOf(mesh);
  24845. if (index === -1) {
  24846. return;
  24847. }
  24848. for (var kind in this._vertexBuffers) {
  24849. this._vertexBuffers[kind].dispose();
  24850. }
  24851. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24852. this._indexBuffer = null;
  24853. }
  24854. meshes.splice(index, 1);
  24855. mesh._geometry = null;
  24856. if (meshes.length === 0 && shouldDispose) {
  24857. this.dispose();
  24858. }
  24859. };
  24860. Geometry.prototype.applyToMesh = function (mesh) {
  24861. if (mesh._geometry === this) {
  24862. return;
  24863. }
  24864. var previousGeometry = mesh._geometry;
  24865. if (previousGeometry) {
  24866. previousGeometry.releaseForMesh(mesh);
  24867. }
  24868. var meshes = this._meshes;
  24869. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24870. mesh._geometry = this;
  24871. this._scene.pushGeometry(this);
  24872. meshes.push(mesh);
  24873. if (this.isReady()) {
  24874. this._applyToMesh(mesh);
  24875. }
  24876. else {
  24877. mesh._boundingInfo = this._boundingInfo;
  24878. }
  24879. };
  24880. Geometry.prototype._applyToMesh = function (mesh) {
  24881. var numOfMeshes = this._meshes.length;
  24882. for (var kind in this._vertexBuffers) {
  24883. if (numOfMeshes === 1) {
  24884. this._vertexBuffers[kind].create();
  24885. }
  24886. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24887. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24888. mesh._resetPointsArrayCache();
  24889. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24890. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24891. mesh._createGlobalSubMesh();
  24892. //bounding info was just created again, world matrix should be applied again.
  24893. mesh._updateBoundingInfo();
  24894. }
  24895. }
  24896. // indexBuffer
  24897. if (numOfMeshes === 1 && this._indices) {
  24898. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24899. }
  24900. if (this._indexBuffer) {
  24901. this._indexBuffer.references = numOfMeshes;
  24902. }
  24903. };
  24904. Geometry.prototype.load = function (scene, onLoaded) {
  24905. var _this = this;
  24906. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24907. return;
  24908. }
  24909. if (this.isReady()) {
  24910. if (onLoaded) {
  24911. onLoaded();
  24912. }
  24913. return;
  24914. }
  24915. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24916. scene._addPendingData(this);
  24917. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24918. _this._delayLoadingFunction(JSON.parse(data), _this);
  24919. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24920. _this._delayInfo = [];
  24921. scene._removePendingData(_this);
  24922. var meshes = _this._meshes;
  24923. var numOfMeshes = meshes.length;
  24924. for (var index = 0; index < numOfMeshes; index++) {
  24925. _this._applyToMesh(meshes[index]);
  24926. }
  24927. if (onLoaded) {
  24928. onLoaded();
  24929. }
  24930. }, function () {
  24931. }, scene.database);
  24932. };
  24933. Geometry.prototype.dispose = function () {
  24934. var meshes = this._meshes;
  24935. var numOfMeshes = meshes.length;
  24936. var index;
  24937. for (index = 0; index < numOfMeshes; index++) {
  24938. this.releaseForMesh(meshes[index]);
  24939. }
  24940. this._meshes = [];
  24941. for (var kind in this._vertexBuffers) {
  24942. this._vertexBuffers[kind].dispose();
  24943. }
  24944. this._vertexBuffers = [];
  24945. this._totalVertices = 0;
  24946. if (this._indexBuffer) {
  24947. this._engine._releaseBuffer(this._indexBuffer);
  24948. }
  24949. this._indexBuffer = null;
  24950. this._indices = [];
  24951. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24952. this.delayLoadingFile = null;
  24953. this._delayLoadingFunction = null;
  24954. this._delayInfo = [];
  24955. this._boundingInfo = null; // todo: .dispose()
  24956. var geometries = this._scene.getGeometries();
  24957. index = geometries.indexOf(this);
  24958. if (index > -1) {
  24959. geometries.splice(index, 1);
  24960. }
  24961. };
  24962. Geometry.prototype.copy = function (id) {
  24963. var vertexData = new BABYLON.VertexData();
  24964. vertexData.indices = [];
  24965. var indices = this.getIndices();
  24966. for (var index = 0; index < indices.length; index++) {
  24967. vertexData.indices.push(indices[index]);
  24968. }
  24969. var updatable = false;
  24970. var stopChecking = false;
  24971. for (var kind in this._vertexBuffers) {
  24972. // using slice() to make a copy of the array and not just reference it
  24973. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  24974. if (!stopChecking) {
  24975. updatable = this.getVertexBuffer(kind).isUpdatable();
  24976. stopChecking = !updatable;
  24977. }
  24978. }
  24979. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24980. geometry.delayLoadState = this.delayLoadState;
  24981. geometry.delayLoadingFile = this.delayLoadingFile;
  24982. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24983. for (kind in this._delayInfo) {
  24984. geometry._delayInfo = geometry._delayInfo || [];
  24985. geometry._delayInfo.push(kind);
  24986. }
  24987. // Bounding info
  24988. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24989. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24990. return geometry;
  24991. };
  24992. // Statics
  24993. Geometry.ExtractFromMesh = function (mesh, id) {
  24994. var geometry = mesh._geometry;
  24995. if (!geometry) {
  24996. return null;
  24997. }
  24998. return geometry.copy(id);
  24999. };
  25000. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25001. // be aware Math.random() could cause collisions
  25002. Geometry.RandomId = function () {
  25003. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25004. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25005. return v.toString(16);
  25006. });
  25007. };
  25008. return Geometry;
  25009. })();
  25010. BABYLON.Geometry = Geometry;
  25011. /////// Primitives //////////////////////////////////////////////
  25012. var Geometry;
  25013. (function (Geometry) {
  25014. var Primitives;
  25015. (function (Primitives) {
  25016. /// Abstract class
  25017. var _Primitive = (function (_super) {
  25018. __extends(_Primitive, _super);
  25019. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25020. this._beingRegenerated = true;
  25021. this._canBeRegenerated = canBeRegenerated;
  25022. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25023. this._beingRegenerated = false;
  25024. }
  25025. _Primitive.prototype.canBeRegenerated = function () {
  25026. return this._canBeRegenerated;
  25027. };
  25028. _Primitive.prototype.regenerate = function () {
  25029. if (!this._canBeRegenerated) {
  25030. return;
  25031. }
  25032. this._beingRegenerated = true;
  25033. this.setAllVerticesData(this._regenerateVertexData(), false);
  25034. this._beingRegenerated = false;
  25035. };
  25036. _Primitive.prototype.asNewGeometry = function (id) {
  25037. return _super.prototype.copy.call(this, id);
  25038. };
  25039. // overrides
  25040. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25041. if (!this._beingRegenerated) {
  25042. return;
  25043. }
  25044. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25045. };
  25046. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25047. if (!this._beingRegenerated) {
  25048. return;
  25049. }
  25050. _super.prototype.setVerticesData.call(this, kind, data, false);
  25051. };
  25052. // to override
  25053. // protected
  25054. _Primitive.prototype._regenerateVertexData = function () {
  25055. throw new Error("Abstract method");
  25056. };
  25057. _Primitive.prototype.copy = function (id) {
  25058. throw new Error("Must be overriden in sub-classes.");
  25059. };
  25060. return _Primitive;
  25061. })(Geometry);
  25062. Primitives._Primitive = _Primitive;
  25063. var Ribbon = (function (_super) {
  25064. __extends(Ribbon, _super);
  25065. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25066. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25067. this.pathArray = pathArray;
  25068. this.closeArray = closeArray;
  25069. this.closePath = closePath;
  25070. this.offset = offset;
  25071. this.side = side;
  25072. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25073. }
  25074. Ribbon.prototype._regenerateVertexData = function () {
  25075. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25076. };
  25077. Ribbon.prototype.copy = function (id) {
  25078. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25079. };
  25080. return Ribbon;
  25081. })(_Primitive);
  25082. Primitives.Ribbon = Ribbon;
  25083. var Box = (function (_super) {
  25084. __extends(Box, _super);
  25085. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25086. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25087. this.size = size;
  25088. this.side = side;
  25089. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25090. }
  25091. Box.prototype._regenerateVertexData = function () {
  25092. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25093. };
  25094. Box.prototype.copy = function (id) {
  25095. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25096. };
  25097. return Box;
  25098. })(_Primitive);
  25099. Primitives.Box = Box;
  25100. var Sphere = (function (_super) {
  25101. __extends(Sphere, _super);
  25102. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25103. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25104. this.segments = segments;
  25105. this.diameter = diameter;
  25106. this.side = side;
  25107. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25108. }
  25109. Sphere.prototype._regenerateVertexData = function () {
  25110. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25111. };
  25112. Sphere.prototype.copy = function (id) {
  25113. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25114. };
  25115. return Sphere;
  25116. })(_Primitive);
  25117. Primitives.Sphere = Sphere;
  25118. var Cylinder = (function (_super) {
  25119. __extends(Cylinder, _super);
  25120. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25121. if (subdivisions === void 0) { subdivisions = 1; }
  25122. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25123. this.height = height;
  25124. this.diameterTop = diameterTop;
  25125. this.diameterBottom = diameterBottom;
  25126. this.tessellation = tessellation;
  25127. this.subdivisions = subdivisions;
  25128. this.side = side;
  25129. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25130. }
  25131. Cylinder.prototype._regenerateVertexData = function () {
  25132. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25133. };
  25134. Cylinder.prototype.copy = function (id) {
  25135. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25136. };
  25137. return Cylinder;
  25138. })(_Primitive);
  25139. Primitives.Cylinder = Cylinder;
  25140. var Torus = (function (_super) {
  25141. __extends(Torus, _super);
  25142. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25143. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25144. this.diameter = diameter;
  25145. this.thickness = thickness;
  25146. this.tessellation = tessellation;
  25147. this.side = side;
  25148. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25149. }
  25150. Torus.prototype._regenerateVertexData = function () {
  25151. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25152. };
  25153. Torus.prototype.copy = function (id) {
  25154. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25155. };
  25156. return Torus;
  25157. })(_Primitive);
  25158. Primitives.Torus = Torus;
  25159. var Ground = (function (_super) {
  25160. __extends(Ground, _super);
  25161. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25162. this.width = width;
  25163. this.height = height;
  25164. this.subdivisions = subdivisions;
  25165. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25166. }
  25167. Ground.prototype._regenerateVertexData = function () {
  25168. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25169. };
  25170. Ground.prototype.copy = function (id) {
  25171. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25172. };
  25173. return Ground;
  25174. })(_Primitive);
  25175. Primitives.Ground = Ground;
  25176. var TiledGround = (function (_super) {
  25177. __extends(TiledGround, _super);
  25178. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25179. this.xmin = xmin;
  25180. this.zmin = zmin;
  25181. this.xmax = xmax;
  25182. this.zmax = zmax;
  25183. this.subdivisions = subdivisions;
  25184. this.precision = precision;
  25185. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25186. }
  25187. TiledGround.prototype._regenerateVertexData = function () {
  25188. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25189. };
  25190. TiledGround.prototype.copy = function (id) {
  25191. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25192. };
  25193. return TiledGround;
  25194. })(_Primitive);
  25195. Primitives.TiledGround = TiledGround;
  25196. var Plane = (function (_super) {
  25197. __extends(Plane, _super);
  25198. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25199. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25200. this.size = size;
  25201. this.side = side;
  25202. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25203. }
  25204. Plane.prototype._regenerateVertexData = function () {
  25205. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25206. };
  25207. Plane.prototype.copy = function (id) {
  25208. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25209. };
  25210. return Plane;
  25211. })(_Primitive);
  25212. Primitives.Plane = Plane;
  25213. var TorusKnot = (function (_super) {
  25214. __extends(TorusKnot, _super);
  25215. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25216. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25217. this.radius = radius;
  25218. this.tube = tube;
  25219. this.radialSegments = radialSegments;
  25220. this.tubularSegments = tubularSegments;
  25221. this.p = p;
  25222. this.q = q;
  25223. this.side = side;
  25224. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25225. }
  25226. TorusKnot.prototype._regenerateVertexData = function () {
  25227. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25228. };
  25229. TorusKnot.prototype.copy = function (id) {
  25230. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25231. };
  25232. return TorusKnot;
  25233. })(_Primitive);
  25234. Primitives.TorusKnot = TorusKnot;
  25235. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25236. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25237. })(BABYLON || (BABYLON = {}));
  25238. //# sourceMappingURL=babylon.geometry.js.map
  25239. var BABYLON;
  25240. (function (BABYLON) {
  25241. var Gamepads = (function () {
  25242. function Gamepads(ongamedpadconnected) {
  25243. var _this = this;
  25244. this.babylonGamepads = [];
  25245. this.oneGamepadConnected = false;
  25246. this.isMonitoring = false;
  25247. this.gamepadEventSupported = 'GamepadEvent' in window;
  25248. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25249. 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=";
  25250. this._callbackGamepadConnected = ongamedpadconnected;
  25251. if (this.gamepadSupportAvailable) {
  25252. // Checking if the gamepad connected event is supported (like in Firefox)
  25253. if (this.gamepadEventSupported) {
  25254. window.addEventListener('gamepadconnected', function (evt) {
  25255. _this._onGamepadConnected(evt);
  25256. }, false);
  25257. window.addEventListener('gamepaddisconnected', function (evt) {
  25258. _this._onGamepadDisconnected(evt);
  25259. }, false);
  25260. }
  25261. else {
  25262. this._startMonitoringGamepads();
  25263. }
  25264. if (!this.oneGamepadConnected) {
  25265. this._insertGamepadDOMInstructions();
  25266. }
  25267. }
  25268. else {
  25269. this._insertGamepadDOMNotSupported();
  25270. }
  25271. }
  25272. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25273. Gamepads.gamepadDOMInfo = document.createElement("div");
  25274. var buttonAImage = document.createElement("img");
  25275. buttonAImage.src = this.buttonADataURL;
  25276. var spanMessage = document.createElement("span");
  25277. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25278. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25279. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25280. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25281. Gamepads.gamepadDOMInfo.style.width = "100%";
  25282. Gamepads.gamepadDOMInfo.style.height = "48px";
  25283. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25284. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25285. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25286. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25287. buttonAImage.style.position = "relative";
  25288. buttonAImage.style.bottom = "8px";
  25289. spanMessage.style.position = "relative";
  25290. spanMessage.style.fontSize = "32px";
  25291. spanMessage.style.bottom = "32px";
  25292. spanMessage.style.color = "green";
  25293. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25294. };
  25295. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25296. Gamepads.gamepadDOMInfo = document.createElement("div");
  25297. var spanMessage = document.createElement("span");
  25298. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25299. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25300. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25301. Gamepads.gamepadDOMInfo.style.width = "100%";
  25302. Gamepads.gamepadDOMInfo.style.height = "40px";
  25303. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25304. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25305. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25306. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25307. spanMessage.style.position = "relative";
  25308. spanMessage.style.fontSize = "32px";
  25309. spanMessage.style.color = "red";
  25310. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25311. };
  25312. Gamepads.prototype.dispose = function () {
  25313. if (Gamepads.gamepadDOMInfo) {
  25314. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25315. }
  25316. };
  25317. Gamepads.prototype._onGamepadConnected = function (evt) {
  25318. var newGamepad = this._addNewGamepad(evt.gamepad);
  25319. if (this._callbackGamepadConnected)
  25320. this._callbackGamepadConnected(newGamepad);
  25321. this._startMonitoringGamepads();
  25322. };
  25323. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25324. if (!this.oneGamepadConnected) {
  25325. this.oneGamepadConnected = true;
  25326. if (Gamepads.gamepadDOMInfo) {
  25327. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25328. Gamepads.gamepadDOMInfo = null;
  25329. }
  25330. }
  25331. var newGamepad;
  25332. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25333. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25334. }
  25335. else {
  25336. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25337. }
  25338. this.babylonGamepads.push(newGamepad);
  25339. return newGamepad;
  25340. };
  25341. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25342. for (var i in this.babylonGamepads) {
  25343. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25344. this.babylonGamepads.splice(i, 1);
  25345. break;
  25346. }
  25347. }
  25348. // If no gamepads are left, stop the polling loop.
  25349. if (this.babylonGamepads.length == 0) {
  25350. this._stopMonitoringGamepads();
  25351. }
  25352. };
  25353. Gamepads.prototype._startMonitoringGamepads = function () {
  25354. if (!this.isMonitoring) {
  25355. this.isMonitoring = true;
  25356. this._checkGamepadsStatus();
  25357. }
  25358. };
  25359. Gamepads.prototype._stopMonitoringGamepads = function () {
  25360. this.isMonitoring = false;
  25361. };
  25362. Gamepads.prototype._checkGamepadsStatus = function () {
  25363. var _this = this;
  25364. // updating gamepad objects
  25365. this._updateGamepadObjects();
  25366. for (var i in this.babylonGamepads) {
  25367. this.babylonGamepads[i].update();
  25368. }
  25369. if (this.isMonitoring) {
  25370. if (window.requestAnimationFrame) {
  25371. window.requestAnimationFrame(function () {
  25372. _this._checkGamepadsStatus();
  25373. });
  25374. }
  25375. else if (window.mozRequestAnimationFrame) {
  25376. window.mozRequestAnimationFrame(function () {
  25377. _this._checkGamepadsStatus();
  25378. });
  25379. }
  25380. else if (window.webkitRequestAnimationFrame) {
  25381. window.webkitRequestAnimationFrame(function () {
  25382. _this._checkGamepadsStatus();
  25383. });
  25384. }
  25385. }
  25386. };
  25387. // This function is called only on Chrome, which does not yet support
  25388. // connection/disconnection events, but requires you to monitor
  25389. // an array for changes.
  25390. Gamepads.prototype._updateGamepadObjects = function () {
  25391. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25392. for (var i = 0; i < gamepads.length; i++) {
  25393. if (gamepads[i]) {
  25394. if (!(gamepads[i].index in this.babylonGamepads)) {
  25395. var newGamepad = this._addNewGamepad(gamepads[i]);
  25396. if (this._callbackGamepadConnected) {
  25397. this._callbackGamepadConnected(newGamepad);
  25398. }
  25399. }
  25400. else {
  25401. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25402. }
  25403. }
  25404. }
  25405. };
  25406. return Gamepads;
  25407. })();
  25408. BABYLON.Gamepads = Gamepads;
  25409. var StickValues = (function () {
  25410. function StickValues(x, y) {
  25411. this.x = x;
  25412. this.y = y;
  25413. }
  25414. return StickValues;
  25415. })();
  25416. BABYLON.StickValues = StickValues;
  25417. var Gamepad = (function () {
  25418. function Gamepad(id, index, browserGamepad) {
  25419. this.id = id;
  25420. this.index = index;
  25421. this.browserGamepad = browserGamepad;
  25422. if (this.browserGamepad.axes.length >= 2) {
  25423. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25424. }
  25425. if (this.browserGamepad.axes.length >= 4) {
  25426. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25427. }
  25428. }
  25429. Gamepad.prototype.onleftstickchanged = function (callback) {
  25430. this._onleftstickchanged = callback;
  25431. };
  25432. Gamepad.prototype.onrightstickchanged = function (callback) {
  25433. this._onrightstickchanged = callback;
  25434. };
  25435. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25436. get: function () {
  25437. return this._leftStick;
  25438. },
  25439. set: function (newValues) {
  25440. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25441. this._onleftstickchanged(newValues);
  25442. }
  25443. this._leftStick = newValues;
  25444. },
  25445. enumerable: true,
  25446. configurable: true
  25447. });
  25448. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25449. get: function () {
  25450. return this._rightStick;
  25451. },
  25452. set: function (newValues) {
  25453. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25454. this._onrightstickchanged(newValues);
  25455. }
  25456. this._rightStick = newValues;
  25457. },
  25458. enumerable: true,
  25459. configurable: true
  25460. });
  25461. Gamepad.prototype.update = function () {
  25462. if (this._leftStick) {
  25463. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25464. }
  25465. if (this._rightStick) {
  25466. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25467. }
  25468. };
  25469. return Gamepad;
  25470. })();
  25471. BABYLON.Gamepad = Gamepad;
  25472. var GenericPad = (function (_super) {
  25473. __extends(GenericPad, _super);
  25474. function GenericPad(id, index, gamepad) {
  25475. _super.call(this, id, index, gamepad);
  25476. this.id = id;
  25477. this.index = index;
  25478. this.gamepad = gamepad;
  25479. this._buttons = new Array(gamepad.buttons.length);
  25480. }
  25481. GenericPad.prototype.onbuttondown = function (callback) {
  25482. this._onbuttondown = callback;
  25483. };
  25484. GenericPad.prototype.onbuttonup = function (callback) {
  25485. this._onbuttonup = callback;
  25486. };
  25487. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25488. if (newValue !== currentValue) {
  25489. if (this._onbuttondown && newValue === 1) {
  25490. this._onbuttondown(buttonIndex);
  25491. }
  25492. if (this._onbuttonup && newValue === 0) {
  25493. this._onbuttonup(buttonIndex);
  25494. }
  25495. }
  25496. return newValue;
  25497. };
  25498. GenericPad.prototype.update = function () {
  25499. _super.prototype.update.call(this);
  25500. for (var index = 0; index < this._buttons.length; index++) {
  25501. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25502. }
  25503. };
  25504. return GenericPad;
  25505. })(Gamepad);
  25506. BABYLON.GenericPad = GenericPad;
  25507. (function (Xbox360Button) {
  25508. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25509. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25510. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25511. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25512. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25513. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25514. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25515. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25516. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25517. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25518. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25519. var Xbox360Button = BABYLON.Xbox360Button;
  25520. (function (Xbox360Dpad) {
  25521. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25522. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25523. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25524. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25525. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25526. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25527. var Xbox360Pad = (function (_super) {
  25528. __extends(Xbox360Pad, _super);
  25529. function Xbox360Pad() {
  25530. _super.apply(this, arguments);
  25531. this._leftTrigger = 0;
  25532. this._rightTrigger = 0;
  25533. this._buttonA = 0;
  25534. this._buttonB = 0;
  25535. this._buttonX = 0;
  25536. this._buttonY = 0;
  25537. this._buttonBack = 0;
  25538. this._buttonStart = 0;
  25539. this._buttonLB = 0;
  25540. this._buttonRB = 0;
  25541. this._buttonLeftStick = 0;
  25542. this._buttonRightStick = 0;
  25543. this._dPadUp = 0;
  25544. this._dPadDown = 0;
  25545. this._dPadLeft = 0;
  25546. this._dPadRight = 0;
  25547. }
  25548. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25549. this._onlefttriggerchanged = callback;
  25550. };
  25551. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25552. this._onrighttriggerchanged = callback;
  25553. };
  25554. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25555. get: function () {
  25556. return this._leftTrigger;
  25557. },
  25558. set: function (newValue) {
  25559. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25560. this._onlefttriggerchanged(newValue);
  25561. }
  25562. this._leftTrigger = newValue;
  25563. },
  25564. enumerable: true,
  25565. configurable: true
  25566. });
  25567. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25568. get: function () {
  25569. return this._rightTrigger;
  25570. },
  25571. set: function (newValue) {
  25572. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25573. this._onrighttriggerchanged(newValue);
  25574. }
  25575. this._rightTrigger = newValue;
  25576. },
  25577. enumerable: true,
  25578. configurable: true
  25579. });
  25580. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25581. this._onbuttondown = callback;
  25582. };
  25583. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25584. this._onbuttonup = callback;
  25585. };
  25586. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25587. this._ondpaddown = callback;
  25588. };
  25589. Xbox360Pad.prototype.ondpadup = function (callback) {
  25590. this._ondpadup = callback;
  25591. };
  25592. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25593. if (newValue !== currentValue) {
  25594. if (this._onbuttondown && newValue === 1) {
  25595. this._onbuttondown(buttonType);
  25596. }
  25597. if (this._onbuttonup && newValue === 0) {
  25598. this._onbuttonup(buttonType);
  25599. }
  25600. }
  25601. return newValue;
  25602. };
  25603. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25604. if (newValue !== currentValue) {
  25605. if (this._ondpaddown && newValue === 1) {
  25606. this._ondpaddown(buttonType);
  25607. }
  25608. if (this._ondpadup && newValue === 0) {
  25609. this._ondpadup(buttonType);
  25610. }
  25611. }
  25612. return newValue;
  25613. };
  25614. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25615. get: function () {
  25616. return this._buttonA;
  25617. },
  25618. set: function (value) {
  25619. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25620. },
  25621. enumerable: true,
  25622. configurable: true
  25623. });
  25624. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25625. get: function () {
  25626. return this._buttonB;
  25627. },
  25628. set: function (value) {
  25629. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25630. },
  25631. enumerable: true,
  25632. configurable: true
  25633. });
  25634. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25635. get: function () {
  25636. return this._buttonX;
  25637. },
  25638. set: function (value) {
  25639. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25640. },
  25641. enumerable: true,
  25642. configurable: true
  25643. });
  25644. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25645. get: function () {
  25646. return this._buttonY;
  25647. },
  25648. set: function (value) {
  25649. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25650. },
  25651. enumerable: true,
  25652. configurable: true
  25653. });
  25654. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25655. get: function () {
  25656. return this._buttonStart;
  25657. },
  25658. set: function (value) {
  25659. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25660. },
  25661. enumerable: true,
  25662. configurable: true
  25663. });
  25664. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25665. get: function () {
  25666. return this._buttonBack;
  25667. },
  25668. set: function (value) {
  25669. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25670. },
  25671. enumerable: true,
  25672. configurable: true
  25673. });
  25674. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25675. get: function () {
  25676. return this._buttonLB;
  25677. },
  25678. set: function (value) {
  25679. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25680. },
  25681. enumerable: true,
  25682. configurable: true
  25683. });
  25684. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25685. get: function () {
  25686. return this._buttonRB;
  25687. },
  25688. set: function (value) {
  25689. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25690. },
  25691. enumerable: true,
  25692. configurable: true
  25693. });
  25694. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25695. get: function () {
  25696. return this._buttonLeftStick;
  25697. },
  25698. set: function (value) {
  25699. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25700. },
  25701. enumerable: true,
  25702. configurable: true
  25703. });
  25704. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25705. get: function () {
  25706. return this._buttonRightStick;
  25707. },
  25708. set: function (value) {
  25709. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25710. },
  25711. enumerable: true,
  25712. configurable: true
  25713. });
  25714. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25715. get: function () {
  25716. return this._dPadUp;
  25717. },
  25718. set: function (value) {
  25719. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25720. },
  25721. enumerable: true,
  25722. configurable: true
  25723. });
  25724. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25725. get: function () {
  25726. return this._dPadDown;
  25727. },
  25728. set: function (value) {
  25729. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25730. },
  25731. enumerable: true,
  25732. configurable: true
  25733. });
  25734. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25735. get: function () {
  25736. return this._dPadLeft;
  25737. },
  25738. set: function (value) {
  25739. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25740. },
  25741. enumerable: true,
  25742. configurable: true
  25743. });
  25744. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25745. get: function () {
  25746. return this._dPadRight;
  25747. },
  25748. set: function (value) {
  25749. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25750. },
  25751. enumerable: true,
  25752. configurable: true
  25753. });
  25754. Xbox360Pad.prototype.update = function () {
  25755. _super.prototype.update.call(this);
  25756. this.buttonA = this.browserGamepad.buttons[0].value;
  25757. this.buttonB = this.browserGamepad.buttons[1].value;
  25758. this.buttonX = this.browserGamepad.buttons[2].value;
  25759. this.buttonY = this.browserGamepad.buttons[3].value;
  25760. this.buttonLB = this.browserGamepad.buttons[4].value;
  25761. this.buttonRB = this.browserGamepad.buttons[5].value;
  25762. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25763. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25764. this.buttonBack = this.browserGamepad.buttons[8].value;
  25765. this.buttonStart = this.browserGamepad.buttons[9].value;
  25766. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25767. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25768. this.dPadUp = this.browserGamepad.buttons[12].value;
  25769. this.dPadDown = this.browserGamepad.buttons[13].value;
  25770. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25771. this.dPadRight = this.browserGamepad.buttons[15].value;
  25772. };
  25773. return Xbox360Pad;
  25774. })(Gamepad);
  25775. BABYLON.Xbox360Pad = Xbox360Pad;
  25776. })(BABYLON || (BABYLON = {}));
  25777. //# sourceMappingURL=babylon.gamepads.js.map
  25778. var BABYLON;
  25779. (function (BABYLON) {
  25780. // We're mainly based on the logic defined into the FreeCamera code
  25781. var GamepadCamera = (function (_super) {
  25782. __extends(GamepadCamera, _super);
  25783. function GamepadCamera(name, position, scene) {
  25784. var _this = this;
  25785. _super.call(this, name, position, scene);
  25786. this.angularSensibility = 200;
  25787. this.moveSensibility = 75;
  25788. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25789. _this._onNewGameConnected(gamepad);
  25790. });
  25791. }
  25792. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25793. // Only the first gamepad can control the camera
  25794. if (gamepad.index === 0) {
  25795. this._gamepad = gamepad;
  25796. }
  25797. };
  25798. GamepadCamera.prototype._checkInputs = function () {
  25799. if (!this._gamepad) {
  25800. return;
  25801. }
  25802. var LSValues = this._gamepad.leftStick;
  25803. var normalizedLX = LSValues.x / this.moveSensibility;
  25804. var normalizedLY = LSValues.y / this.moveSensibility;
  25805. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25806. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25807. var RSValues = this._gamepad.rightStick;
  25808. var normalizedRX = RSValues.x / this.angularSensibility;
  25809. var normalizedRY = RSValues.y / this.angularSensibility;
  25810. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25811. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25812. ;
  25813. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25814. var speed = this._computeLocalCameraSpeed() * 50.0;
  25815. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25816. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25817. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25818. };
  25819. GamepadCamera.prototype.dispose = function () {
  25820. this._gamepads.dispose();
  25821. _super.prototype.dispose.call(this);
  25822. };
  25823. return GamepadCamera;
  25824. })(BABYLON.FreeCamera);
  25825. BABYLON.GamepadCamera = GamepadCamera;
  25826. })(BABYLON || (BABYLON = {}));
  25827. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25828. var BABYLON;
  25829. (function (BABYLON) {
  25830. var LinesMesh = (function (_super) {
  25831. __extends(LinesMesh, _super);
  25832. function LinesMesh(name, scene, updatable) {
  25833. if (updatable === void 0) { updatable = false; }
  25834. _super.call(this, name, scene);
  25835. this.color = new BABYLON.Color3(1, 1, 1);
  25836. this.alpha = 1;
  25837. this._indices = new Array();
  25838. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25839. attributes: ["position"],
  25840. uniforms: ["worldViewProjection", "color"],
  25841. needAlphaBlending: true
  25842. });
  25843. }
  25844. Object.defineProperty(LinesMesh.prototype, "material", {
  25845. get: function () {
  25846. return this._colorShader;
  25847. },
  25848. enumerable: true,
  25849. configurable: true
  25850. });
  25851. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25852. get: function () {
  25853. return false;
  25854. },
  25855. enumerable: true,
  25856. configurable: true
  25857. });
  25858. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25859. get: function () {
  25860. return false;
  25861. },
  25862. enumerable: true,
  25863. configurable: true
  25864. });
  25865. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25866. var engine = this.getScene().getEngine();
  25867. var indexToBind = this._geometry.getIndexBuffer();
  25868. // VBOs
  25869. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25870. // Color
  25871. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25872. };
  25873. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25874. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25875. return;
  25876. }
  25877. var engine = this.getScene().getEngine();
  25878. // Draw order
  25879. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25880. };
  25881. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25882. return null;
  25883. };
  25884. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25885. this._colorShader.dispose();
  25886. _super.prototype.dispose.call(this, doNotRecurse);
  25887. };
  25888. return LinesMesh;
  25889. })(BABYLON.Mesh);
  25890. BABYLON.LinesMesh = LinesMesh;
  25891. })(BABYLON || (BABYLON = {}));
  25892. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25893. (function (BABYLON) {
  25894. var OutlineRenderer = (function () {
  25895. function OutlineRenderer(scene) {
  25896. this._scene = scene;
  25897. }
  25898. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25899. var _this = this;
  25900. if (useOverlay === void 0) { useOverlay = false; }
  25901. var scene = this._scene;
  25902. var engine = this._scene.getEngine();
  25903. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25904. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25905. return;
  25906. }
  25907. var mesh = subMesh.getRenderingMesh();
  25908. var material = subMesh.getMaterial();
  25909. engine.enableEffect(this._effect);
  25910. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25911. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25912. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25913. // Bones
  25914. if (mesh.useBones) {
  25915. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25916. }
  25917. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25918. // Alpha test
  25919. if (material && material.needAlphaTesting()) {
  25920. var alphaTexture = material.getAlphaTestTexture();
  25921. this._effect.setTexture("diffuseSampler", alphaTexture);
  25922. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25923. }
  25924. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25925. _this._effect.setMatrix("world", world);
  25926. });
  25927. };
  25928. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25929. var defines = [];
  25930. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25931. var mesh = subMesh.getMesh();
  25932. var material = subMesh.getMaterial();
  25933. // Alpha test
  25934. if (material && material.needAlphaTesting()) {
  25935. defines.push("#define ALPHATEST");
  25936. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25937. attribs.push(BABYLON.VertexBuffer.UVKind);
  25938. defines.push("#define UV1");
  25939. }
  25940. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25941. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25942. defines.push("#define UV2");
  25943. }
  25944. }
  25945. // Bones
  25946. if (mesh.useBones) {
  25947. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25948. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25949. defines.push("#define BONES");
  25950. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25951. }
  25952. // Instances
  25953. if (useInstances) {
  25954. defines.push("#define INSTANCES");
  25955. attribs.push("world0");
  25956. attribs.push("world1");
  25957. attribs.push("world2");
  25958. attribs.push("world3");
  25959. }
  25960. // Get correct effect
  25961. var join = defines.join("\n");
  25962. if (this._cachedDefines !== join) {
  25963. this._cachedDefines = join;
  25964. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25965. }
  25966. return this._effect.isReady();
  25967. };
  25968. return OutlineRenderer;
  25969. })();
  25970. BABYLON.OutlineRenderer = OutlineRenderer;
  25971. })(BABYLON || (BABYLON = {}));
  25972. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25973. (function (BABYLON) {
  25974. var MeshAssetTask = (function () {
  25975. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25976. this.name = name;
  25977. this.meshesNames = meshesNames;
  25978. this.rootUrl = rootUrl;
  25979. this.sceneFilename = sceneFilename;
  25980. this.isCompleted = false;
  25981. }
  25982. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25983. var _this = this;
  25984. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25985. _this.loadedMeshes = meshes;
  25986. _this.loadedParticleSystems = particleSystems;
  25987. _this.loadedSkeletons = skeletons;
  25988. _this.isCompleted = true;
  25989. if (_this.onSuccess) {
  25990. _this.onSuccess(_this);
  25991. }
  25992. onSuccess();
  25993. }, null, function () {
  25994. if (_this.onError) {
  25995. _this.onError(_this);
  25996. }
  25997. onError();
  25998. });
  25999. };
  26000. return MeshAssetTask;
  26001. })();
  26002. BABYLON.MeshAssetTask = MeshAssetTask;
  26003. var TextFileAssetTask = (function () {
  26004. function TextFileAssetTask(name, url) {
  26005. this.name = name;
  26006. this.url = url;
  26007. this.isCompleted = false;
  26008. }
  26009. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26010. var _this = this;
  26011. BABYLON.Tools.LoadFile(this.url, function (data) {
  26012. _this.text = data;
  26013. _this.isCompleted = true;
  26014. if (_this.onSuccess) {
  26015. _this.onSuccess(_this);
  26016. }
  26017. onSuccess();
  26018. }, null, scene.database, false, function () {
  26019. if (_this.onError) {
  26020. _this.onError(_this);
  26021. }
  26022. onError();
  26023. });
  26024. };
  26025. return TextFileAssetTask;
  26026. })();
  26027. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26028. var BinaryFileAssetTask = (function () {
  26029. function BinaryFileAssetTask(name, url) {
  26030. this.name = name;
  26031. this.url = url;
  26032. this.isCompleted = false;
  26033. }
  26034. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26035. var _this = this;
  26036. BABYLON.Tools.LoadFile(this.url, function (data) {
  26037. _this.data = data;
  26038. _this.isCompleted = true;
  26039. if (_this.onSuccess) {
  26040. _this.onSuccess(_this);
  26041. }
  26042. onSuccess();
  26043. }, null, scene.database, true, function () {
  26044. if (_this.onError) {
  26045. _this.onError(_this);
  26046. }
  26047. onError();
  26048. });
  26049. };
  26050. return BinaryFileAssetTask;
  26051. })();
  26052. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26053. var ImageAssetTask = (function () {
  26054. function ImageAssetTask(name, url) {
  26055. this.name = name;
  26056. this.url = url;
  26057. this.isCompleted = false;
  26058. }
  26059. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26060. var _this = this;
  26061. var img = new Image();
  26062. img.onload = function () {
  26063. _this.image = img;
  26064. _this.isCompleted = true;
  26065. if (_this.onSuccess) {
  26066. _this.onSuccess(_this);
  26067. }
  26068. onSuccess();
  26069. };
  26070. img.onerror = function () {
  26071. if (_this.onError) {
  26072. _this.onError(_this);
  26073. }
  26074. onError();
  26075. };
  26076. img.src = this.url;
  26077. };
  26078. return ImageAssetTask;
  26079. })();
  26080. BABYLON.ImageAssetTask = ImageAssetTask;
  26081. var TextureAssetTask = (function () {
  26082. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26083. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26084. this.name = name;
  26085. this.url = url;
  26086. this.noMipmap = noMipmap;
  26087. this.invertY = invertY;
  26088. this.samplingMode = samplingMode;
  26089. this.isCompleted = false;
  26090. }
  26091. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26092. var _this = this;
  26093. var onload = function () {
  26094. _this.isCompleted = true;
  26095. if (_this.onSuccess) {
  26096. _this.onSuccess(_this);
  26097. }
  26098. onSuccess();
  26099. };
  26100. var onerror = function () {
  26101. if (_this.onError) {
  26102. _this.onError(_this);
  26103. }
  26104. onError();
  26105. };
  26106. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26107. };
  26108. return TextureAssetTask;
  26109. })();
  26110. BABYLON.TextureAssetTask = TextureAssetTask;
  26111. var AssetsManager = (function () {
  26112. function AssetsManager(scene) {
  26113. this._tasks = new Array();
  26114. this._waitingTasksCount = 0;
  26115. this.useDefaultLoadingScreen = true;
  26116. this._scene = scene;
  26117. }
  26118. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26119. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26120. this._tasks.push(task);
  26121. return task;
  26122. };
  26123. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26124. var task = new TextFileAssetTask(taskName, url);
  26125. this._tasks.push(task);
  26126. return task;
  26127. };
  26128. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26129. var task = new BinaryFileAssetTask(taskName, url);
  26130. this._tasks.push(task);
  26131. return task;
  26132. };
  26133. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26134. var task = new ImageAssetTask(taskName, url);
  26135. this._tasks.push(task);
  26136. return task;
  26137. };
  26138. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26139. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26140. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26141. this._tasks.push(task);
  26142. return task;
  26143. };
  26144. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26145. this._waitingTasksCount--;
  26146. if (this._waitingTasksCount === 0) {
  26147. if (this.onFinish) {
  26148. this.onFinish(this._tasks);
  26149. }
  26150. this._scene.getEngine().hideLoadingUI();
  26151. }
  26152. };
  26153. AssetsManager.prototype._runTask = function (task) {
  26154. var _this = this;
  26155. task.run(this._scene, function () {
  26156. if (_this.onTaskSuccess) {
  26157. _this.onTaskSuccess(task);
  26158. }
  26159. _this._decreaseWaitingTasksCount();
  26160. }, function () {
  26161. if (_this.onTaskError) {
  26162. _this.onTaskError(task);
  26163. }
  26164. _this._decreaseWaitingTasksCount();
  26165. });
  26166. };
  26167. AssetsManager.prototype.reset = function () {
  26168. this._tasks = new Array();
  26169. return this;
  26170. };
  26171. AssetsManager.prototype.load = function () {
  26172. this._waitingTasksCount = this._tasks.length;
  26173. if (this._waitingTasksCount === 0) {
  26174. if (this.onFinish) {
  26175. this.onFinish(this._tasks);
  26176. }
  26177. return this;
  26178. }
  26179. if (this.useDefaultLoadingScreen) {
  26180. this._scene.getEngine().displayLoadingUI();
  26181. }
  26182. for (var index = 0; index < this._tasks.length; index++) {
  26183. var task = this._tasks[index];
  26184. this._runTask(task);
  26185. }
  26186. return this;
  26187. };
  26188. return AssetsManager;
  26189. })();
  26190. BABYLON.AssetsManager = AssetsManager;
  26191. })(BABYLON || (BABYLON = {}));
  26192. //# sourceMappingURL=babylon.assetsManager.js.map
  26193. var BABYLON;
  26194. (function (BABYLON) {
  26195. var VRDeviceOrientationCamera = (function (_super) {
  26196. __extends(VRDeviceOrientationCamera, _super);
  26197. function VRDeviceOrientationCamera(name, position, scene) {
  26198. _super.call(this, name, position, scene);
  26199. this._alpha = 0;
  26200. this._beta = 0;
  26201. this._gamma = 0;
  26202. }
  26203. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26204. this._alpha = +evt.alpha | 0;
  26205. this._beta = +evt.beta | 0;
  26206. this._gamma = +evt.gamma | 0;
  26207. if (this._gamma < 0) {
  26208. this._gamma = 90 + this._gamma;
  26209. }
  26210. else {
  26211. // Incline it in the correct angle.
  26212. this._gamma = 270 - this._gamma;
  26213. }
  26214. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26215. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26216. this.rotation.z = this._beta / 180.0 * Math.PI;
  26217. };
  26218. return VRDeviceOrientationCamera;
  26219. })(BABYLON.OculusCamera);
  26220. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26221. })(BABYLON || (BABYLON = {}));
  26222. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26223. var BABYLON;
  26224. (function (BABYLON) {
  26225. var WebVRCamera = (function (_super) {
  26226. __extends(WebVRCamera, _super);
  26227. function WebVRCamera(name, position, scene) {
  26228. _super.call(this, name, position, scene);
  26229. this._hmdDevice = null;
  26230. this._sensorDevice = null;
  26231. this._cacheState = null;
  26232. this._cacheQuaternion = new BABYLON.Quaternion();
  26233. this._cacheRotation = BABYLON.Vector3.Zero();
  26234. this._vrEnabled = false;
  26235. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26236. }
  26237. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26238. var size = devices.length;
  26239. var i = 0;
  26240. // Reset devices.
  26241. this._sensorDevice = null;
  26242. this._hmdDevice = null;
  26243. while (i < size && this._hmdDevice === null) {
  26244. if (devices[i] instanceof HMDVRDevice) {
  26245. this._hmdDevice = devices[i];
  26246. }
  26247. i++;
  26248. }
  26249. i = 0;
  26250. while (i < size && this._sensorDevice === null) {
  26251. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26252. this._sensorDevice = devices[i];
  26253. }
  26254. i++;
  26255. }
  26256. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26257. };
  26258. WebVRCamera.prototype._update = function () {
  26259. if (this._vrEnabled) {
  26260. this._cacheState = this._sensorDevice.getState();
  26261. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26262. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26263. this.rotation.x = -this._cacheRotation.z;
  26264. this.rotation.y = -this._cacheRotation.y;
  26265. this.rotation.z = this._cacheRotation.x;
  26266. }
  26267. _super.prototype._update.call(this);
  26268. };
  26269. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26270. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26271. if (navigator.getVRDevices) {
  26272. navigator.getVRDevices().then(this._getWebVRDevices);
  26273. }
  26274. else if (navigator.mozGetVRDevices) {
  26275. navigator.mozGetVRDevices(this._getWebVRDevices);
  26276. }
  26277. };
  26278. WebVRCamera.prototype.detachControl = function (element) {
  26279. _super.prototype.detachControl.call(this, element);
  26280. this._vrEnabled = false;
  26281. };
  26282. return WebVRCamera;
  26283. })(BABYLON.OculusCamera);
  26284. BABYLON.WebVRCamera = WebVRCamera;
  26285. })(BABYLON || (BABYLON = {}));
  26286. //# sourceMappingURL=babylon.webVRCamera.js.map
  26287. var BABYLON;
  26288. (function (BABYLON) {
  26289. // Standard optimizations
  26290. var SceneOptimization = (function () {
  26291. function SceneOptimization(priority) {
  26292. if (priority === void 0) { priority = 0; }
  26293. this.priority = priority;
  26294. this.apply = function (scene) {
  26295. return true; // Return true if everything that can be done was applied
  26296. };
  26297. }
  26298. return SceneOptimization;
  26299. })();
  26300. BABYLON.SceneOptimization = SceneOptimization;
  26301. var TextureOptimization = (function (_super) {
  26302. __extends(TextureOptimization, _super);
  26303. function TextureOptimization(priority, maximumSize) {
  26304. var _this = this;
  26305. if (priority === void 0) { priority = 0; }
  26306. if (maximumSize === void 0) { maximumSize = 1024; }
  26307. _super.call(this, priority);
  26308. this.priority = priority;
  26309. this.maximumSize = maximumSize;
  26310. this.apply = function (scene) {
  26311. var allDone = true;
  26312. for (var index = 0; index < scene.textures.length; index++) {
  26313. var texture = scene.textures[index];
  26314. if (!texture.canRescale) {
  26315. continue;
  26316. }
  26317. var currentSize = texture.getSize();
  26318. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26319. if (maxDimension > _this.maximumSize) {
  26320. texture.scale(0.5);
  26321. allDone = false;
  26322. }
  26323. }
  26324. return allDone;
  26325. };
  26326. }
  26327. return TextureOptimization;
  26328. })(SceneOptimization);
  26329. BABYLON.TextureOptimization = TextureOptimization;
  26330. var HardwareScalingOptimization = (function (_super) {
  26331. __extends(HardwareScalingOptimization, _super);
  26332. function HardwareScalingOptimization(priority, maximumScale) {
  26333. var _this = this;
  26334. if (priority === void 0) { priority = 0; }
  26335. if (maximumScale === void 0) { maximumScale = 2; }
  26336. _super.call(this, priority);
  26337. this.priority = priority;
  26338. this.maximumScale = maximumScale;
  26339. this._currentScale = 1;
  26340. this.apply = function (scene) {
  26341. _this._currentScale++;
  26342. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26343. return _this._currentScale >= _this.maximumScale;
  26344. };
  26345. }
  26346. return HardwareScalingOptimization;
  26347. })(SceneOptimization);
  26348. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26349. var ShadowsOptimization = (function (_super) {
  26350. __extends(ShadowsOptimization, _super);
  26351. function ShadowsOptimization() {
  26352. _super.apply(this, arguments);
  26353. this.apply = function (scene) {
  26354. scene.shadowsEnabled = false;
  26355. return true;
  26356. };
  26357. }
  26358. return ShadowsOptimization;
  26359. })(SceneOptimization);
  26360. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26361. var PostProcessesOptimization = (function (_super) {
  26362. __extends(PostProcessesOptimization, _super);
  26363. function PostProcessesOptimization() {
  26364. _super.apply(this, arguments);
  26365. this.apply = function (scene) {
  26366. scene.postProcessesEnabled = false;
  26367. return true;
  26368. };
  26369. }
  26370. return PostProcessesOptimization;
  26371. })(SceneOptimization);
  26372. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26373. var LensFlaresOptimization = (function (_super) {
  26374. __extends(LensFlaresOptimization, _super);
  26375. function LensFlaresOptimization() {
  26376. _super.apply(this, arguments);
  26377. this.apply = function (scene) {
  26378. scene.lensFlaresEnabled = false;
  26379. return true;
  26380. };
  26381. }
  26382. return LensFlaresOptimization;
  26383. })(SceneOptimization);
  26384. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26385. var ParticlesOptimization = (function (_super) {
  26386. __extends(ParticlesOptimization, _super);
  26387. function ParticlesOptimization() {
  26388. _super.apply(this, arguments);
  26389. this.apply = function (scene) {
  26390. scene.particlesEnabled = false;
  26391. return true;
  26392. };
  26393. }
  26394. return ParticlesOptimization;
  26395. })(SceneOptimization);
  26396. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26397. var RenderTargetsOptimization = (function (_super) {
  26398. __extends(RenderTargetsOptimization, _super);
  26399. function RenderTargetsOptimization() {
  26400. _super.apply(this, arguments);
  26401. this.apply = function (scene) {
  26402. scene.renderTargetsEnabled = false;
  26403. return true;
  26404. };
  26405. }
  26406. return RenderTargetsOptimization;
  26407. })(SceneOptimization);
  26408. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26409. var MergeMeshesOptimization = (function (_super) {
  26410. __extends(MergeMeshesOptimization, _super);
  26411. function MergeMeshesOptimization() {
  26412. var _this = this;
  26413. _super.apply(this, arguments);
  26414. this._canBeMerged = function (abstractMesh) {
  26415. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26416. return false;
  26417. }
  26418. var mesh = abstractMesh;
  26419. if (!mesh.isVisible || !mesh.isEnabled()) {
  26420. return false;
  26421. }
  26422. if (mesh.instances.length > 0) {
  26423. return false;
  26424. }
  26425. if (mesh.skeleton || mesh.hasLODLevels) {
  26426. return false;
  26427. }
  26428. return true;
  26429. };
  26430. this.apply = function (scene) {
  26431. var globalPool = scene.meshes.slice(0);
  26432. var globalLength = globalPool.length;
  26433. for (var index = 0; index < globalLength; index++) {
  26434. var currentPool = new Array();
  26435. var current = globalPool[index];
  26436. // Checks
  26437. if (!_this._canBeMerged(current)) {
  26438. continue;
  26439. }
  26440. currentPool.push(current);
  26441. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26442. var otherMesh = globalPool[subIndex];
  26443. if (!_this._canBeMerged(otherMesh)) {
  26444. continue;
  26445. }
  26446. if (otherMesh.material !== current.material) {
  26447. continue;
  26448. }
  26449. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26450. continue;
  26451. }
  26452. currentPool.push(otherMesh);
  26453. globalLength--;
  26454. globalPool.splice(subIndex, 1);
  26455. subIndex--;
  26456. }
  26457. if (currentPool.length < 2) {
  26458. continue;
  26459. }
  26460. // Merge meshes
  26461. BABYLON.Mesh.MergeMeshes(currentPool);
  26462. }
  26463. return true;
  26464. };
  26465. }
  26466. return MergeMeshesOptimization;
  26467. })(SceneOptimization);
  26468. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26469. // Options
  26470. var SceneOptimizerOptions = (function () {
  26471. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26472. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26473. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26474. this.targetFrameRate = targetFrameRate;
  26475. this.trackerDuration = trackerDuration;
  26476. this.optimizations = new Array();
  26477. }
  26478. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26479. var result = new SceneOptimizerOptions(targetFrameRate);
  26480. var priority = 0;
  26481. result.optimizations.push(new MergeMeshesOptimization(priority));
  26482. result.optimizations.push(new ShadowsOptimization(priority));
  26483. result.optimizations.push(new LensFlaresOptimization(priority));
  26484. // Next priority
  26485. priority++;
  26486. result.optimizations.push(new PostProcessesOptimization(priority));
  26487. result.optimizations.push(new ParticlesOptimization(priority));
  26488. // Next priority
  26489. priority++;
  26490. result.optimizations.push(new TextureOptimization(priority, 1024));
  26491. return result;
  26492. };
  26493. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26494. var result = new SceneOptimizerOptions(targetFrameRate);
  26495. var priority = 0;
  26496. result.optimizations.push(new MergeMeshesOptimization(priority));
  26497. result.optimizations.push(new ShadowsOptimization(priority));
  26498. result.optimizations.push(new LensFlaresOptimization(priority));
  26499. // Next priority
  26500. priority++;
  26501. result.optimizations.push(new PostProcessesOptimization(priority));
  26502. result.optimizations.push(new ParticlesOptimization(priority));
  26503. // Next priority
  26504. priority++;
  26505. result.optimizations.push(new TextureOptimization(priority, 512));
  26506. // Next priority
  26507. priority++;
  26508. result.optimizations.push(new RenderTargetsOptimization(priority));
  26509. // Next priority
  26510. priority++;
  26511. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26512. return result;
  26513. };
  26514. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26515. var result = new SceneOptimizerOptions(targetFrameRate);
  26516. var priority = 0;
  26517. result.optimizations.push(new MergeMeshesOptimization(priority));
  26518. result.optimizations.push(new ShadowsOptimization(priority));
  26519. result.optimizations.push(new LensFlaresOptimization(priority));
  26520. // Next priority
  26521. priority++;
  26522. result.optimizations.push(new PostProcessesOptimization(priority));
  26523. result.optimizations.push(new ParticlesOptimization(priority));
  26524. // Next priority
  26525. priority++;
  26526. result.optimizations.push(new TextureOptimization(priority, 256));
  26527. // Next priority
  26528. priority++;
  26529. result.optimizations.push(new RenderTargetsOptimization(priority));
  26530. // Next priority
  26531. priority++;
  26532. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26533. return result;
  26534. };
  26535. return SceneOptimizerOptions;
  26536. })();
  26537. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26538. // Scene optimizer tool
  26539. var SceneOptimizer = (function () {
  26540. function SceneOptimizer() {
  26541. }
  26542. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26543. // TODO: add an epsilon
  26544. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26545. if (onSuccess) {
  26546. onSuccess();
  26547. }
  26548. return;
  26549. }
  26550. // Apply current level of optimizations
  26551. var allDone = true;
  26552. var noOptimizationApplied = true;
  26553. for (var index = 0; index < options.optimizations.length; index++) {
  26554. var optimization = options.optimizations[index];
  26555. if (optimization.priority === currentPriorityLevel) {
  26556. noOptimizationApplied = false;
  26557. allDone = allDone && optimization.apply(scene);
  26558. }
  26559. }
  26560. // If no optimization was applied, this is a failure :(
  26561. if (noOptimizationApplied) {
  26562. if (onFailure) {
  26563. onFailure();
  26564. }
  26565. return;
  26566. }
  26567. // If all optimizations were done, move to next level
  26568. if (allDone) {
  26569. currentPriorityLevel++;
  26570. }
  26571. // Let's the system running for a specific amount of time before checking FPS
  26572. scene.executeWhenReady(function () {
  26573. setTimeout(function () {
  26574. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26575. }, options.trackerDuration);
  26576. });
  26577. };
  26578. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26579. if (!options) {
  26580. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26581. }
  26582. // Let's the system running for a specific amount of time before checking FPS
  26583. scene.executeWhenReady(function () {
  26584. setTimeout(function () {
  26585. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26586. }, options.trackerDuration);
  26587. });
  26588. };
  26589. return SceneOptimizer;
  26590. })();
  26591. BABYLON.SceneOptimizer = SceneOptimizer;
  26592. })(BABYLON || (BABYLON = {}));
  26593. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26594. (function (BABYLON) {
  26595. var Internals;
  26596. (function (Internals) {
  26597. var MeshLODLevel = (function () {
  26598. function MeshLODLevel(distance, mesh) {
  26599. this.distance = distance;
  26600. this.mesh = mesh;
  26601. }
  26602. return MeshLODLevel;
  26603. })();
  26604. Internals.MeshLODLevel = MeshLODLevel;
  26605. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26606. })(BABYLON || (BABYLON = {}));
  26607. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26608. (function (BABYLON) {
  26609. var AudioEngine = (function () {
  26610. function AudioEngine() {
  26611. this.audioContext = null;
  26612. this.canUseWebAudio = false;
  26613. this.WarnedWebAudioUnsupported = false;
  26614. try {
  26615. if (typeof AudioContext !== 'undefined') {
  26616. this.audioContext = new AudioContext();
  26617. this.canUseWebAudio = true;
  26618. }
  26619. else if (typeof webkitAudioContext !== 'undefined') {
  26620. this.audioContext = new webkitAudioContext();
  26621. this.canUseWebAudio = true;
  26622. }
  26623. }
  26624. catch (e) {
  26625. this.canUseWebAudio = false;
  26626. BABYLON.Tools.Error("Web Audio: " + e.message);
  26627. }
  26628. // create a global volume gain node
  26629. if (this.canUseWebAudio) {
  26630. this.masterGain = this.audioContext.createGain();
  26631. this.masterGain.gain.value = 1;
  26632. this.masterGain.connect(this.audioContext.destination);
  26633. }
  26634. }
  26635. AudioEngine.prototype.dispose = function () {
  26636. if (this.canUseWebAudio) {
  26637. if (this._connectedAnalyser) {
  26638. this._connectedAnalyser.stopDebugCanvas();
  26639. this._connectedAnalyser.dispose();
  26640. this.masterGain.disconnect();
  26641. this.masterGain.connect(this.audioContext.destination);
  26642. this._connectedAnalyser = null;
  26643. }
  26644. this.masterGain.gain.value = 1;
  26645. }
  26646. this.WarnedWebAudioUnsupported = false;
  26647. };
  26648. AudioEngine.prototype.getGlobalVolume = function () {
  26649. if (this.canUseWebAudio) {
  26650. return this.masterGain.gain.value;
  26651. }
  26652. else {
  26653. return -1;
  26654. }
  26655. };
  26656. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26657. if (this.canUseWebAudio) {
  26658. this.masterGain.gain.value = newVolume;
  26659. }
  26660. };
  26661. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26662. if (this._connectedAnalyser) {
  26663. this._connectedAnalyser.stopDebugCanvas();
  26664. }
  26665. this._connectedAnalyser = analyser;
  26666. if (this.canUseWebAudio) {
  26667. this.masterGain.disconnect();
  26668. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26669. }
  26670. };
  26671. return AudioEngine;
  26672. })();
  26673. BABYLON.AudioEngine = AudioEngine;
  26674. })(BABYLON || (BABYLON = {}));
  26675. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  26676. (function (BABYLON) {
  26677. var Sound = (function () {
  26678. /**
  26679. * Create a sound and attach it to a scene
  26680. * @param name Name of your sound
  26681. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26682. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26683. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26684. */
  26685. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26686. var _this = this;
  26687. this.autoplay = false;
  26688. this.loop = false;
  26689. this.useCustomAttenuation = false;
  26690. this.spatialSound = false;
  26691. this.refDistance = 1;
  26692. this.rolloffFactor = 1;
  26693. this.maxDistance = 100;
  26694. this.distanceModel = "linear";
  26695. this._panningModel = "equalpower";
  26696. this._playbackRate = 1;
  26697. this._startTime = 0;
  26698. this._startOffset = 0;
  26699. this._position = BABYLON.Vector3.Zero();
  26700. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26701. this._volume = 1;
  26702. this._isLoaded = false;
  26703. this._isReadyToPlay = false;
  26704. this.isPlaying = false;
  26705. this.isPaused = false;
  26706. this._isDirectional = false;
  26707. // Used if you'd like to create a directional sound.
  26708. // If not set, the sound will be omnidirectional
  26709. this._coneInnerAngle = 360;
  26710. this._coneOuterAngle = 360;
  26711. this._coneOuterGain = 0;
  26712. this.name = name;
  26713. this._scene = scene;
  26714. this._readyToPlayCallback = readyToPlayCallback;
  26715. // Default custom attenuation function is a linear attenuation
  26716. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26717. if (currentDistance < maxDistance) {
  26718. return currentVolume * (1 - currentDistance / maxDistance);
  26719. }
  26720. else {
  26721. return 0;
  26722. }
  26723. };
  26724. if (options) {
  26725. this.autoplay = options.autoplay || false;
  26726. this.loop = options.loop || false;
  26727. // if volume === 0, we need another way to check this option
  26728. if (options.volume !== undefined) {
  26729. this._volume = options.volume;
  26730. }
  26731. this.spatialSound = options.spatialSound || false;
  26732. this.maxDistance = options.maxDistance || 100;
  26733. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26734. this.rolloffFactor = options.rolloffFactor || 1;
  26735. this.refDistance = options.refDistance || 1;
  26736. this.distanceModel = options.distanceModel || "linear";
  26737. this._playbackRate = options.playbackRate || 1;
  26738. }
  26739. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26740. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26741. this._soundGain.gain.value = this._volume;
  26742. this._inputAudioNode = this._soundGain;
  26743. this._ouputAudioNode = this._soundGain;
  26744. if (this.spatialSound) {
  26745. this._createSpatialParameters();
  26746. }
  26747. this._scene.mainSoundTrack.AddSound(this);
  26748. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26749. if (urlOrArrayBuffer) {
  26750. // If it's an URL
  26751. if (typeof (urlOrArrayBuffer) === "string") {
  26752. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26753. _this._soundLoaded(data);
  26754. }, null, null, true);
  26755. }
  26756. else {
  26757. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26758. this._soundLoaded(urlOrArrayBuffer);
  26759. }
  26760. else {
  26761. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26762. }
  26763. }
  26764. }
  26765. }
  26766. else {
  26767. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26768. this._scene.mainSoundTrack.AddSound(this);
  26769. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26770. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26771. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26772. }
  26773. }
  26774. }
  26775. Sound.prototype.dispose = function () {
  26776. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26777. if (this.isPlaying) {
  26778. this.stop();
  26779. }
  26780. this._isReadyToPlay = false;
  26781. if (this.soundTrackId === -1) {
  26782. this._scene.mainSoundTrack.RemoveSound(this);
  26783. }
  26784. else {
  26785. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26786. }
  26787. if (this._soundGain) {
  26788. this._soundGain.disconnect();
  26789. this._soundGain = null;
  26790. }
  26791. if (this._soundPanner) {
  26792. this._soundPanner.disconnect();
  26793. this._soundPanner = null;
  26794. }
  26795. if (this._soundSource) {
  26796. this._soundSource.disconnect();
  26797. this._soundSource = null;
  26798. }
  26799. this._audioBuffer = null;
  26800. if (this._connectedMesh) {
  26801. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26802. this._connectedMesh = null;
  26803. }
  26804. }
  26805. };
  26806. Sound.prototype._soundLoaded = function (audioData) {
  26807. var _this = this;
  26808. this._isLoaded = true;
  26809. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26810. _this._audioBuffer = buffer;
  26811. _this._isReadyToPlay = true;
  26812. if (_this.autoplay) {
  26813. _this.play();
  26814. }
  26815. if (_this._readyToPlayCallback) {
  26816. _this._readyToPlayCallback();
  26817. }
  26818. }, function (error) {
  26819. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26820. });
  26821. };
  26822. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26823. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26824. this._audioBuffer = audioBuffer;
  26825. this._isReadyToPlay = true;
  26826. }
  26827. };
  26828. Sound.prototype.updateOptions = function (options) {
  26829. if (options) {
  26830. this.loop = options.loop || this.loop;
  26831. this.maxDistance = options.maxDistance || this.maxDistance;
  26832. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26833. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26834. this.refDistance = options.refDistance || this.refDistance;
  26835. this.distanceModel = options.distanceModel || this.distanceModel;
  26836. this._playbackRate = options.playbackRate || this._playbackRate;
  26837. }
  26838. };
  26839. Sound.prototype._createSpatialParameters = function () {
  26840. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26841. if (this._scene.headphone) {
  26842. this._panningModel = "HRTF";
  26843. }
  26844. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26845. if (this.useCustomAttenuation) {
  26846. // Tricks to disable in a way embedded Web Audio attenuation
  26847. this._soundPanner.distanceModel = "linear";
  26848. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26849. this._soundPanner.refDistance = 1;
  26850. this._soundPanner.rolloffFactor = 1;
  26851. this._soundPanner.panningModel = this._panningModel;
  26852. }
  26853. else {
  26854. this._soundPanner.distanceModel = this.distanceModel;
  26855. this._soundPanner.maxDistance = this.maxDistance;
  26856. this._soundPanner.refDistance = this.refDistance;
  26857. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26858. this._soundPanner.panningModel = this._panningModel;
  26859. }
  26860. this._soundPanner.connect(this._ouputAudioNode);
  26861. this._inputAudioNode = this._soundPanner;
  26862. }
  26863. };
  26864. Sound.prototype.switchPanningModelToHRTF = function () {
  26865. this._panningModel = "HRTF";
  26866. this._switchPanningModel();
  26867. };
  26868. Sound.prototype.switchPanningModelToEqualPower = function () {
  26869. this._panningModel = "equalpower";
  26870. this._switchPanningModel();
  26871. };
  26872. Sound.prototype._switchPanningModel = function () {
  26873. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  26874. this._soundPanner.panningModel = this._panningModel;
  26875. }
  26876. };
  26877. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26878. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26879. this._ouputAudioNode.disconnect();
  26880. this._ouputAudioNode.connect(soundTrackAudioNode);
  26881. }
  26882. };
  26883. /**
  26884. * Transform this sound into a directional source
  26885. * @param coneInnerAngle Size of the inner cone in degree
  26886. * @param coneOuterAngle Size of the outer cone in degree
  26887. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26888. */
  26889. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26890. if (coneOuterAngle < coneInnerAngle) {
  26891. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26892. return;
  26893. }
  26894. this._coneInnerAngle = coneInnerAngle;
  26895. this._coneOuterAngle = coneOuterAngle;
  26896. this._coneOuterGain = coneOuterGain;
  26897. this._isDirectional = true;
  26898. if (this.isPlaying && this.loop) {
  26899. this.stop();
  26900. this.play();
  26901. }
  26902. };
  26903. Sound.prototype.setPosition = function (newPosition) {
  26904. this._position = newPosition;
  26905. if (this.isPlaying && this.spatialSound) {
  26906. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26907. }
  26908. };
  26909. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26910. this._localDirection = newLocalDirection;
  26911. if (this._connectedMesh && this.isPlaying) {
  26912. this._updateDirection();
  26913. }
  26914. };
  26915. Sound.prototype._updateDirection = function () {
  26916. var mat = this._connectedMesh.getWorldMatrix();
  26917. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26918. direction.normalize();
  26919. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26920. };
  26921. Sound.prototype.updateDistanceFromListener = function () {
  26922. if (this._connectedMesh && this.useCustomAttenuation) {
  26923. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26924. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26925. }
  26926. };
  26927. Sound.prototype.setAttenuationFunction = function (callback) {
  26928. this._customAttenuationFunction = callback;
  26929. };
  26930. /**
  26931. * Play the sound
  26932. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26933. */
  26934. Sound.prototype.play = function (time) {
  26935. var _this = this;
  26936. if (this._isReadyToPlay && this._scene.audioEnabled) {
  26937. try {
  26938. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26939. if (!this._soundSource) {
  26940. if (this.spatialSound) {
  26941. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26942. if (this._isDirectional) {
  26943. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26944. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26945. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26946. if (this._connectedMesh) {
  26947. this._updateDirection();
  26948. }
  26949. else {
  26950. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26951. }
  26952. }
  26953. }
  26954. }
  26955. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26956. this._soundSource.buffer = this._audioBuffer;
  26957. this._soundSource.connect(this._inputAudioNode);
  26958. this._soundSource.loop = this.loop;
  26959. this._soundSource.playbackRate.value = this._playbackRate;
  26960. this._startTime = startTime;
  26961. this._soundSource.onended = function () {
  26962. _this._onended();
  26963. };
  26964. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  26965. this.isPlaying = true;
  26966. this.isPaused = false;
  26967. }
  26968. catch (ex) {
  26969. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26970. }
  26971. }
  26972. };
  26973. Sound.prototype._onended = function () {
  26974. this.isPlaying = false;
  26975. if (this.onended) {
  26976. this.onended();
  26977. }
  26978. };
  26979. /**
  26980. * Stop the sound
  26981. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26982. */
  26983. Sound.prototype.stop = function (time) {
  26984. if (this.isPlaying) {
  26985. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26986. this._soundSource.stop(stopTime);
  26987. this.isPlaying = false;
  26988. }
  26989. };
  26990. Sound.prototype.pause = function () {
  26991. if (this.isPlaying) {
  26992. this.stop(0);
  26993. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26994. this.isPaused = true;
  26995. }
  26996. };
  26997. Sound.prototype.setVolume = function (newVolume, time) {
  26998. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26999. if (time) {
  27000. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27001. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27002. }
  27003. else {
  27004. this._soundGain.gain.value = newVolume;
  27005. }
  27006. }
  27007. this._volume = newVolume;
  27008. };
  27009. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27010. this._playbackRate = newPlaybackRate;
  27011. if (this.isPlaying) {
  27012. this._soundSource.playbackRate.value = this._playbackRate;
  27013. }
  27014. };
  27015. Sound.prototype.getVolume = function () {
  27016. return this._volume;
  27017. };
  27018. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27019. var _this = this;
  27020. this._connectedMesh = meshToConnectTo;
  27021. if (!this.spatialSound) {
  27022. this._createSpatialParameters();
  27023. this.spatialSound = true;
  27024. if (this.isPlaying && this.loop) {
  27025. this.stop();
  27026. this.play();
  27027. }
  27028. }
  27029. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27030. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27031. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27032. };
  27033. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27034. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27035. if (this._isDirectional && this.isPlaying) {
  27036. this._updateDirection();
  27037. }
  27038. };
  27039. return Sound;
  27040. })();
  27041. BABYLON.Sound = Sound;
  27042. })(BABYLON || (BABYLON = {}));
  27043. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27044. (function (BABYLON) {
  27045. var SoundTrack = (function () {
  27046. function SoundTrack(scene, options) {
  27047. this.id = -1;
  27048. this._isMainTrack = false;
  27049. this._scene = scene;
  27050. this._audioEngine = BABYLON.Engine.audioEngine;
  27051. this.soundCollection = new Array();
  27052. if (this._audioEngine.canUseWebAudio) {
  27053. this._trackGain = this._audioEngine.audioContext.createGain();
  27054. this._trackGain.connect(this._audioEngine.masterGain);
  27055. if (options) {
  27056. if (options.volume) {
  27057. this._trackGain.gain.value = options.volume;
  27058. }
  27059. if (options.mainTrack) {
  27060. this._isMainTrack = options.mainTrack;
  27061. }
  27062. }
  27063. }
  27064. if (!this._isMainTrack) {
  27065. this._scene.soundTracks.push(this);
  27066. this.id = this._scene.soundTracks.length - 1;
  27067. }
  27068. }
  27069. SoundTrack.prototype.dispose = function () {
  27070. if (this._audioEngine.canUseWebAudio) {
  27071. if (this._connectedAnalyser) {
  27072. this._connectedAnalyser.stopDebugCanvas();
  27073. }
  27074. while (this.soundCollection.length) {
  27075. this.soundCollection[0].dispose();
  27076. }
  27077. this._trackGain.disconnect();
  27078. this._trackGain = null;
  27079. }
  27080. };
  27081. SoundTrack.prototype.AddSound = function (sound) {
  27082. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27083. sound.connectToSoundTrackAudioNode(this._trackGain);
  27084. }
  27085. if (sound.soundTrackId) {
  27086. if (sound.soundTrackId === -1) {
  27087. this._scene.mainSoundTrack.RemoveSound(sound);
  27088. }
  27089. else {
  27090. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27091. }
  27092. }
  27093. this.soundCollection.push(sound);
  27094. sound.soundTrackId = this.id;
  27095. };
  27096. SoundTrack.prototype.RemoveSound = function (sound) {
  27097. var index = this.soundCollection.indexOf(sound);
  27098. if (index !== -1) {
  27099. this.soundCollection.splice(index, 1);
  27100. }
  27101. };
  27102. SoundTrack.prototype.setVolume = function (newVolume) {
  27103. if (this._audioEngine.canUseWebAudio) {
  27104. this._trackGain.gain.value = newVolume;
  27105. }
  27106. };
  27107. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27108. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27109. for (var i = 0; i < this.soundCollection.length; i++) {
  27110. this.soundCollection[i].switchPanningModelToHRTF();
  27111. }
  27112. }
  27113. };
  27114. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27115. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27116. for (var i = 0; i < this.soundCollection.length; i++) {
  27117. this.soundCollection[i].switchPanningModelToEqualPower();
  27118. }
  27119. }
  27120. };
  27121. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27122. if (this._connectedAnalyser) {
  27123. this._connectedAnalyser.stopDebugCanvas();
  27124. }
  27125. this._connectedAnalyser = analyser;
  27126. if (this._audioEngine.canUseWebAudio) {
  27127. this._trackGain.disconnect();
  27128. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27129. }
  27130. };
  27131. return SoundTrack;
  27132. })();
  27133. BABYLON.SoundTrack = SoundTrack;
  27134. })(BABYLON || (BABYLON = {}));
  27135. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27136. (function (BABYLON) {
  27137. var DebugLayer = (function () {
  27138. function DebugLayer(scene) {
  27139. var _this = this;
  27140. this._transformationMatrix = BABYLON.Matrix.Identity();
  27141. this._enabled = false;
  27142. this._labelsEnabled = false;
  27143. this._displayStatistics = true;
  27144. this._displayTree = false;
  27145. this._displayLogs = false;
  27146. this._identityMatrix = BABYLON.Matrix.Identity();
  27147. this.axisRatio = 0.02;
  27148. this.accentColor = "orange";
  27149. this._scene = scene;
  27150. this._syncPositions = function () {
  27151. var engine = _this._scene.getEngine();
  27152. var canvasRect = engine.getRenderingCanvasClientRect();
  27153. if (_this._showUI) {
  27154. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27155. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27156. _this._statsDiv.style.width = "400px";
  27157. _this._statsDiv.style.height = "auto";
  27158. _this._statsSubsetDiv.style.maxHeight = "240px";
  27159. _this._optionsDiv.style.left = "0px";
  27160. _this._optionsDiv.style.top = "10px";
  27161. _this._optionsDiv.style.width = "200px";
  27162. _this._optionsDiv.style.height = "auto";
  27163. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27164. _this._logDiv.style.left = "0px";
  27165. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27166. _this._logDiv.style.width = "600px";
  27167. _this._logDiv.style.height = "160px";
  27168. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27169. _this._treeDiv.style.top = "10px";
  27170. _this._treeDiv.style.width = "300px";
  27171. _this._treeDiv.style.height = "auto";
  27172. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27173. }
  27174. _this._globalDiv.style.left = canvasRect.left + "px";
  27175. _this._globalDiv.style.top = canvasRect.top + "px";
  27176. _this._drawingCanvas.style.left = "0px";
  27177. _this._drawingCanvas.style.top = "0px";
  27178. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27179. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27180. var devicePixelRatio = window.devicePixelRatio || 1;
  27181. var context = _this._drawingContext;
  27182. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27183. _this._ratio = devicePixelRatio / backingStoreRatio;
  27184. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27185. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27186. };
  27187. this._onCanvasClick = function (evt) {
  27188. _this._clickPosition = {
  27189. x: evt.clientX * _this._ratio,
  27190. y: evt.clientY * _this._ratio
  27191. };
  27192. };
  27193. this._syncUI = function () {
  27194. if (_this._showUI) {
  27195. if (_this._displayStatistics) {
  27196. _this._displayStats();
  27197. _this._statsDiv.style.display = "";
  27198. }
  27199. else {
  27200. _this._statsDiv.style.display = "none";
  27201. }
  27202. if (_this._displayLogs) {
  27203. _this._logDiv.style.display = "";
  27204. }
  27205. else {
  27206. _this._logDiv.style.display = "none";
  27207. }
  27208. if (_this._displayTree) {
  27209. _this._treeDiv.style.display = "";
  27210. if (_this._needToRefreshMeshesTree) {
  27211. _this._needToRefreshMeshesTree = false;
  27212. _this._refreshMeshesTreeContent();
  27213. }
  27214. }
  27215. else {
  27216. _this._treeDiv.style.display = "none";
  27217. }
  27218. }
  27219. };
  27220. this._syncData = function () {
  27221. if (_this._labelsEnabled || !_this._showUI) {
  27222. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27223. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27224. var engine = _this._scene.getEngine();
  27225. var viewport = _this._camera.viewport;
  27226. var globalViewport = viewport.toGlobal(engine);
  27227. // Meshes
  27228. var meshes = _this._camera.getActiveMeshes();
  27229. for (var index = 0; index < meshes.length; index++) {
  27230. var mesh = meshes.data[index];
  27231. var position = mesh.getBoundingInfo().boundingSphere.center;
  27232. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27233. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27234. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27235. }
  27236. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27237. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27238. mesh.renderOverlay = !mesh.renderOverlay;
  27239. }, function () {
  27240. return mesh.renderOverlay ? 'red' : 'black';
  27241. });
  27242. }
  27243. }
  27244. // Cameras
  27245. var cameras = _this._scene.cameras;
  27246. for (index = 0; index < cameras.length; index++) {
  27247. var camera = cameras[index];
  27248. if (camera === _this._camera) {
  27249. continue;
  27250. }
  27251. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27252. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27253. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27254. _this._camera.detachControl(engine.getRenderingCanvas());
  27255. _this._camera = camera;
  27256. _this._camera.attachControl(engine.getRenderingCanvas());
  27257. }, function () {
  27258. return "purple";
  27259. });
  27260. }
  27261. }
  27262. // Lights
  27263. var lights = _this._scene.lights;
  27264. for (index = 0; index < lights.length; index++) {
  27265. var light = lights[index];
  27266. if (light.position) {
  27267. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27268. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27269. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27270. light.setEnabled(!light.isEnabled());
  27271. }, function () {
  27272. return light.isEnabled() ? "orange" : "gray";
  27273. });
  27274. }
  27275. }
  27276. }
  27277. }
  27278. _this._clickPosition = undefined;
  27279. };
  27280. }
  27281. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27282. while (this._treeSubsetDiv.hasChildNodes()) {
  27283. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27284. }
  27285. // Add meshes
  27286. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27287. sortedArray.sort(function (a, b) {
  27288. if (a.name === b.name) {
  27289. return 0;
  27290. }
  27291. return (a.name > b.name) ? 1 : -1;
  27292. });
  27293. for (var index = 0; index < sortedArray.length; index++) {
  27294. var mesh = sortedArray[index];
  27295. if (!mesh.isEnabled()) {
  27296. continue;
  27297. }
  27298. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27299. m.isVisible = element.checked;
  27300. }, mesh);
  27301. }
  27302. };
  27303. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27304. this._drawingContext.beginPath();
  27305. this._drawingContext.moveTo(zero.x, zero.y);
  27306. this._drawingContext.lineTo(unit.x, unit.y);
  27307. this._drawingContext.strokeStyle = color;
  27308. this._drawingContext.lineWidth = 4;
  27309. this._drawingContext.stroke();
  27310. this._drawingContext.font = "normal 14px Segoe UI";
  27311. this._drawingContext.fillStyle = color;
  27312. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27313. };
  27314. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27315. var position = mesh.getBoundingInfo().boundingSphere.center;
  27316. var worldMatrix = mesh.getWorldMatrix();
  27317. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27318. var unit = (unprojectedVector.subtract(position)).length();
  27319. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27320. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27321. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27322. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27323. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27324. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27325. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27326. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27327. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27328. };
  27329. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27330. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27331. this._drawingContext.font = "normal 12px Segoe UI";
  27332. var textMetrics = this._drawingContext.measureText(text);
  27333. var centerX = projectedPosition.x - textMetrics.width / 2;
  27334. var centerY = projectedPosition.y;
  27335. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27336. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27337. onClick();
  27338. }
  27339. this._drawingContext.beginPath();
  27340. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27341. this._drawingContext.fillStyle = getFillStyle();
  27342. this._drawingContext.globalAlpha = 0.5;
  27343. this._drawingContext.fill();
  27344. this._drawingContext.globalAlpha = 1.0;
  27345. this._drawingContext.strokeStyle = '#FFFFFF';
  27346. this._drawingContext.lineWidth = 1;
  27347. this._drawingContext.stroke();
  27348. this._drawingContext.fillStyle = "#FFFFFF";
  27349. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27350. this._drawingContext.beginPath();
  27351. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27352. this._drawingContext.fill();
  27353. }
  27354. };
  27355. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27356. if (!this._clickPosition) {
  27357. return false;
  27358. }
  27359. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27360. return false;
  27361. }
  27362. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27363. return false;
  27364. }
  27365. return true;
  27366. };
  27367. DebugLayer.prototype.isVisible = function () {
  27368. return this._enabled;
  27369. };
  27370. DebugLayer.prototype.hide = function () {
  27371. if (!this._enabled) {
  27372. return;
  27373. }
  27374. this._enabled = false;
  27375. var engine = this._scene.getEngine();
  27376. this._scene.unregisterBeforeRender(this._syncData);
  27377. this._scene.unregisterAfterRender(this._syncUI);
  27378. document.body.removeChild(this._globalDiv);
  27379. window.removeEventListener("resize", this._syncPositions);
  27380. this._scene.forceShowBoundingBoxes = false;
  27381. this._scene.forceWireframe = false;
  27382. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27383. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27384. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27385. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27386. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27387. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27388. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27389. this._scene.shadowsEnabled = true;
  27390. this._scene.particlesEnabled = true;
  27391. this._scene.postProcessesEnabled = true;
  27392. this._scene.collisionsEnabled = true;
  27393. this._scene.lightsEnabled = true;
  27394. this._scene.texturesEnabled = true;
  27395. this._scene.lensFlaresEnabled = true;
  27396. this._scene.proceduralTexturesEnabled = true;
  27397. this._scene.renderTargetsEnabled = true;
  27398. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27399. };
  27400. DebugLayer.prototype.show = function (showUI, camera) {
  27401. if (showUI === void 0) { showUI = true; }
  27402. if (camera === void 0) { camera = null; }
  27403. if (this._enabled) {
  27404. return;
  27405. }
  27406. if (camera) {
  27407. this._camera = camera;
  27408. }
  27409. else {
  27410. this._camera = this._scene.activeCamera;
  27411. }
  27412. this._enabled = true;
  27413. this._showUI = showUI;
  27414. var engine = this._scene.getEngine();
  27415. this._globalDiv = document.createElement("div");
  27416. document.body.appendChild(this._globalDiv);
  27417. this._generateDOMelements();
  27418. window.addEventListener("resize", this._syncPositions);
  27419. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27420. this._syncPositions();
  27421. this._scene.registerBeforeRender(this._syncData);
  27422. this._scene.registerAfterRender(this._syncUI);
  27423. };
  27424. DebugLayer.prototype._clearLabels = function () {
  27425. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27426. for (var index = 0; index < this._scene.meshes.length; index++) {
  27427. var mesh = this._scene.meshes[index];
  27428. mesh.renderOverlay = false;
  27429. }
  27430. };
  27431. DebugLayer.prototype._generateheader = function (root, text) {
  27432. var header = document.createElement("div");
  27433. header.innerHTML = text + "&nbsp;";
  27434. header.style.textAlign = "right";
  27435. header.style.width = "100%";
  27436. header.style.color = "white";
  27437. header.style.backgroundColor = "Black";
  27438. header.style.padding = "5px 5px 4px 0px";
  27439. header.style.marginLeft = "-5px";
  27440. header.style.fontWeight = "bold";
  27441. root.appendChild(header);
  27442. };
  27443. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27444. var label = document.createElement("label");
  27445. label.innerHTML = title;
  27446. label.style.color = color;
  27447. root.appendChild(label);
  27448. root.appendChild(document.createElement("br"));
  27449. };
  27450. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27451. if (tag === void 0) { tag = null; }
  27452. var label = document.createElement("label");
  27453. var boundingBoxesCheckbox = document.createElement("input");
  27454. boundingBoxesCheckbox.type = "checkbox";
  27455. boundingBoxesCheckbox.checked = initialState;
  27456. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27457. task(evt.target, tag);
  27458. });
  27459. label.appendChild(boundingBoxesCheckbox);
  27460. var container = document.createElement("span");
  27461. var leftPart = document.createElement("span");
  27462. var rightPart = document.createElement("span");
  27463. rightPart.style.cssFloat = "right";
  27464. leftPart.innerHTML = leftTitle;
  27465. rightPart.innerHTML = rightTitle;
  27466. rightPart.style.fontSize = "12px";
  27467. rightPart.style.maxWidth = "200px";
  27468. container.appendChild(leftPart);
  27469. container.appendChild(rightPart);
  27470. label.appendChild(container);
  27471. root.appendChild(label);
  27472. root.appendChild(document.createElement("br"));
  27473. };
  27474. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27475. if (tag === void 0) { tag = null; }
  27476. var label = document.createElement("label");
  27477. var checkBox = document.createElement("input");
  27478. checkBox.type = "checkbox";
  27479. checkBox.checked = initialState;
  27480. checkBox.addEventListener("change", function (evt) {
  27481. task(evt.target, tag);
  27482. });
  27483. label.appendChild(checkBox);
  27484. label.appendChild(document.createTextNode(title));
  27485. root.appendChild(label);
  27486. root.appendChild(document.createElement("br"));
  27487. };
  27488. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27489. if (tag === void 0) { tag = null; }
  27490. var button = document.createElement("button");
  27491. button.innerHTML = title;
  27492. button.style.height = "24px";
  27493. button.style.color = "#444444";
  27494. button.style.border = "1px solid white";
  27495. button.className = "debugLayerButton";
  27496. button.addEventListener("click", function (evt) {
  27497. task(evt.target, tag);
  27498. });
  27499. root.appendChild(button);
  27500. root.appendChild(document.createElement("br"));
  27501. };
  27502. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27503. if (tag === void 0) { tag = null; }
  27504. var label = document.createElement("label");
  27505. var boundingBoxesRadio = document.createElement("input");
  27506. boundingBoxesRadio.type = "radio";
  27507. boundingBoxesRadio.name = name;
  27508. boundingBoxesRadio.checked = initialState;
  27509. boundingBoxesRadio.addEventListener("change", function (evt) {
  27510. task(evt.target, tag);
  27511. });
  27512. label.appendChild(boundingBoxesRadio);
  27513. label.appendChild(document.createTextNode(title));
  27514. root.appendChild(label);
  27515. root.appendChild(document.createElement("br"));
  27516. };
  27517. DebugLayer.prototype._generateDOMelements = function () {
  27518. var _this = this;
  27519. this._globalDiv.id = "DebugLayer";
  27520. this._globalDiv.style.position = "absolute";
  27521. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27522. this._globalDiv.style.fontSize = "14px";
  27523. this._globalDiv.style.color = "white";
  27524. // Drawing canvas
  27525. this._drawingCanvas = document.createElement("canvas");
  27526. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27527. this._drawingCanvas.style.position = "absolute";
  27528. this._drawingCanvas.style.pointerEvents = "none";
  27529. this._drawingContext = this._drawingCanvas.getContext("2d");
  27530. this._globalDiv.appendChild(this._drawingCanvas);
  27531. if (this._showUI) {
  27532. var background = "rgba(128, 128, 128, 0.4)";
  27533. var border = "rgb(180, 180, 180) solid 1px";
  27534. // Stats
  27535. this._statsDiv = document.createElement("div");
  27536. this._statsDiv.id = "DebugLayerStats";
  27537. this._statsDiv.style.border = border;
  27538. this._statsDiv.style.position = "absolute";
  27539. this._statsDiv.style.background = background;
  27540. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27541. this._generateheader(this._statsDiv, "STATISTICS");
  27542. this._statsSubsetDiv = document.createElement("div");
  27543. this._statsSubsetDiv.style.paddingTop = "5px";
  27544. this._statsSubsetDiv.style.paddingBottom = "5px";
  27545. this._statsSubsetDiv.style.overflowY = "auto";
  27546. this._statsDiv.appendChild(this._statsSubsetDiv);
  27547. // Tree
  27548. this._treeDiv = document.createElement("div");
  27549. this._treeDiv.id = "DebugLayerTree";
  27550. this._treeDiv.style.border = border;
  27551. this._treeDiv.style.position = "absolute";
  27552. this._treeDiv.style.background = background;
  27553. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27554. this._treeDiv.style.display = "none";
  27555. this._generateheader(this._treeDiv, "MESHES TREE");
  27556. this._treeSubsetDiv = document.createElement("div");
  27557. this._treeSubsetDiv.style.paddingTop = "5px";
  27558. this._treeSubsetDiv.style.paddingRight = "5px";
  27559. this._treeSubsetDiv.style.overflowY = "auto";
  27560. this._treeSubsetDiv.style.maxHeight = "300px";
  27561. this._treeDiv.appendChild(this._treeSubsetDiv);
  27562. this._needToRefreshMeshesTree = true;
  27563. // Logs
  27564. this._logDiv = document.createElement("div");
  27565. this._logDiv.style.border = border;
  27566. this._logDiv.id = "DebugLayerLogs";
  27567. this._logDiv.style.position = "absolute";
  27568. this._logDiv.style.background = background;
  27569. this._logDiv.style.padding = "0px 0px 0px 5px";
  27570. this._logDiv.style.display = "none";
  27571. this._generateheader(this._logDiv, "LOGS");
  27572. this._logSubsetDiv = document.createElement("div");
  27573. this._logSubsetDiv.style.height = "127px";
  27574. this._logSubsetDiv.style.paddingTop = "5px";
  27575. this._logSubsetDiv.style.overflowY = "auto";
  27576. this._logSubsetDiv.style.fontSize = "12px";
  27577. this._logSubsetDiv.style.fontFamily = "consolas";
  27578. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27579. this._logDiv.appendChild(this._logSubsetDiv);
  27580. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27581. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27582. };
  27583. // Options
  27584. this._optionsDiv = document.createElement("div");
  27585. this._optionsDiv.id = "DebugLayerOptions";
  27586. this._optionsDiv.style.border = border;
  27587. this._optionsDiv.style.position = "absolute";
  27588. this._optionsDiv.style.background = background;
  27589. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27590. this._optionsDiv.style.overflowY = "auto";
  27591. this._generateheader(this._optionsDiv, "OPTIONS");
  27592. this._optionsSubsetDiv = document.createElement("div");
  27593. this._optionsSubsetDiv.style.paddingTop = "5px";
  27594. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27595. this._optionsSubsetDiv.style.overflowY = "auto";
  27596. this._optionsSubsetDiv.style.maxHeight = "200px";
  27597. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27598. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27599. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27600. _this._displayStatistics = element.checked;
  27601. });
  27602. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27603. _this._displayLogs = element.checked;
  27604. });
  27605. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27606. _this._displayTree = element.checked;
  27607. _this._needToRefreshMeshesTree = true;
  27608. });
  27609. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27610. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27611. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27612. _this._scene.forceShowBoundingBoxes = element.checked;
  27613. });
  27614. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27615. _this._labelsEnabled = element.checked;
  27616. if (!_this._labelsEnabled) {
  27617. _this._clearLabels();
  27618. }
  27619. });
  27620. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27621. if (element.checked) {
  27622. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27623. }
  27624. else {
  27625. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27626. }
  27627. });
  27628. ;
  27629. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27630. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27631. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27632. if (element.checked) {
  27633. _this._scene.forceWireframe = false;
  27634. _this._scene.forcePointsCloud = false;
  27635. }
  27636. });
  27637. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27638. if (element.checked) {
  27639. _this._scene.forceWireframe = true;
  27640. _this._scene.forcePointsCloud = false;
  27641. }
  27642. });
  27643. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27644. if (element.checked) {
  27645. _this._scene.forceWireframe = false;
  27646. _this._scene.forcePointsCloud = true;
  27647. }
  27648. });
  27649. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27650. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27651. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27652. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27653. });
  27654. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27655. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27656. });
  27657. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27658. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27659. });
  27660. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27661. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27662. });
  27663. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27664. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27665. });
  27666. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27667. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27668. });
  27669. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27670. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27671. });
  27672. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27673. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27674. });
  27675. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27676. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27677. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27678. _this._scene.animationsEnabled = element.checked;
  27679. });
  27680. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27681. _this._scene.collisionsEnabled = element.checked;
  27682. });
  27683. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27684. _this._scene.fogEnabled = element.checked;
  27685. });
  27686. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27687. _this._scene.lensFlaresEnabled = element.checked;
  27688. });
  27689. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27690. _this._scene.lightsEnabled = element.checked;
  27691. });
  27692. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27693. _this._scene.particlesEnabled = element.checked;
  27694. });
  27695. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27696. _this._scene.postProcessesEnabled = element.checked;
  27697. });
  27698. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27699. _this._scene.proceduralTexturesEnabled = element.checked;
  27700. });
  27701. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27702. _this._scene.renderTargetsEnabled = element.checked;
  27703. });
  27704. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27705. _this._scene.shadowsEnabled = element.checked;
  27706. });
  27707. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27708. _this._scene.skeletonsEnabled = element.checked;
  27709. });
  27710. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27711. _this._scene.spritesEnabled = element.checked;
  27712. });
  27713. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27714. _this._scene.texturesEnabled = element.checked;
  27715. });
  27716. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27717. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27718. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27719. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27720. if (element.checked) {
  27721. _this._scene.headphone = true;
  27722. }
  27723. });
  27724. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27725. if (element.checked) {
  27726. _this._scene.headphone = false;
  27727. }
  27728. });
  27729. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27730. _this._scene.audioEnabled = !element.checked;
  27731. });
  27732. }
  27733. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27734. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27735. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27736. _this._scene.dumpNextRenderTargets = true;
  27737. });
  27738. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27739. this._globalDiv.appendChild(this._statsDiv);
  27740. this._globalDiv.appendChild(this._logDiv);
  27741. this._globalDiv.appendChild(this._optionsDiv);
  27742. this._globalDiv.appendChild(this._treeDiv);
  27743. }
  27744. };
  27745. DebugLayer.prototype._displayStats = function () {
  27746. var scene = this._scene;
  27747. var engine = scene.getEngine();
  27748. var glInfo = engine.getGlInfo();
  27749. 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>";
  27750. if (this.customStatsFunction) {
  27751. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27752. }
  27753. };
  27754. return DebugLayer;
  27755. })();
  27756. BABYLON.DebugLayer = DebugLayer;
  27757. })(BABYLON || (BABYLON = {}));
  27758. //# sourceMappingURL=babylon.debugLayer.js.map
  27759. var BABYLON;
  27760. (function (BABYLON) {
  27761. var RawTexture = (function (_super) {
  27762. __extends(RawTexture, _super);
  27763. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27764. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27765. if (invertY === void 0) { invertY = false; }
  27766. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27767. _super.call(this, null, scene, !generateMipMaps, invertY);
  27768. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27769. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27770. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27771. }
  27772. // Statics
  27773. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27774. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27775. if (invertY === void 0) { invertY = false; }
  27776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27777. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27778. };
  27779. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27780. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27781. if (invertY === void 0) { invertY = false; }
  27782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27783. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27784. };
  27785. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27786. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27787. if (invertY === void 0) { invertY = false; }
  27788. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27789. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27790. };
  27791. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27792. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27793. if (invertY === void 0) { invertY = false; }
  27794. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27795. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27796. };
  27797. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27798. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27799. if (invertY === void 0) { invertY = false; }
  27800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27801. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27802. };
  27803. return RawTexture;
  27804. })(BABYLON.Texture);
  27805. BABYLON.RawTexture = RawTexture;
  27806. })(BABYLON || (BABYLON = {}));
  27807. //# sourceMappingURL=babylon.rawTexture.js.map
  27808. var BABYLON;
  27809. (function (BABYLON) {
  27810. var IndexedVector2 = (function (_super) {
  27811. __extends(IndexedVector2, _super);
  27812. function IndexedVector2(original, index) {
  27813. _super.call(this, original.x, original.y);
  27814. this.index = index;
  27815. }
  27816. return IndexedVector2;
  27817. })(BABYLON.Vector2);
  27818. var PolygonPoints = (function () {
  27819. function PolygonPoints() {
  27820. this.elements = new Array();
  27821. }
  27822. PolygonPoints.prototype.add = function (originalPoints) {
  27823. var _this = this;
  27824. var result = new Array();
  27825. originalPoints.forEach(function (point) {
  27826. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  27827. var newPoint = new IndexedVector2(point, _this.elements.length);
  27828. result.push(newPoint);
  27829. _this.elements.push(newPoint);
  27830. }
  27831. });
  27832. return result;
  27833. };
  27834. PolygonPoints.prototype.computeBounds = function () {
  27835. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27836. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27837. this.elements.forEach(function (point) {
  27838. // x
  27839. if (point.x < lmin.x) {
  27840. lmin.x = point.x;
  27841. }
  27842. else if (point.x > lmax.x) {
  27843. lmax.x = point.x;
  27844. }
  27845. // y
  27846. if (point.y < lmin.y) {
  27847. lmin.y = point.y;
  27848. }
  27849. else if (point.y > lmax.y) {
  27850. lmax.y = point.y;
  27851. }
  27852. });
  27853. return {
  27854. min: lmin,
  27855. max: lmax,
  27856. width: lmax.x - lmin.x,
  27857. height: lmax.y - lmin.y
  27858. };
  27859. };
  27860. return PolygonPoints;
  27861. })();
  27862. var Polygon = (function () {
  27863. function Polygon() {
  27864. }
  27865. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27866. return [
  27867. new BABYLON.Vector2(xmin, ymin),
  27868. new BABYLON.Vector2(xmax, ymin),
  27869. new BABYLON.Vector2(xmax, ymax),
  27870. new BABYLON.Vector2(xmin, ymax)
  27871. ];
  27872. };
  27873. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27874. if (cx === void 0) { cx = 0; }
  27875. if (cy === void 0) { cy = 0; }
  27876. if (numberOfSides === void 0) { numberOfSides = 32; }
  27877. var result = new Array();
  27878. var angle = 0;
  27879. var increment = (Math.PI * 2) / numberOfSides;
  27880. for (var i = 0; i < numberOfSides; i++) {
  27881. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27882. angle -= increment;
  27883. }
  27884. return result;
  27885. };
  27886. Polygon.Parse = function (input) {
  27887. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27888. var i, result = [];
  27889. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27890. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27891. }
  27892. return result;
  27893. };
  27894. Polygon.StartingAt = function (x, y) {
  27895. return BABYLON.Path2.StartingAt(x, y);
  27896. };
  27897. return Polygon;
  27898. })();
  27899. BABYLON.Polygon = Polygon;
  27900. var PolygonMeshBuilder = (function () {
  27901. function PolygonMeshBuilder(name, contours, scene) {
  27902. this._points = new PolygonPoints();
  27903. if (!("poly2tri" in window)) {
  27904. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27905. }
  27906. this._name = name;
  27907. this._scene = scene;
  27908. var points;
  27909. if (contours instanceof BABYLON.Path2) {
  27910. points = contours.getPoints();
  27911. }
  27912. else {
  27913. points = contours;
  27914. }
  27915. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27916. }
  27917. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27918. this._swctx.addHole(this._points.add(hole));
  27919. return this;
  27920. };
  27921. PolygonMeshBuilder.prototype.build = function (updatable) {
  27922. if (updatable === void 0) { updatable = false; }
  27923. var result = new BABYLON.Mesh(this._name, this._scene);
  27924. var normals = [];
  27925. var positions = [];
  27926. var uvs = [];
  27927. var bounds = this._points.computeBounds();
  27928. this._points.elements.forEach(function (p) {
  27929. normals.push(0, 1.0, 0);
  27930. positions.push(p.x, 0, p.y);
  27931. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27932. });
  27933. var indices = [];
  27934. this._swctx.triangulate();
  27935. this._swctx.getTriangles().forEach(function (triangle) {
  27936. triangle.getPoints().forEach(function (point) {
  27937. indices.push(point.index);
  27938. });
  27939. });
  27940. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27941. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27942. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27943. result.setIndices(indices);
  27944. return result;
  27945. };
  27946. return PolygonMeshBuilder;
  27947. })();
  27948. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27949. })(BABYLON || (BABYLON = {}));
  27950. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27951. (function (BABYLON) {
  27952. var SimplificationSettings = (function () {
  27953. function SimplificationSettings(quality, distance) {
  27954. this.quality = quality;
  27955. this.distance = distance;
  27956. }
  27957. return SimplificationSettings;
  27958. })();
  27959. BABYLON.SimplificationSettings = SimplificationSettings;
  27960. var SimplificationQueue = (function () {
  27961. function SimplificationQueue() {
  27962. this.running = false;
  27963. this._simplificationArray = [];
  27964. }
  27965. SimplificationQueue.prototype.addTask = function (task) {
  27966. this._simplificationArray.push(task);
  27967. };
  27968. SimplificationQueue.prototype.executeNext = function () {
  27969. var task = this._simplificationArray.pop();
  27970. if (task) {
  27971. this.running = true;
  27972. this.runSimplification(task);
  27973. }
  27974. else {
  27975. this.running = false;
  27976. }
  27977. };
  27978. SimplificationQueue.prototype.runSimplification = function (task) {
  27979. var _this = this;
  27980. if (task.parallelProcessing) {
  27981. //parallel simplifier
  27982. task.settings.forEach(function (setting) {
  27983. var simplifier = _this.getSimplifier(task);
  27984. simplifier.simplify(setting, function (newMesh) {
  27985. task.mesh.addLODLevel(setting.distance, newMesh);
  27986. newMesh.isVisible = true;
  27987. //check if it is the last
  27988. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  27989. //all done, run the success callback.
  27990. task.successCallback();
  27991. }
  27992. _this.executeNext();
  27993. });
  27994. });
  27995. }
  27996. else {
  27997. //single simplifier.
  27998. var simplifier = this.getSimplifier(task);
  27999. var runDecimation = function (setting, callback) {
  28000. simplifier.simplify(setting, function (newMesh) {
  28001. task.mesh.addLODLevel(setting.distance, newMesh);
  28002. newMesh.isVisible = true;
  28003. //run the next quality level
  28004. callback();
  28005. });
  28006. };
  28007. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28008. runDecimation(task.settings[loop.index], function () {
  28009. loop.executeNext();
  28010. });
  28011. }, function () {
  28012. //execution ended, run the success callback.
  28013. if (task.successCallback) {
  28014. task.successCallback();
  28015. }
  28016. _this.executeNext();
  28017. });
  28018. }
  28019. };
  28020. SimplificationQueue.prototype.getSimplifier = function (task) {
  28021. switch (task.simplificationType) {
  28022. case 0 /* QUADRATIC */:
  28023. default:
  28024. return new QuadraticErrorSimplification(task.mesh);
  28025. }
  28026. };
  28027. return SimplificationQueue;
  28028. })();
  28029. BABYLON.SimplificationQueue = SimplificationQueue;
  28030. /**
  28031. * The implemented types of simplification.
  28032. * At the moment only Quadratic Error Decimation is implemented.
  28033. */
  28034. (function (SimplificationType) {
  28035. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28036. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28037. var SimplificationType = BABYLON.SimplificationType;
  28038. var DecimationTriangle = (function () {
  28039. function DecimationTriangle(vertices) {
  28040. this.vertices = vertices;
  28041. this.error = new Array(4);
  28042. this.deleted = false;
  28043. this.isDirty = false;
  28044. this.deletePending = false;
  28045. this.borderFactor = 0;
  28046. }
  28047. return DecimationTriangle;
  28048. })();
  28049. BABYLON.DecimationTriangle = DecimationTriangle;
  28050. var DecimationVertex = (function () {
  28051. function DecimationVertex(position, normal, uv, id) {
  28052. this.position = position;
  28053. this.normal = normal;
  28054. this.uv = uv;
  28055. this.id = id;
  28056. this.isBorder = true;
  28057. this.q = new QuadraticMatrix();
  28058. this.triangleCount = 0;
  28059. this.triangleStart = 0;
  28060. }
  28061. return DecimationVertex;
  28062. })();
  28063. BABYLON.DecimationVertex = DecimationVertex;
  28064. var QuadraticMatrix = (function () {
  28065. function QuadraticMatrix(data) {
  28066. this.data = new Array(10);
  28067. for (var i = 0; i < 10; ++i) {
  28068. if (data && data[i]) {
  28069. this.data[i] = data[i];
  28070. }
  28071. else {
  28072. this.data[i] = 0;
  28073. }
  28074. }
  28075. }
  28076. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28077. 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];
  28078. return det;
  28079. };
  28080. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28081. for (var i = 0; i < 10; ++i) {
  28082. this.data[i] += matrix.data[i];
  28083. }
  28084. };
  28085. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28086. for (var i = 0; i < 10; ++i) {
  28087. this.data[i] += data[i];
  28088. }
  28089. };
  28090. QuadraticMatrix.prototype.add = function (matrix) {
  28091. var m = new QuadraticMatrix();
  28092. for (var i = 0; i < 10; ++i) {
  28093. m.data[i] = this.data[i] + matrix.data[i];
  28094. }
  28095. return m;
  28096. };
  28097. QuadraticMatrix.FromData = function (a, b, c, d) {
  28098. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28099. };
  28100. //returning an array to avoid garbage collection
  28101. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28102. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28103. };
  28104. return QuadraticMatrix;
  28105. })();
  28106. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28107. var Reference = (function () {
  28108. function Reference(vertexId, triangleId) {
  28109. this.vertexId = vertexId;
  28110. this.triangleId = triangleId;
  28111. }
  28112. return Reference;
  28113. })();
  28114. BABYLON.Reference = Reference;
  28115. /**
  28116. * An implementation of the Quadratic Error simplification algorithm.
  28117. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28118. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28119. * @author RaananW
  28120. */
  28121. var QuadraticErrorSimplification = (function () {
  28122. function QuadraticErrorSimplification(_mesh) {
  28123. this._mesh = _mesh;
  28124. this.initialised = false;
  28125. this.syncIterations = 5000;
  28126. this.aggressiveness = 7;
  28127. this.decimationIterations = 100;
  28128. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28129. }
  28130. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28131. var _this = this;
  28132. this.initDecimatedMesh();
  28133. //iterating through the submeshes array, one after the other.
  28134. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28135. _this.initWithMesh(_this._mesh, loop.index, function () {
  28136. _this.runDecimation(settings, loop.index, function () {
  28137. loop.executeNext();
  28138. });
  28139. });
  28140. }, function () {
  28141. setTimeout(function () {
  28142. successCallback(_this._reconstructedMesh);
  28143. }, 0);
  28144. });
  28145. };
  28146. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28147. var _this = this;
  28148. var gCount = 0;
  28149. triangle.vertices.forEach(function (vId) {
  28150. var count = 0;
  28151. var vPos = _this.vertices[vId].position;
  28152. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28153. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28154. ++count;
  28155. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28156. ++count;
  28157. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28158. ++count;
  28159. if (count > 1) {
  28160. ++gCount;
  28161. }
  28162. ;
  28163. });
  28164. if (gCount > 1) {
  28165. console.log(triangle, gCount);
  28166. }
  28167. return gCount > 1;
  28168. };
  28169. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28170. var _this = this;
  28171. var targetCount = ~~(this.triangles.length * settings.quality);
  28172. var deletedTriangles = 0;
  28173. var triangleCount = this.triangles.length;
  28174. var iterationFunction = function (iteration, callback) {
  28175. setTimeout(function () {
  28176. if (iteration % 5 === 0) {
  28177. _this.updateMesh(iteration === 0);
  28178. }
  28179. for (var i = 0; i < _this.triangles.length; ++i) {
  28180. _this.triangles[i].isDirty = false;
  28181. }
  28182. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28183. var trianglesIterator = function (i) {
  28184. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28185. var t = _this.triangles[tIdx];
  28186. if (!t)
  28187. return;
  28188. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28189. return;
  28190. }
  28191. for (var j = 0; j < 3; ++j) {
  28192. if (t.error[j] < threshold) {
  28193. var deleted0 = [];
  28194. var deleted1 = [];
  28195. var i0 = t.vertices[j];
  28196. var i1 = t.vertices[(j + 1) % 3];
  28197. var v0 = _this.vertices[i0];
  28198. var v1 = _this.vertices[i1];
  28199. if (v0.isBorder !== v1.isBorder)
  28200. continue;
  28201. var p = BABYLON.Vector3.Zero();
  28202. var n = BABYLON.Vector3.Zero();
  28203. var uv = BABYLON.Vector2.Zero();
  28204. var color = new BABYLON.Color4(0, 0, 0, 1);
  28205. _this.calculateError(v0, v1, p, n, uv, color);
  28206. var delTr = [];
  28207. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  28208. continue;
  28209. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  28210. continue;
  28211. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28212. continue;
  28213. var uniqueArray = [];
  28214. delTr.forEach(function (deletedT) {
  28215. if (uniqueArray.indexOf(deletedT) === -1) {
  28216. deletedT.deletePending = true;
  28217. uniqueArray.push(deletedT);
  28218. }
  28219. });
  28220. if (uniqueArray.length % 2 != 0) {
  28221. continue;
  28222. }
  28223. v0.normal = n;
  28224. if (v0.uv)
  28225. v0.uv = uv;
  28226. else if (v0.color)
  28227. v0.color = color;
  28228. v0.q = v1.q.add(v0.q);
  28229. v0.position = p;
  28230. var tStart = _this.references.length;
  28231. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  28232. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  28233. var tCount = _this.references.length - tStart;
  28234. if (tCount <= v0.triangleCount) {
  28235. if (tCount) {
  28236. for (var c = 0; c < tCount; c++) {
  28237. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28238. }
  28239. }
  28240. }
  28241. else {
  28242. v0.triangleStart = tStart;
  28243. }
  28244. v0.triangleCount = tCount;
  28245. break;
  28246. }
  28247. }
  28248. };
  28249. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28250. return (triangleCount - deletedTriangles <= targetCount);
  28251. });
  28252. }, 0);
  28253. };
  28254. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28255. if (triangleCount - deletedTriangles <= targetCount)
  28256. loop.breakLoop();
  28257. else {
  28258. iterationFunction(loop.index, function () {
  28259. loop.executeNext();
  28260. });
  28261. }
  28262. }, function () {
  28263. setTimeout(function () {
  28264. //reconstruct this part of the mesh
  28265. _this.reconstructMesh(submeshIndex);
  28266. successCallback();
  28267. }, 0);
  28268. });
  28269. };
  28270. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  28271. var _this = this;
  28272. if (!mesh)
  28273. return;
  28274. this.vertices = [];
  28275. this.triangles = [];
  28276. this._mesh = mesh;
  28277. //It is assumed that a mesh has positions, normals and either uvs or colors.
  28278. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28279. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28280. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28281. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28282. var indices = mesh.getIndices();
  28283. var submesh = mesh.subMeshes[submeshIndex];
  28284. var vertexInit = function (i) {
  28285. var offset = i + submesh.verticesStart;
  28286. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  28287. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28288. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  28289. }
  28290. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28291. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  28292. }
  28293. _this.vertices.push(vertex);
  28294. };
  28295. //var totalVertices = mesh.getTotalVertices();
  28296. var totalVertices = submesh.verticesCount;
  28297. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  28298. var indicesInit = function (i) {
  28299. var offset = (submesh.indexStart / 3) + i;
  28300. var pos = (offset * 3);
  28301. var i0 = indices[pos + 0] - submesh.verticesStart;
  28302. var i1 = indices[pos + 1] - submesh.verticesStart;
  28303. var i2 = indices[pos + 2] - submesh.verticesStart;
  28304. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  28305. _this.triangles.push(triangle);
  28306. };
  28307. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28308. _this.init(callback);
  28309. });
  28310. });
  28311. };
  28312. QuadraticErrorSimplification.prototype.init = function (callback) {
  28313. var _this = this;
  28314. var triangleInit1 = function (i) {
  28315. var t = _this.triangles[i];
  28316. 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();
  28317. for (var j = 0; j < 3; j++) {
  28318. _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))));
  28319. }
  28320. };
  28321. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28322. var triangleInit2 = function (i) {
  28323. var t = _this.triangles[i];
  28324. for (var j = 0; j < 3; ++j) {
  28325. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  28326. }
  28327. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28328. };
  28329. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28330. _this.initialised = true;
  28331. callback();
  28332. });
  28333. });
  28334. };
  28335. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28336. var newTriangles = [];
  28337. var i;
  28338. for (i = 0; i < this.vertices.length; ++i) {
  28339. this.vertices[i].triangleCount = 0;
  28340. }
  28341. var t;
  28342. var j;
  28343. for (i = 0; i < this.triangles.length; ++i) {
  28344. if (!this.triangles[i].deleted) {
  28345. t = this.triangles[i];
  28346. for (j = 0; j < 3; ++j) {
  28347. this.vertices[t.vertices[j]].triangleCount = 1;
  28348. }
  28349. newTriangles.push(t);
  28350. }
  28351. }
  28352. var newVerticesOrder = [];
  28353. //compact vertices, get the IDs of the vertices used.
  28354. var dst = 0;
  28355. for (i = 0; i < this.vertices.length; ++i) {
  28356. if (this.vertices[i].triangleCount) {
  28357. this.vertices[i].triangleStart = dst;
  28358. this.vertices[dst].position = this.vertices[i].position;
  28359. this.vertices[dst].normal = this.vertices[i].normal;
  28360. this.vertices[dst].uv = this.vertices[i].uv;
  28361. this.vertices[dst].color = this.vertices[i].color;
  28362. newVerticesOrder.push(dst);
  28363. dst++;
  28364. }
  28365. }
  28366. for (i = 0; i < newTriangles.length; ++i) {
  28367. t = newTriangles[i];
  28368. for (j = 0; j < 3; ++j) {
  28369. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  28370. }
  28371. }
  28372. this.vertices = this.vertices.slice(0, dst);
  28373. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28374. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28375. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28376. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28377. for (i = 0; i < newVerticesOrder.length; ++i) {
  28378. newPositionData.push(this.vertices[i].position.x);
  28379. newPositionData.push(this.vertices[i].position.y);
  28380. newPositionData.push(this.vertices[i].position.z);
  28381. newNormalData.push(this.vertices[i].normal.x);
  28382. newNormalData.push(this.vertices[i].normal.y);
  28383. newNormalData.push(this.vertices[i].normal.z);
  28384. if (this.vertices[i].uv) {
  28385. newUVsData.push(this.vertices[i].uv.x);
  28386. newUVsData.push(this.vertices[i].uv.y);
  28387. }
  28388. else if (this.vertices[i].color) {
  28389. newColorsData.push(this.vertices[i].color.r);
  28390. newColorsData.push(this.vertices[i].color.g);
  28391. newColorsData.push(this.vertices[i].color.b);
  28392. newColorsData.push(this.vertices[i].color.a);
  28393. }
  28394. }
  28395. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28396. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28397. var submeshesArray = this._reconstructedMesh.subMeshes;
  28398. this._reconstructedMesh.subMeshes = [];
  28399. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28400. for (i = 0; i < newTriangles.length; ++i) {
  28401. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  28402. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  28403. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  28404. }
  28405. //overwriting the old vertex buffers and indices.
  28406. this._reconstructedMesh.setIndices(newIndicesArray);
  28407. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28408. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28409. if (newUVsData.length > 0)
  28410. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28411. if (newColorsData.length > 0)
  28412. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28413. //create submesh
  28414. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28415. if (submeshIndex > 0) {
  28416. this._reconstructedMesh.subMeshes = [];
  28417. submeshesArray.forEach(function (submesh) {
  28418. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28419. });
  28420. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28421. }
  28422. };
  28423. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28424. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28425. this._reconstructedMesh.material = this._mesh.material;
  28426. this._reconstructedMesh.parent = this._mesh.parent;
  28427. this._reconstructedMesh.isVisible = false;
  28428. };
  28429. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  28430. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28431. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28432. if (t.deleted)
  28433. continue;
  28434. var s = this.references[vertex1.triangleStart + i].vertexId;
  28435. var id1 = t.vertices[(s + 1) % 3];
  28436. var id2 = t.vertices[(s + 2) % 3];
  28437. if ((id1 === index2 || id2 === index2)) {
  28438. deletedArray[i] = true;
  28439. delTr.push(t);
  28440. continue;
  28441. }
  28442. var d1 = this.vertices[id1].position.subtract(point);
  28443. d1 = d1.normalize();
  28444. var d2 = this.vertices[id2].position.subtract(point);
  28445. d2 = d2.normalize();
  28446. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28447. return true;
  28448. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28449. deletedArray[i] = false;
  28450. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28451. return true;
  28452. }
  28453. return false;
  28454. };
  28455. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  28456. var newDeleted = deletedTriangles;
  28457. for (var i = 0; i < vertex.triangleCount; ++i) {
  28458. var ref = this.references[vertex.triangleStart + i];
  28459. var t = this.triangles[ref.triangleId];
  28460. if (t.deleted)
  28461. continue;
  28462. if (deletedArray[i] && t.deletePending) {
  28463. t.deleted = true;
  28464. newDeleted++;
  28465. continue;
  28466. }
  28467. t.vertices[ref.vertexId] = vertexId;
  28468. t.isDirty = true;
  28469. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  28470. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  28471. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  28472. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28473. this.references.push(ref);
  28474. }
  28475. return newDeleted;
  28476. };
  28477. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28478. for (var i = 0; i < this.vertices.length; ++i) {
  28479. var vCount = [];
  28480. var vId = [];
  28481. var v = this.vertices[i];
  28482. var j;
  28483. for (j = 0; j < v.triangleCount; ++j) {
  28484. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28485. for (var ii = 0; ii < 3; ii++) {
  28486. var ofs = 0;
  28487. var id = triangle.vertices[ii];
  28488. while (ofs < vCount.length) {
  28489. if (vId[ofs] === id)
  28490. break;
  28491. ++ofs;
  28492. }
  28493. if (ofs === vCount.length) {
  28494. vCount.push(1);
  28495. vId.push(id);
  28496. }
  28497. else {
  28498. vCount[ofs]++;
  28499. }
  28500. }
  28501. }
  28502. for (j = 0; j < vCount.length; ++j) {
  28503. if (vCount[j] === 1) {
  28504. this.vertices[vId[j]].isBorder = true;
  28505. }
  28506. else {
  28507. this.vertices[vId[j]].isBorder = false;
  28508. }
  28509. }
  28510. }
  28511. };
  28512. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28513. if (identifyBorders === void 0) { identifyBorders = false; }
  28514. var i;
  28515. if (!identifyBorders) {
  28516. var newTrianglesVector = [];
  28517. for (i = 0; i < this.triangles.length; ++i) {
  28518. if (!this.triangles[i].deleted) {
  28519. newTrianglesVector.push(this.triangles[i]);
  28520. }
  28521. }
  28522. this.triangles = newTrianglesVector;
  28523. }
  28524. for (i = 0; i < this.vertices.length; ++i) {
  28525. this.vertices[i].triangleCount = 0;
  28526. this.vertices[i].triangleStart = 0;
  28527. }
  28528. var t;
  28529. var j;
  28530. var v;
  28531. for (i = 0; i < this.triangles.length; ++i) {
  28532. t = this.triangles[i];
  28533. for (j = 0; j < 3; ++j) {
  28534. v = this.vertices[t.vertices[j]];
  28535. v.triangleCount++;
  28536. }
  28537. }
  28538. var tStart = 0;
  28539. for (i = 0; i < this.vertices.length; ++i) {
  28540. this.vertices[i].triangleStart = tStart;
  28541. tStart += this.vertices[i].triangleCount;
  28542. this.vertices[i].triangleCount = 0;
  28543. }
  28544. var newReferences = new Array(this.triangles.length * 3);
  28545. for (i = 0; i < this.triangles.length; ++i) {
  28546. t = this.triangles[i];
  28547. for (j = 0; j < 3; ++j) {
  28548. v = this.vertices[t.vertices[j]];
  28549. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28550. v.triangleCount++;
  28551. }
  28552. }
  28553. this.references = newReferences;
  28554. if (identifyBorders) {
  28555. this.identifyBorder();
  28556. }
  28557. };
  28558. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28559. var x = point.x;
  28560. var y = point.y;
  28561. var z = point.z;
  28562. 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];
  28563. };
  28564. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28565. var q = vertex1.q.add(vertex2.q);
  28566. var border = vertex1.isBorder && vertex2.isBorder;
  28567. var error = 0;
  28568. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28569. if (qDet !== 0 && !border) {
  28570. if (!pointResult) {
  28571. pointResult = BABYLON.Vector3.Zero();
  28572. }
  28573. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28574. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28575. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28576. error = this.vertexError(q, pointResult);
  28577. //TODO this should be correctly calculated
  28578. if (normalResult) {
  28579. normalResult.copyFrom(vertex1.normal);
  28580. if (vertex1.uv)
  28581. uvResult.copyFrom(vertex1.uv);
  28582. else if (vertex1.color)
  28583. colorResult.copyFrom(vertex1.color);
  28584. }
  28585. }
  28586. else {
  28587. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28588. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28589. var error1 = this.vertexError(q, vertex1.position);
  28590. var error2 = this.vertexError(q, vertex2.position);
  28591. var error3 = this.vertexError(q, p3);
  28592. error = Math.min(error1, error2, error3);
  28593. if (error === error1) {
  28594. if (pointResult) {
  28595. pointResult.copyFrom(vertex1.position);
  28596. normalResult.copyFrom(vertex1.normal);
  28597. if (vertex1.uv)
  28598. uvResult.copyFrom(vertex1.uv);
  28599. else if (vertex1.color)
  28600. colorResult.copyFrom(vertex1.color);
  28601. }
  28602. }
  28603. else if (error === error2) {
  28604. if (pointResult) {
  28605. pointResult.copyFrom(vertex2.position);
  28606. normalResult.copyFrom(vertex2.normal);
  28607. if (vertex2.uv)
  28608. uvResult.copyFrom(vertex2.uv);
  28609. else if (vertex2.color)
  28610. colorResult.copyFrom(vertex2.color);
  28611. }
  28612. }
  28613. else {
  28614. if (pointResult) {
  28615. pointResult.copyFrom(p3);
  28616. normalResult.copyFrom(vertex1.normal);
  28617. if (vertex1.uv)
  28618. uvResult.copyFrom(vertex1.uv);
  28619. else if (vertex1.color)
  28620. colorResult.copyFrom(vertex1.color);
  28621. }
  28622. }
  28623. }
  28624. return error;
  28625. };
  28626. return QuadraticErrorSimplification;
  28627. })();
  28628. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28629. })(BABYLON || (BABYLON = {}));
  28630. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28631. (function (BABYLON) {
  28632. var Analyser = (function () {
  28633. function Analyser(scene) {
  28634. this.SMOOTHING = 0.75;
  28635. this.FFT_SIZE = 512;
  28636. this.BARGRAPHAMPLITUDE = 256;
  28637. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28638. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28639. this._scene = scene;
  28640. this._audioEngine = BABYLON.Engine.audioEngine;
  28641. if (this._audioEngine.canUseWebAudio) {
  28642. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28643. this._webAudioAnalyser.minDecibels = -140;
  28644. this._webAudioAnalyser.maxDecibels = 0;
  28645. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28646. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28647. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28648. }
  28649. }
  28650. Analyser.prototype.getFrequencyBinCount = function () {
  28651. if (this._audioEngine.canUseWebAudio) {
  28652. return this._webAudioAnalyser.frequencyBinCount;
  28653. }
  28654. else {
  28655. return 0;
  28656. }
  28657. };
  28658. Analyser.prototype.getByteFrequencyData = function () {
  28659. if (this._audioEngine.canUseWebAudio) {
  28660. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28661. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28662. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28663. }
  28664. return this._byteFreqs;
  28665. };
  28666. Analyser.prototype.getByteTimeDomainData = function () {
  28667. if (this._audioEngine.canUseWebAudio) {
  28668. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28669. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28670. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28671. }
  28672. return this._byteTime;
  28673. };
  28674. Analyser.prototype.getFloatFrequencyData = function () {
  28675. if (this._audioEngine.canUseWebAudio) {
  28676. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28677. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28678. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28679. }
  28680. return this._floatFreqs;
  28681. };
  28682. Analyser.prototype.drawDebugCanvas = function () {
  28683. var _this = this;
  28684. if (this._audioEngine.canUseWebAudio) {
  28685. if (!this._debugCanvas) {
  28686. this._debugCanvas = document.createElement("canvas");
  28687. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28688. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28689. this._debugCanvas.style.position = "absolute";
  28690. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28691. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28692. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28693. document.body.appendChild(this._debugCanvas);
  28694. this._registerFunc = function () {
  28695. _this.drawDebugCanvas();
  28696. };
  28697. this._scene.registerBeforeRender(this._registerFunc);
  28698. }
  28699. if (this._registerFunc) {
  28700. var workingArray = this.getByteFrequencyData();
  28701. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28702. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28703. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28704. var value = workingArray[i];
  28705. var percent = value / this.BARGRAPHAMPLITUDE;
  28706. var height = this.DEBUGCANVASSIZE.height * percent;
  28707. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28708. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28709. var hue = i / this.getFrequencyBinCount() * 360;
  28710. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28711. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28712. }
  28713. }
  28714. }
  28715. };
  28716. Analyser.prototype.stopDebugCanvas = function () {
  28717. if (this._debugCanvas) {
  28718. this._scene.unregisterBeforeRender(this._registerFunc);
  28719. this._registerFunc = null;
  28720. document.body.removeChild(this._debugCanvas);
  28721. this._debugCanvas = null;
  28722. this._debugCanvasContext = null;
  28723. }
  28724. };
  28725. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28726. if (this._audioEngine.canUseWebAudio) {
  28727. inputAudioNode.connect(this._webAudioAnalyser);
  28728. this._webAudioAnalyser.connect(outputAudioNode);
  28729. }
  28730. };
  28731. Analyser.prototype.dispose = function () {
  28732. if (this._audioEngine.canUseWebAudio) {
  28733. this._webAudioAnalyser.disconnect();
  28734. }
  28735. };
  28736. return Analyser;
  28737. })();
  28738. BABYLON.Analyser = Analyser;
  28739. })(BABYLON || (BABYLON = {}));
  28740. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28741. (function (BABYLON) {
  28742. var DepthRenderer = (function () {
  28743. function DepthRenderer(scene, type) {
  28744. var _this = this;
  28745. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28746. this._viewMatrix = BABYLON.Matrix.Zero();
  28747. this._projectionMatrix = BABYLON.Matrix.Zero();
  28748. this._transformMatrix = BABYLON.Matrix.Zero();
  28749. this._worldViewProjection = BABYLON.Matrix.Zero();
  28750. this._scene = scene;
  28751. var engine = scene.getEngine();
  28752. // Render target
  28753. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28754. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28755. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28756. this._depthMap.refreshRate = 1;
  28757. this._depthMap.renderParticles = false;
  28758. this._depthMap.renderList = null;
  28759. // Custom render function
  28760. var renderSubMesh = function (subMesh) {
  28761. var mesh = subMesh.getRenderingMesh();
  28762. var scene = _this._scene;
  28763. var engine = scene.getEngine();
  28764. // Culling
  28765. engine.setState(subMesh.getMaterial().backFaceCulling);
  28766. // Managing instances
  28767. var batch = mesh._getInstancesRenderList(subMesh._id);
  28768. if (batch.mustReturn) {
  28769. return;
  28770. }
  28771. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28772. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28773. engine.enableEffect(_this._effect);
  28774. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28775. var material = subMesh.getMaterial();
  28776. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28777. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28778. // Alpha test
  28779. if (material && material.needAlphaTesting()) {
  28780. var alphaTexture = material.getAlphaTestTexture();
  28781. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28782. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28783. }
  28784. // Bones
  28785. if (mesh.useBones) {
  28786. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28787. }
  28788. // Draw
  28789. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28790. }
  28791. };
  28792. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28793. var index;
  28794. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28795. renderSubMesh(opaqueSubMeshes.data[index]);
  28796. }
  28797. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28798. renderSubMesh(alphaTestSubMeshes.data[index]);
  28799. }
  28800. };
  28801. }
  28802. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  28803. var defines = [];
  28804. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28805. var mesh = subMesh.getMesh();
  28806. var scene = mesh.getScene();
  28807. var material = subMesh.getMaterial();
  28808. // Alpha test
  28809. if (material && material.needAlphaTesting()) {
  28810. defines.push("#define ALPHATEST");
  28811. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28812. attribs.push(BABYLON.VertexBuffer.UVKind);
  28813. defines.push("#define UV1");
  28814. }
  28815. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28816. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28817. defines.push("#define UV2");
  28818. }
  28819. }
  28820. // Bones
  28821. if (mesh.useBones) {
  28822. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28823. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28824. defines.push("#define BONES");
  28825. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28826. }
  28827. // Instances
  28828. if (useInstances) {
  28829. defines.push("#define INSTANCES");
  28830. attribs.push("world0");
  28831. attribs.push("world1");
  28832. attribs.push("world2");
  28833. attribs.push("world3");
  28834. }
  28835. // Get correct effect
  28836. var join = defines.join("\n");
  28837. if (this._cachedDefines !== join) {
  28838. this._cachedDefines = join;
  28839. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  28840. }
  28841. return this._effect.isReady();
  28842. };
  28843. DepthRenderer.prototype.getDepthMap = function () {
  28844. return this._depthMap;
  28845. };
  28846. // Methods
  28847. DepthRenderer.prototype.dispose = function () {
  28848. this._depthMap.dispose();
  28849. };
  28850. return DepthRenderer;
  28851. })();
  28852. BABYLON.DepthRenderer = DepthRenderer;
  28853. })(BABYLON || (BABYLON = {}));
  28854. //# sourceMappingURL=babylon.depthRenderer.js.map
  28855. var BABYLON;
  28856. (function (BABYLON) {
  28857. var SSAORenderingPipeline = (function (_super) {
  28858. __extends(SSAORenderingPipeline, _super);
  28859. /**
  28860. * @constructor
  28861. * @param {string} name - The rendering pipeline name
  28862. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28863. * @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)
  28864. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28865. */
  28866. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  28867. var _this = this;
  28868. _super.call(this, scene.getEngine(), name);
  28869. // Members
  28870. /**
  28871. * The PassPostProcess id in the pipeline that contains the original scene color
  28872. * @type {string}
  28873. */
  28874. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  28875. /**
  28876. * The SSAO PostProcess id in the pipeline
  28877. * @type {string}
  28878. */
  28879. this.SSAORenderEffect = "SSAORenderEffect";
  28880. /**
  28881. * The horizontal blur PostProcess id in the pipeline
  28882. * @type {string}
  28883. */
  28884. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  28885. /**
  28886. * The vertical blur PostProcess id in the pipeline
  28887. * @type {string}
  28888. */
  28889. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  28890. /**
  28891. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  28892. * @type {string}
  28893. */
  28894. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  28895. this._firstUpdate = true;
  28896. this._scene = scene;
  28897. // Set up assets
  28898. this._createRandomTexture();
  28899. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28900. var ssaoRatio = ratio.ssaoRatio || ratio;
  28901. var combineRatio = ratio.combineRatio || ratio;
  28902. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28903. this._createSSAOPostProcess(ssaoRatio);
  28904. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28905. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28906. this._createSSAOCombinePostProcess(combineRatio);
  28907. // Set up pipeline
  28908. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  28909. return _this._originalColorPostProcess;
  28910. }, true));
  28911. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  28912. return _this._ssaoPostProcess;
  28913. }, true));
  28914. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  28915. return _this._blurHPostProcess;
  28916. }, true));
  28917. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  28918. return _this._blurVPostProcess;
  28919. }, true));
  28920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  28921. return _this._ssaoCombinePostProcess;
  28922. }, true));
  28923. // Finish
  28924. scene.postProcessRenderPipelineManager.addPipeline(this);
  28925. if (cameras)
  28926. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28927. }
  28928. // Public Methods
  28929. /**
  28930. * Returns the horizontal blur PostProcess
  28931. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  28932. */
  28933. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  28934. return this._blurHPostProcess;
  28935. };
  28936. /**
  28937. * Returns the vertical blur PostProcess
  28938. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  28939. */
  28940. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  28941. return this._blurVPostProcess;
  28942. };
  28943. /**
  28944. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  28945. */
  28946. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28947. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28948. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28949. this._originalColorPostProcess = undefined;
  28950. this._ssaoPostProcess = undefined;
  28951. this._blurHPostProcess = undefined;
  28952. this._blurVPostProcess = undefined;
  28953. this._ssaoCombinePostProcess = undefined;
  28954. this._randomTexture.dispose();
  28955. if (disableDepthRender)
  28956. this._scene.disableDepthRenderer();
  28957. };
  28958. // Private Methods
  28959. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28960. var _this = this;
  28961. var sampleSphere = [
  28962. 0.5381,
  28963. 0.1856,
  28964. -0.4319,
  28965. 0.1379,
  28966. 0.2486,
  28967. 0.4430,
  28968. 0.3371,
  28969. 0.5679,
  28970. -0.0057,
  28971. -0.6999,
  28972. -0.0451,
  28973. -0.0019,
  28974. 0.0689,
  28975. -0.1598,
  28976. -0.8547,
  28977. 0.0560,
  28978. 0.0069,
  28979. -0.1843,
  28980. -0.0146,
  28981. 0.1402,
  28982. 0.0762,
  28983. 0.0100,
  28984. -0.1924,
  28985. -0.0344,
  28986. -0.3577,
  28987. -0.5301,
  28988. -0.4358,
  28989. -0.3169,
  28990. 0.1063,
  28991. 0.0158,
  28992. 0.0103,
  28993. -0.5869,
  28994. 0.0046,
  28995. -0.0897,
  28996. -0.4940,
  28997. 0.3287,
  28998. 0.7119,
  28999. -0.0154,
  29000. -0.0918,
  29001. -0.0533,
  29002. 0.0596,
  29003. -0.5411,
  29004. 0.0352,
  29005. -0.0631,
  29006. 0.5460,
  29007. -0.4776,
  29008. 0.2847,
  29009. -0.0271
  29010. ];
  29011. var samplesFactor = 1.0 / 16.0;
  29012. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29013. this._ssaoPostProcess.onApply = function (effect) {
  29014. if (_this._firstUpdate) {
  29015. effect.setArray3("sampleSphere", sampleSphere);
  29016. effect.setFloat("samplesFactor", samplesFactor);
  29017. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29018. _this._firstUpdate = false;
  29019. }
  29020. effect.setTexture("textureSampler", _this._depthTexture);
  29021. effect.setTexture("randomSampler", _this._randomTexture);
  29022. };
  29023. };
  29024. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29025. var _this = this;
  29026. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29027. this._ssaoCombinePostProcess.onApply = function (effect) {
  29028. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29029. };
  29030. };
  29031. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29032. var size = 512;
  29033. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29034. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29035. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29036. var context = this._randomTexture.getContext();
  29037. var rand = function (min, max) {
  29038. return Math.random() * (max - min) + min;
  29039. };
  29040. for (var x = 0; x < size; x++) {
  29041. for (var y = 0; y < size; y++) {
  29042. var randVector = BABYLON.Vector3.Zero();
  29043. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29044. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29045. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29046. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29047. context.fillRect(x, y, 1, 1);
  29048. }
  29049. }
  29050. this._randomTexture.update(false);
  29051. };
  29052. return SSAORenderingPipeline;
  29053. })(BABYLON.PostProcessRenderPipeline);
  29054. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29055. })(BABYLON || (BABYLON = {}));
  29056. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29057. var BABYLON;
  29058. (function (BABYLON) {
  29059. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29060. var VolumetricLightScatteringPostProcess = (function (_super) {
  29061. __extends(VolumetricLightScatteringPostProcess, _super);
  29062. /**
  29063. * @constructor
  29064. * @param {string} name - The post-process name
  29065. * @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)
  29066. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29067. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29068. * @param {number} samples - The post-process quality, default 100
  29069. * @param {number} samplingMode - The post-process filtering mode
  29070. * @param {BABYLON.Engine} engine - The babylon engine
  29071. * @param {boolean} reusable - If the post-process is reusable
  29072. */
  29073. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29074. var _this = this;
  29075. if (samples === void 0) { samples = 100; }
  29076. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29077. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29078. this._screenCoordinates = BABYLON.Vector2.Zero();
  29079. /**
  29080. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29081. * @type {boolean}
  29082. */
  29083. this.useCustomMeshPosition = false;
  29084. /**
  29085. * If the post-process should inverse the light scattering direction
  29086. * @type {boolean}
  29087. */
  29088. this.invert = true;
  29089. /**
  29090. * Array containing the excluded meshes not rendered in the internal pass
  29091. */
  29092. this.excludedMeshes = new Array();
  29093. this.exposure = 0.3;
  29094. this.decay = 0.96815;
  29095. this.weight = 0.58767;
  29096. this.density = 0.926;
  29097. var scene = camera.getScene();
  29098. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29099. // Configure mesh
  29100. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29101. // Configure
  29102. this._createPass(scene, ratio.passRatio || ratio);
  29103. this.onApply = function (effect) {
  29104. _this._updateMeshScreenCoordinates(scene);
  29105. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29106. effect.setFloat("exposure", _this.exposure);
  29107. effect.setFloat("decay", _this.decay);
  29108. effect.setFloat("weight", _this.weight);
  29109. effect.setFloat("density", _this.density);
  29110. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29111. };
  29112. }
  29113. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29114. var mesh = subMesh.getMesh();
  29115. var defines = [];
  29116. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29117. var material = subMesh.getMaterial();
  29118. var needUV = false;
  29119. // Render this.mesh as default
  29120. if (mesh === this.mesh) {
  29121. defines.push("#define BASIC_RENDER");
  29122. defines.push("#define NEED_UV");
  29123. needUV = true;
  29124. }
  29125. // Alpha test
  29126. if (material) {
  29127. if (material.needAlphaTesting() || mesh === this.mesh)
  29128. defines.push("#define ALPHATEST");
  29129. if (material.opacityTexture !== undefined) {
  29130. defines.push("#define OPACITY");
  29131. if (material.opacityTexture.getAlphaFromRGB)
  29132. defines.push("#define OPACITYRGB");
  29133. if (!needUV)
  29134. defines.push("#define NEED_UV");
  29135. }
  29136. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29137. attribs.push(BABYLON.VertexBuffer.UVKind);
  29138. defines.push("#define UV1");
  29139. }
  29140. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29141. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29142. defines.push("#define UV2");
  29143. }
  29144. }
  29145. // Bones
  29146. if (mesh.useBones) {
  29147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29149. defines.push("#define BONES");
  29150. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29151. }
  29152. // Instances
  29153. if (useInstances) {
  29154. defines.push("#define INSTANCES");
  29155. attribs.push("world0");
  29156. attribs.push("world1");
  29157. attribs.push("world2");
  29158. attribs.push("world3");
  29159. }
  29160. // Get correct effect
  29161. var join = defines.join("\n");
  29162. if (this._cachedDefines !== join) {
  29163. this._cachedDefines = join;
  29164. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29165. }
  29166. return this._volumetricLightScatteringPass.isReady();
  29167. };
  29168. /**
  29169. * Sets the new light position for light scattering effect
  29170. * @param {BABYLON.Vector3} The new custom light position
  29171. */
  29172. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29173. this._customMeshPosition = position;
  29174. };
  29175. /**
  29176. * Returns the light position for light scattering effect
  29177. * @return {BABYLON.Vector3} The custom light position
  29178. */
  29179. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29180. return this._customMeshPosition;
  29181. };
  29182. /**
  29183. * Disposes the internal assets and detaches the post-process from the camera
  29184. */
  29185. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29186. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29187. if (rttIndex !== -1) {
  29188. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29189. }
  29190. this._volumetricLightScatteringRTT.dispose();
  29191. _super.prototype.dispose.call(this, camera);
  29192. };
  29193. /**
  29194. * Returns the render target texture used by the post-process
  29195. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29196. */
  29197. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29198. return this._volumetricLightScatteringRTT;
  29199. };
  29200. // Private methods
  29201. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29202. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29203. return true;
  29204. }
  29205. return false;
  29206. };
  29207. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29208. var _this = this;
  29209. var engine = scene.getEngine();
  29210. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29211. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29212. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29213. this._volumetricLightScatteringRTT.renderList = null;
  29214. this._volumetricLightScatteringRTT.renderParticles = false;
  29215. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29216. // Custom render function for submeshes
  29217. var renderSubMesh = function (subMesh) {
  29218. var mesh = subMesh.getRenderingMesh();
  29219. if (_this._meshExcluded(mesh)) {
  29220. return;
  29221. }
  29222. var scene = mesh.getScene();
  29223. var engine = scene.getEngine();
  29224. // Culling
  29225. engine.setState(subMesh.getMaterial().backFaceCulling);
  29226. // Managing instances
  29227. var batch = mesh._getInstancesRenderList(subMesh._id);
  29228. if (batch.mustReturn) {
  29229. return;
  29230. }
  29231. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29232. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29233. engine.enableEffect(_this._volumetricLightScatteringPass);
  29234. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29235. var material = subMesh.getMaterial();
  29236. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29237. // Alpha test
  29238. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29239. var alphaTexture = material.getAlphaTestTexture();
  29240. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29241. if (alphaTexture) {
  29242. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29243. }
  29244. if (material.opacityTexture !== undefined) {
  29245. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29246. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  29247. }
  29248. }
  29249. // Bones
  29250. if (mesh.useBones) {
  29251. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29252. }
  29253. // Draw
  29254. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29255. }
  29256. };
  29257. // Render target texture callbacks
  29258. var savedSceneClearColor;
  29259. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  29260. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29261. savedSceneClearColor = scene.clearColor;
  29262. scene.clearColor = sceneClearColor;
  29263. };
  29264. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29265. scene.clearColor = savedSceneClearColor;
  29266. };
  29267. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29268. var engine = scene.getEngine();
  29269. var index;
  29270. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29271. renderSubMesh(opaqueSubMeshes.data[index]);
  29272. }
  29273. engine.setAlphaTesting(true);
  29274. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29275. renderSubMesh(alphaTestSubMeshes.data[index]);
  29276. }
  29277. engine.setAlphaTesting(false);
  29278. if (transparentSubMeshes.length) {
  29279. for (index = 0; index < transparentSubMeshes.length; index++) {
  29280. var submesh = transparentSubMeshes.data[index];
  29281. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  29282. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  29283. }
  29284. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  29285. sortedArray.sort(function (a, b) {
  29286. // Alpha index first
  29287. if (a._alphaIndex > b._alphaIndex) {
  29288. return 1;
  29289. }
  29290. if (a._alphaIndex < b._alphaIndex) {
  29291. return -1;
  29292. }
  29293. // Then distance to camera
  29294. if (a._distanceToCamera < b._distanceToCamera) {
  29295. return 1;
  29296. }
  29297. if (a._distanceToCamera > b._distanceToCamera) {
  29298. return -1;
  29299. }
  29300. return 0;
  29301. });
  29302. // Render sub meshes
  29303. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29304. for (index = 0; index < sortedArray.length; index++) {
  29305. renderSubMesh(sortedArray[index]);
  29306. }
  29307. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29308. }
  29309. };
  29310. };
  29311. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29312. var transform = scene.getTransformMatrix();
  29313. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29314. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29315. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29316. if (this.invert)
  29317. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29318. };
  29319. // Static methods
  29320. /**
  29321. * Creates a default mesh for the Volumeric Light Scattering post-process
  29322. * @param {string} The mesh name
  29323. * @param {BABYLON.Scene} The scene where to create the mesh
  29324. * @return {BABYLON.Mesh} the default mesh
  29325. */
  29326. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29327. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29328. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29329. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29330. return mesh;
  29331. };
  29332. return VolumetricLightScatteringPostProcess;
  29333. })(BABYLON.PostProcess);
  29334. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29335. })(BABYLON || (BABYLON = {}));
  29336. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29337. var BABYLON;
  29338. (function (BABYLON) {
  29339. var LensRenderingPipeline = (function (_super) {
  29340. __extends(LensRenderingPipeline, _super);
  29341. /**
  29342. * @constructor
  29343. * @param {string} name - The rendering pipeline name
  29344. * @param {object} parameters - An object containing all parameters (see below)
  29345. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29346. * @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)
  29347. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29348. Effect parameters are as follow:
  29349. {
  29350. chromatic_aberration: number; // from 0 to x (1 for realism)
  29351. edge_blur: number; // from 0 to x (1 for realism)
  29352. distortion: number; // from 0 to x (1 for realism)
  29353. grain_amount: number; // from 0 to 1
  29354. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29355. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  29356. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29357. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29358. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  29359. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  29360. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29361. }
  29362. Note: if an effect parameter is unset, effect is disabled
  29363. */
  29364. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29365. var _this = this;
  29366. if (ratio === void 0) { ratio = 1.0; }
  29367. _super.call(this, scene.getEngine(), name);
  29368. // Lens effects can be of the following:
  29369. // - chromatic aberration (slight shift of RGB colors)
  29370. // - blur on the edge of the lens
  29371. // - lens distortion
  29372. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  29373. // - grain/dust-on-lens effect
  29374. // Two additional texture samplers are needed:
  29375. // - depth map (for depth-of-field)
  29376. // - grain texture
  29377. /**
  29378. * The chromatic aberration PostProcess id in the pipeline
  29379. * @type {string}
  29380. */
  29381. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29382. /**
  29383. * The depth-of-field PostProcess id in the pipeline
  29384. * @type {string}
  29385. */
  29386. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29387. this._scene = scene;
  29388. // Fetch texture samplers
  29389. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29390. if (parameters.grain_texture) {
  29391. this._grainTexture = parameters.grain_texture;
  29392. }
  29393. else {
  29394. this._createGrainTexture();
  29395. }
  29396. // save parameters
  29397. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29398. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29399. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29400. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29401. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29402. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29403. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29404. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29405. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29406. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29407. // Create effects
  29408. this._createChromaticAberrationPostProcess(ratio);
  29409. this._createDepthOfFieldPostProcess(ratio);
  29410. // Set up pipeline
  29411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29412. return _this._chromaticAberrationPostProcess;
  29413. }, true));
  29414. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29415. return _this._depthOfFieldPostProcess;
  29416. }, true));
  29417. // Finish
  29418. scene.postProcessRenderPipelineManager.addPipeline(this);
  29419. if (cameras) {
  29420. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29421. }
  29422. }
  29423. // public methods
  29424. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29425. this._edgeBlur = amount;
  29426. };
  29427. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29428. this._edgeBlur = 0;
  29429. };
  29430. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29431. this._grainAmount = amount;
  29432. };
  29433. LensRenderingPipeline.prototype.disableGrain = function () {
  29434. this._grainAmount = 0;
  29435. };
  29436. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29437. this._chromaticAberration = amount;
  29438. };
  29439. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29440. this._chromaticAberration = 0;
  29441. };
  29442. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29443. this._distortion = amount;
  29444. };
  29445. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29446. this._distortion = 0;
  29447. };
  29448. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29449. this._highlightsGain = amount;
  29450. };
  29451. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29452. this._highlightsThreshold = amount;
  29453. };
  29454. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29455. this._dofDepth = amount;
  29456. };
  29457. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29458. this._dofDepth = -1;
  29459. };
  29460. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29461. this._dofAperture = amount;
  29462. };
  29463. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29464. this._dofPentagon = true;
  29465. };
  29466. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29467. this._dofPentagon = false;
  29468. };
  29469. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29470. this._blurNoise = true;
  29471. };
  29472. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29473. this._blurNoise = false;
  29474. };
  29475. /**
  29476. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29477. */
  29478. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29479. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29480. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29481. this._chromaticAberrationPostProcess = undefined;
  29482. this._depthOfFieldPostProcess = undefined;
  29483. this._grainTexture.dispose();
  29484. if (disableDepthRender)
  29485. this._scene.disableDepthRenderer();
  29486. };
  29487. // colors shifting and distortion
  29488. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29489. var _this = this;
  29490. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29491. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29492. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29493. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29494. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29495. };
  29496. };
  29497. // colors shifting and distortion
  29498. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29499. var _this = this;
  29500. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29501. "gain",
  29502. "threshold",
  29503. "focus_depth",
  29504. "aperture",
  29505. "pentagon",
  29506. "maxZ",
  29507. "edge_blur",
  29508. "chromatic_aberration",
  29509. "distortion",
  29510. "blur_noise",
  29511. "grain_amount",
  29512. "screen_width",
  29513. "screen_height"
  29514. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29515. this._depthOfFieldPostProcess.onApply = function (effect) {
  29516. effect.setBool('pentagon', _this._dofPentagon);
  29517. effect.setBool('blur_noise', _this._blurNoise);
  29518. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29519. effect.setFloat('grain_amount', _this._grainAmount);
  29520. effect.setTexture("depthSampler", _this._depthTexture);
  29521. effect.setTexture("grainSampler", _this._grainTexture);
  29522. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29523. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29524. effect.setFloat('distortion', _this._distortion);
  29525. effect.setFloat('focus_depth', _this._dofDepth);
  29526. effect.setFloat('aperture', _this._dofAperture);
  29527. effect.setFloat('gain', _this._highlightsGain);
  29528. effect.setFloat('threshold', _this._highlightsThreshold);
  29529. effect.setFloat('edge_blur', _this._edgeBlur);
  29530. };
  29531. };
  29532. // creates a black and white random noise texture, 512x512
  29533. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29534. var size = 512;
  29535. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29536. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29537. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29538. var context = this._grainTexture.getContext();
  29539. var rand = function (min, max) {
  29540. return Math.random() * (max - min) + min;
  29541. };
  29542. var value;
  29543. for (var x = 0; x < size; x++) {
  29544. for (var y = 0; y < size; y++) {
  29545. value = Math.floor(rand(0.42, 0.58) * 255);
  29546. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29547. context.fillRect(x, y, 1, 1);
  29548. }
  29549. }
  29550. this._grainTexture.update(false);
  29551. };
  29552. return LensRenderingPipeline;
  29553. })(BABYLON.PostProcessRenderPipeline);
  29554. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29555. })(BABYLON || (BABYLON = {}));
  29556. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  29557. // This post-process allows the modification of rendered colors by using
  29558. // a 'look-up table' (LUT). This effect is also called Color Grading.
  29559. //
  29560. // The object needs to be provided an url to a texture containing the color
  29561. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  29562. // Use an image editing software to tweak the LUT to match your needs.
  29563. //
  29564. // For an example of a color LUT, see here:
  29565. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  29566. // For explanations on color grading, see here:
  29567. // http://udn.epicgames.com/Three/ColorGrading.html
  29568. //
  29569. var BABYLON;
  29570. (function (BABYLON) {
  29571. var ColorCorrectionPostProcess = (function (_super) {
  29572. __extends(ColorCorrectionPostProcess, _super);
  29573. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  29574. var _this = this;
  29575. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  29576. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  29577. this._colorTableTexture.anisotropicFilteringLevel = 1;
  29578. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29579. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29580. this.onApply = function (effect) {
  29581. effect.setTexture("colorTable", _this._colorTableTexture);
  29582. };
  29583. }
  29584. return ColorCorrectionPostProcess;
  29585. })(BABYLON.PostProcess);
  29586. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  29587. })(BABYLON || (BABYLON = {}));
  29588. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map