babylon.2.1-alpha.debug.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  657. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  658. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1124. }
  1125. else {
  1126. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. Quaternion.FromRotationMatrixToRef(matrix, this);
  1163. return this;
  1164. };
  1165. // Statics
  1166. Quaternion.FromRotationMatrix = function (matrix) {
  1167. var result = new Quaternion();
  1168. Quaternion.FromRotationMatrixToRef(matrix, result);
  1169. return result;
  1170. };
  1171. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1172. var data = matrix.m;
  1173. var m11 = data[0], m12 = data[4], m13 = data[8];
  1174. var m21 = data[1], m22 = data[5], m23 = data[9];
  1175. var m31 = data[2], m32 = data[6], m33 = data[10];
  1176. var trace = m11 + m22 + m33;
  1177. var s;
  1178. if (trace > 0) {
  1179. s = 0.5 / Math.sqrt(trace + 1.0);
  1180. result.w = 0.25 / s;
  1181. result.x = (m32 - m23) * s;
  1182. result.y = (m13 - m31) * s;
  1183. result.z = (m21 - m12) * s;
  1184. }
  1185. else if (m11 > m22 && m11 > m33) {
  1186. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1187. result.w = (m32 - m23) / s;
  1188. result.x = 0.25 * s;
  1189. result.y = (m12 + m21) / s;
  1190. result.z = (m13 + m31) / s;
  1191. }
  1192. else if (m22 > m33) {
  1193. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1194. result.w = (m13 - m31) / s;
  1195. result.x = (m12 + m21) / s;
  1196. result.y = 0.25 * s;
  1197. result.z = (m23 + m32) / s;
  1198. }
  1199. else {
  1200. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1201. result.w = (m21 - m12) / s;
  1202. result.x = (m13 + m31) / s;
  1203. result.y = (m23 + m32) / s;
  1204. result.z = 0.25 * s;
  1205. }
  1206. };
  1207. Quaternion.Inverse = function (q) {
  1208. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1209. };
  1210. Quaternion.Identity = function () {
  1211. return new Quaternion(0, 0, 0, 1);
  1212. };
  1213. Quaternion.RotationAxis = function (axis, angle) {
  1214. var result = new Quaternion();
  1215. var sin = Math.sin(angle / 2);
  1216. result.w = Math.cos(angle / 2);
  1217. result.x = axis.x * sin;
  1218. result.y = axis.y * sin;
  1219. result.z = axis.z * sin;
  1220. return result;
  1221. };
  1222. Quaternion.FromArray = function (array, offset) {
  1223. if (!offset) {
  1224. offset = 0;
  1225. }
  1226. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1227. };
  1228. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1229. var result = new Quaternion();
  1230. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1231. return result;
  1232. };
  1233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1234. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1235. var halfRoll = roll * 0.5;
  1236. var halfPitch = pitch * 0.5;
  1237. var halfYaw = yaw * 0.5;
  1238. var sinRoll = Math.sin(halfRoll);
  1239. var cosRoll = Math.cos(halfRoll);
  1240. var sinPitch = Math.sin(halfPitch);
  1241. var cosPitch = Math.cos(halfPitch);
  1242. var sinYaw = Math.sin(halfYaw);
  1243. var cosYaw = Math.cos(halfYaw);
  1244. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1245. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1246. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1247. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1248. };
  1249. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1250. var result = new Quaternion();
  1251. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1252. return result;
  1253. };
  1254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1255. // Produces a quaternion from Euler angles in the z-x-z orientation
  1256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1258. var halfBeta = beta * 0.5;
  1259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1263. };
  1264. Quaternion.Slerp = function (left, right, amount) {
  1265. var num2;
  1266. var num3;
  1267. var num = amount;
  1268. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1269. var flag = false;
  1270. if (num4 < 0) {
  1271. flag = true;
  1272. num4 = -num4;
  1273. }
  1274. if (num4 > 0.999999) {
  1275. num3 = 1 - num;
  1276. num2 = flag ? -num : num;
  1277. }
  1278. else {
  1279. var num5 = Math.acos(num4);
  1280. var num6 = (1.0 / Math.sin(num5));
  1281. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1282. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1283. }
  1284. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1285. };
  1286. return Quaternion;
  1287. })();
  1288. BABYLON.Quaternion = Quaternion;
  1289. var Matrix = (function () {
  1290. function Matrix() {
  1291. this.m = new Float32Array(16);
  1292. }
  1293. // Properties
  1294. Matrix.prototype.isIdentity = function () {
  1295. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1296. return false;
  1297. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1298. return false;
  1299. return true;
  1300. };
  1301. Matrix.prototype.determinant = function () {
  1302. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1303. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1304. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1305. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1306. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1307. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1308. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1309. };
  1310. // Methods
  1311. Matrix.prototype.toArray = function () {
  1312. return this.m;
  1313. };
  1314. Matrix.prototype.asArray = function () {
  1315. return this.toArray();
  1316. };
  1317. Matrix.prototype.invert = function () {
  1318. this.invertToRef(this);
  1319. return this;
  1320. };
  1321. Matrix.prototype.invertToRef = function (other) {
  1322. var l1 = this.m[0];
  1323. var l2 = this.m[1];
  1324. var l3 = this.m[2];
  1325. var l4 = this.m[3];
  1326. var l5 = this.m[4];
  1327. var l6 = this.m[5];
  1328. var l7 = this.m[6];
  1329. var l8 = this.m[7];
  1330. var l9 = this.m[8];
  1331. var l10 = this.m[9];
  1332. var l11 = this.m[10];
  1333. var l12 = this.m[11];
  1334. var l13 = this.m[12];
  1335. var l14 = this.m[13];
  1336. var l15 = this.m[14];
  1337. var l16 = this.m[15];
  1338. var l17 = (l11 * l16) - (l12 * l15);
  1339. var l18 = (l10 * l16) - (l12 * l14);
  1340. var l19 = (l10 * l15) - (l11 * l14);
  1341. var l20 = (l9 * l16) - (l12 * l13);
  1342. var l21 = (l9 * l15) - (l11 * l13);
  1343. var l22 = (l9 * l14) - (l10 * l13);
  1344. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1345. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1346. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1347. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1348. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1349. var l28 = (l7 * l16) - (l8 * l15);
  1350. var l29 = (l6 * l16) - (l8 * l14);
  1351. var l30 = (l6 * l15) - (l7 * l14);
  1352. var l31 = (l5 * l16) - (l8 * l13);
  1353. var l32 = (l5 * l15) - (l7 * l13);
  1354. var l33 = (l5 * l14) - (l6 * l13);
  1355. var l34 = (l7 * l12) - (l8 * l11);
  1356. var l35 = (l6 * l12) - (l8 * l10);
  1357. var l36 = (l6 * l11) - (l7 * l10);
  1358. var l37 = (l5 * l12) - (l8 * l9);
  1359. var l38 = (l5 * l11) - (l7 * l9);
  1360. var l39 = (l5 * l10) - (l6 * l9);
  1361. other.m[0] = l23 * l27;
  1362. other.m[4] = l24 * l27;
  1363. other.m[8] = l25 * l27;
  1364. other.m[12] = l26 * l27;
  1365. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1366. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1367. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1368. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1369. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1370. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1371. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1372. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1373. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1374. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1375. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1376. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1377. return this;
  1378. };
  1379. Matrix.prototype.setTranslation = function (vector3) {
  1380. this.m[12] = vector3.x;
  1381. this.m[13] = vector3.y;
  1382. this.m[14] = vector3.z;
  1383. return this;
  1384. };
  1385. Matrix.prototype.multiply = function (other) {
  1386. var result = new Matrix();
  1387. this.multiplyToRef(other, result);
  1388. return result;
  1389. };
  1390. Matrix.prototype.copyFrom = function (other) {
  1391. for (var index = 0; index < 16; index++) {
  1392. this.m[index] = other.m[index];
  1393. }
  1394. return this;
  1395. };
  1396. Matrix.prototype.copyToArray = function (array, offset) {
  1397. if (offset === void 0) { offset = 0; }
  1398. for (var index = 0; index < 16; index++) {
  1399. array[offset + index] = this.m[index];
  1400. }
  1401. return this;
  1402. };
  1403. Matrix.prototype.multiplyToRef = function (other, result) {
  1404. this.multiplyToArray(other, result.m, 0);
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1408. var tm0 = this.m[0];
  1409. var tm1 = this.m[1];
  1410. var tm2 = this.m[2];
  1411. var tm3 = this.m[3];
  1412. var tm4 = this.m[4];
  1413. var tm5 = this.m[5];
  1414. var tm6 = this.m[6];
  1415. var tm7 = this.m[7];
  1416. var tm8 = this.m[8];
  1417. var tm9 = this.m[9];
  1418. var tm10 = this.m[10];
  1419. var tm11 = this.m[11];
  1420. var tm12 = this.m[12];
  1421. var tm13 = this.m[13];
  1422. var tm14 = this.m[14];
  1423. var tm15 = this.m[15];
  1424. var om0 = other.m[0];
  1425. var om1 = other.m[1];
  1426. var om2 = other.m[2];
  1427. var om3 = other.m[3];
  1428. var om4 = other.m[4];
  1429. var om5 = other.m[5];
  1430. var om6 = other.m[6];
  1431. var om7 = other.m[7];
  1432. var om8 = other.m[8];
  1433. var om9 = other.m[9];
  1434. var om10 = other.m[10];
  1435. var om11 = other.m[11];
  1436. var om12 = other.m[12];
  1437. var om13 = other.m[13];
  1438. var om14 = other.m[14];
  1439. var om15 = other.m[15];
  1440. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1441. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1442. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1443. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1444. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1445. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1446. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1447. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1448. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1449. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1450. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1451. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1452. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1453. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1454. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1455. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1456. return this;
  1457. };
  1458. Matrix.prototype.equals = function (value) {
  1459. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1460. };
  1461. Matrix.prototype.clone = function () {
  1462. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1463. };
  1464. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1465. translation.x = this.m[12];
  1466. translation.y = this.m[13];
  1467. translation.z = this.m[14];
  1468. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1469. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1470. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1471. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1472. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1473. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1474. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1475. rotation.x = 0;
  1476. rotation.y = 0;
  1477. rotation.z = 0;
  1478. rotation.w = 1;
  1479. return false;
  1480. }
  1481. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1482. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1483. return true;
  1484. };
  1485. // Statics
  1486. Matrix.FromArray = function (array, offset) {
  1487. var result = new Matrix();
  1488. if (!offset) {
  1489. offset = 0;
  1490. }
  1491. Matrix.FromArrayToRef(array, offset, result);
  1492. return result;
  1493. };
  1494. Matrix.FromArrayToRef = function (array, offset, result) {
  1495. for (var index = 0; index < 16; index++) {
  1496. result.m[index] = array[index + offset];
  1497. }
  1498. };
  1499. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1500. result.m[0] = initialM11;
  1501. result.m[1] = initialM12;
  1502. result.m[2] = initialM13;
  1503. result.m[3] = initialM14;
  1504. result.m[4] = initialM21;
  1505. result.m[5] = initialM22;
  1506. result.m[6] = initialM23;
  1507. result.m[7] = initialM24;
  1508. result.m[8] = initialM31;
  1509. result.m[9] = initialM32;
  1510. result.m[10] = initialM33;
  1511. result.m[11] = initialM34;
  1512. result.m[12] = initialM41;
  1513. result.m[13] = initialM42;
  1514. result.m[14] = initialM43;
  1515. result.m[15] = initialM44;
  1516. };
  1517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1518. var result = new Matrix();
  1519. result.m[0] = initialM11;
  1520. result.m[1] = initialM12;
  1521. result.m[2] = initialM13;
  1522. result.m[3] = initialM14;
  1523. result.m[4] = initialM21;
  1524. result.m[5] = initialM22;
  1525. result.m[6] = initialM23;
  1526. result.m[7] = initialM24;
  1527. result.m[8] = initialM31;
  1528. result.m[9] = initialM32;
  1529. result.m[10] = initialM33;
  1530. result.m[11] = initialM34;
  1531. result.m[12] = initialM41;
  1532. result.m[13] = initialM42;
  1533. result.m[14] = initialM43;
  1534. result.m[15] = initialM44;
  1535. return result;
  1536. };
  1537. Matrix.Compose = function (scale, rotation, translation) {
  1538. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1539. var rotationMatrix = Matrix.Identity();
  1540. rotation.toRotationMatrix(rotationMatrix);
  1541. result = result.multiply(rotationMatrix);
  1542. result.setTranslation(translation);
  1543. return result;
  1544. };
  1545. Matrix.Identity = function () {
  1546. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1547. };
  1548. Matrix.IdentityToRef = function (result) {
  1549. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1550. };
  1551. Matrix.Zero = function () {
  1552. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1553. };
  1554. Matrix.RotationX = function (angle) {
  1555. var result = new Matrix();
  1556. Matrix.RotationXToRef(angle, result);
  1557. return result;
  1558. };
  1559. Matrix.Invert = function (source) {
  1560. var result = new Matrix();
  1561. source.invertToRef(result);
  1562. return result;
  1563. };
  1564. Matrix.RotationXToRef = function (angle, result) {
  1565. var s = Math.sin(angle);
  1566. var c = Math.cos(angle);
  1567. result.m[0] = 1.0;
  1568. result.m[15] = 1.0;
  1569. result.m[5] = c;
  1570. result.m[10] = c;
  1571. result.m[9] = -s;
  1572. result.m[6] = s;
  1573. result.m[1] = 0;
  1574. result.m[2] = 0;
  1575. result.m[3] = 0;
  1576. result.m[4] = 0;
  1577. result.m[7] = 0;
  1578. result.m[8] = 0;
  1579. result.m[11] = 0;
  1580. result.m[12] = 0;
  1581. result.m[13] = 0;
  1582. result.m[14] = 0;
  1583. };
  1584. Matrix.RotationY = function (angle) {
  1585. var result = new Matrix();
  1586. Matrix.RotationYToRef(angle, result);
  1587. return result;
  1588. };
  1589. Matrix.RotationYToRef = function (angle, result) {
  1590. var s = Math.sin(angle);
  1591. var c = Math.cos(angle);
  1592. result.m[5] = 1.0;
  1593. result.m[15] = 1.0;
  1594. result.m[0] = c;
  1595. result.m[2] = -s;
  1596. result.m[8] = s;
  1597. result.m[10] = c;
  1598. result.m[1] = 0;
  1599. result.m[3] = 0;
  1600. result.m[4] = 0;
  1601. result.m[6] = 0;
  1602. result.m[7] = 0;
  1603. result.m[9] = 0;
  1604. result.m[11] = 0;
  1605. result.m[12] = 0;
  1606. result.m[13] = 0;
  1607. result.m[14] = 0;
  1608. };
  1609. Matrix.RotationZ = function (angle) {
  1610. var result = new Matrix();
  1611. Matrix.RotationZToRef(angle, result);
  1612. return result;
  1613. };
  1614. Matrix.RotationZToRef = function (angle, result) {
  1615. var s = Math.sin(angle);
  1616. var c = Math.cos(angle);
  1617. result.m[10] = 1.0;
  1618. result.m[15] = 1.0;
  1619. result.m[0] = c;
  1620. result.m[1] = s;
  1621. result.m[4] = -s;
  1622. result.m[5] = c;
  1623. result.m[2] = 0;
  1624. result.m[3] = 0;
  1625. result.m[6] = 0;
  1626. result.m[7] = 0;
  1627. result.m[8] = 0;
  1628. result.m[9] = 0;
  1629. result.m[11] = 0;
  1630. result.m[12] = 0;
  1631. result.m[13] = 0;
  1632. result.m[14] = 0;
  1633. };
  1634. Matrix.RotationAxis = function (axis, angle) {
  1635. var s = Math.sin(-angle);
  1636. var c = Math.cos(-angle);
  1637. var c1 = 1 - c;
  1638. axis.normalize();
  1639. var result = Matrix.Zero();
  1640. result.m[0] = (axis.x * axis.x) * c1 + c;
  1641. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1642. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1643. result.m[3] = 0.0;
  1644. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1645. result.m[5] = (axis.y * axis.y) * c1 + c;
  1646. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1647. result.m[7] = 0.0;
  1648. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1649. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1650. result.m[10] = (axis.z * axis.z) * c1 + c;
  1651. result.m[11] = 0.0;
  1652. result.m[15] = 1.0;
  1653. return result;
  1654. };
  1655. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1656. var result = new Matrix();
  1657. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1658. return result;
  1659. };
  1660. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1661. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1662. this._tempQuaternion.toRotationMatrix(result);
  1663. };
  1664. Matrix.Scaling = function (x, y, z) {
  1665. var result = Matrix.Zero();
  1666. Matrix.ScalingToRef(x, y, z, result);
  1667. return result;
  1668. };
  1669. Matrix.ScalingToRef = function (x, y, z, result) {
  1670. result.m[0] = x;
  1671. result.m[1] = 0;
  1672. result.m[2] = 0;
  1673. result.m[3] = 0;
  1674. result.m[4] = 0;
  1675. result.m[5] = y;
  1676. result.m[6] = 0;
  1677. result.m[7] = 0;
  1678. result.m[8] = 0;
  1679. result.m[9] = 0;
  1680. result.m[10] = z;
  1681. result.m[11] = 0;
  1682. result.m[12] = 0;
  1683. result.m[13] = 0;
  1684. result.m[14] = 0;
  1685. result.m[15] = 1.0;
  1686. };
  1687. Matrix.Translation = function (x, y, z) {
  1688. var result = Matrix.Identity();
  1689. Matrix.TranslationToRef(x, y, z, result);
  1690. return result;
  1691. };
  1692. Matrix.TranslationToRef = function (x, y, z, result) {
  1693. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1694. };
  1695. Matrix.LookAtLH = function (eye, target, up) {
  1696. var result = Matrix.Zero();
  1697. Matrix.LookAtLHToRef(eye, target, up, result);
  1698. return result;
  1699. };
  1700. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1701. // Z axis
  1702. target.subtractToRef(eye, this._zAxis);
  1703. this._zAxis.normalize();
  1704. // X axis
  1705. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1706. this._xAxis.normalize();
  1707. // Y axis
  1708. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1709. this._yAxis.normalize();
  1710. // Eye angles
  1711. var ex = -Vector3.Dot(this._xAxis, eye);
  1712. var ey = -Vector3.Dot(this._yAxis, eye);
  1713. var ez = -Vector3.Dot(this._zAxis, eye);
  1714. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1715. };
  1716. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1717. var matrix = Matrix.Zero();
  1718. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1719. return matrix;
  1720. };
  1721. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1722. var hw = 2.0 / width;
  1723. var hh = 2.0 / height;
  1724. var id = 1.0 / (zfar - znear);
  1725. var nid = znear / (znear - zfar);
  1726. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1727. };
  1728. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1729. var matrix = Matrix.Zero();
  1730. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1731. return matrix;
  1732. };
  1733. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1734. result.m[0] = 2.0 / (right - left);
  1735. result.m[1] = result.m[2] = result.m[3] = 0;
  1736. result.m[5] = 2.0 / (top - bottom);
  1737. result.m[4] = result.m[6] = result.m[7] = 0;
  1738. result.m[10] = -1.0 / (znear - zfar);
  1739. result.m[8] = result.m[9] = result.m[11] = 0;
  1740. result.m[12] = (left + right) / (left - right);
  1741. result.m[13] = (top + bottom) / (bottom - top);
  1742. result.m[14] = znear / (znear - zfar);
  1743. result.m[15] = 1.0;
  1744. };
  1745. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1746. var matrix = Matrix.Zero();
  1747. matrix.m[0] = (2.0 * znear) / width;
  1748. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1749. matrix.m[5] = (2.0 * znear) / height;
  1750. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1751. matrix.m[10] = -zfar / (znear - zfar);
  1752. matrix.m[8] = matrix.m[9] = 0.0;
  1753. matrix.m[11] = 1.0;
  1754. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1755. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1756. return matrix;
  1757. };
  1758. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1759. var matrix = Matrix.Zero();
  1760. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1761. return matrix;
  1762. };
  1763. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1764. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1765. var tan = 1.0 / (Math.tan(fov * 0.5));
  1766. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1767. if (v_fixed) {
  1768. result.m[0] = tan / aspect;
  1769. }
  1770. else {
  1771. result.m[0] = tan;
  1772. }
  1773. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1774. if (v_fixed) {
  1775. result.m[5] = tan;
  1776. }
  1777. else {
  1778. result.m[5] = tan * aspect;
  1779. }
  1780. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1781. result.m[8] = result.m[9] = 0.0;
  1782. result.m[10] = -zfar / (znear - zfar);
  1783. result.m[11] = 1.0;
  1784. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1785. result.m[14] = (znear * zfar) / (znear - zfar);
  1786. };
  1787. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1788. var cw = viewport.width;
  1789. var ch = viewport.height;
  1790. var cx = viewport.x;
  1791. var cy = viewport.y;
  1792. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1793. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1794. };
  1795. Matrix.Transpose = function (matrix) {
  1796. var result = new Matrix();
  1797. result.m[0] = matrix.m[0];
  1798. result.m[1] = matrix.m[4];
  1799. result.m[2] = matrix.m[8];
  1800. result.m[3] = matrix.m[12];
  1801. result.m[4] = matrix.m[1];
  1802. result.m[5] = matrix.m[5];
  1803. result.m[6] = matrix.m[9];
  1804. result.m[7] = matrix.m[13];
  1805. result.m[8] = matrix.m[2];
  1806. result.m[9] = matrix.m[6];
  1807. result.m[10] = matrix.m[10];
  1808. result.m[11] = matrix.m[14];
  1809. result.m[12] = matrix.m[3];
  1810. result.m[13] = matrix.m[7];
  1811. result.m[14] = matrix.m[11];
  1812. result.m[15] = matrix.m[15];
  1813. return result;
  1814. };
  1815. Matrix.Reflection = function (plane) {
  1816. var matrix = new Matrix();
  1817. Matrix.ReflectionToRef(plane, matrix);
  1818. return matrix;
  1819. };
  1820. Matrix.ReflectionToRef = function (plane, result) {
  1821. plane.normalize();
  1822. var x = plane.normal.x;
  1823. var y = plane.normal.y;
  1824. var z = plane.normal.z;
  1825. var temp = -2 * x;
  1826. var temp2 = -2 * y;
  1827. var temp3 = -2 * z;
  1828. result.m[0] = (temp * x) + 1;
  1829. result.m[1] = temp2 * x;
  1830. result.m[2] = temp3 * x;
  1831. result.m[3] = 0.0;
  1832. result.m[4] = temp * y;
  1833. result.m[5] = (temp2 * y) + 1;
  1834. result.m[6] = temp3 * y;
  1835. result.m[7] = 0.0;
  1836. result.m[8] = temp * z;
  1837. result.m[9] = temp2 * z;
  1838. result.m[10] = (temp3 * z) + 1;
  1839. result.m[11] = 0.0;
  1840. result.m[12] = temp * plane.d;
  1841. result.m[13] = temp2 * plane.d;
  1842. result.m[14] = temp3 * plane.d;
  1843. result.m[15] = 1.0;
  1844. };
  1845. Matrix._tempQuaternion = new Quaternion();
  1846. Matrix._xAxis = Vector3.Zero();
  1847. Matrix._yAxis = Vector3.Zero();
  1848. Matrix._zAxis = Vector3.Zero();
  1849. return Matrix;
  1850. })();
  1851. BABYLON.Matrix = Matrix;
  1852. var Plane = (function () {
  1853. function Plane(a, b, c, d) {
  1854. this.normal = new Vector3(a, b, c);
  1855. this.d = d;
  1856. }
  1857. Plane.prototype.asArray = function () {
  1858. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1859. };
  1860. // Methods
  1861. Plane.prototype.clone = function () {
  1862. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1863. };
  1864. Plane.prototype.normalize = function () {
  1865. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1866. var magnitude = 0;
  1867. if (norm !== 0) {
  1868. magnitude = 1.0 / norm;
  1869. }
  1870. this.normal.x *= magnitude;
  1871. this.normal.y *= magnitude;
  1872. this.normal.z *= magnitude;
  1873. this.d *= magnitude;
  1874. return this;
  1875. };
  1876. Plane.prototype.transform = function (transformation) {
  1877. var transposedMatrix = Matrix.Transpose(transformation);
  1878. var x = this.normal.x;
  1879. var y = this.normal.y;
  1880. var z = this.normal.z;
  1881. var d = this.d;
  1882. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1883. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1884. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1885. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1886. return new Plane(normalX, normalY, normalZ, finalD);
  1887. };
  1888. Plane.prototype.dotCoordinate = function (point) {
  1889. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1890. };
  1891. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1892. var x1 = point2.x - point1.x;
  1893. var y1 = point2.y - point1.y;
  1894. var z1 = point2.z - point1.z;
  1895. var x2 = point3.x - point1.x;
  1896. var y2 = point3.y - point1.y;
  1897. var z2 = point3.z - point1.z;
  1898. var yz = (y1 * z2) - (z1 * y2);
  1899. var xz = (z1 * x2) - (x1 * z2);
  1900. var xy = (x1 * y2) - (y1 * x2);
  1901. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1902. var invPyth;
  1903. if (pyth !== 0) {
  1904. invPyth = 1.0 / pyth;
  1905. }
  1906. else {
  1907. invPyth = 0;
  1908. }
  1909. this.normal.x = yz * invPyth;
  1910. this.normal.y = xz * invPyth;
  1911. this.normal.z = xy * invPyth;
  1912. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1913. return this;
  1914. };
  1915. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1916. var dot = Vector3.Dot(this.normal, direction);
  1917. return (dot <= epsilon);
  1918. };
  1919. Plane.prototype.signedDistanceTo = function (point) {
  1920. return Vector3.Dot(point, this.normal) + this.d;
  1921. };
  1922. // Statics
  1923. Plane.FromArray = function (array) {
  1924. return new Plane(array[0], array[1], array[2], array[3]);
  1925. };
  1926. Plane.FromPoints = function (point1, point2, point3) {
  1927. var result = new Plane(0, 0, 0, 0);
  1928. result.copyFromPoints(point1, point2, point3);
  1929. return result;
  1930. };
  1931. Plane.FromPositionAndNormal = function (origin, normal) {
  1932. var result = new Plane(0, 0, 0, 0);
  1933. normal.normalize();
  1934. result.normal = normal;
  1935. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1936. return result;
  1937. };
  1938. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1939. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1940. return Vector3.Dot(point, normal) + d;
  1941. };
  1942. return Plane;
  1943. })();
  1944. BABYLON.Plane = Plane;
  1945. var Viewport = (function () {
  1946. function Viewport(x, y, width, height) {
  1947. this.x = x;
  1948. this.y = y;
  1949. this.width = width;
  1950. this.height = height;
  1951. }
  1952. Viewport.prototype.toGlobal = function (engine) {
  1953. var width = engine.getRenderWidth();
  1954. var height = engine.getRenderHeight();
  1955. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1956. };
  1957. return Viewport;
  1958. })();
  1959. BABYLON.Viewport = Viewport;
  1960. var Frustum = (function () {
  1961. function Frustum() {
  1962. }
  1963. Frustum.GetPlanes = function (transform) {
  1964. var frustumPlanes = [];
  1965. for (var index = 0; index < 6; index++) {
  1966. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1967. }
  1968. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1969. return frustumPlanes;
  1970. };
  1971. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1972. // Near
  1973. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1974. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1975. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1976. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1977. frustumPlanes[0].normalize();
  1978. // Far
  1979. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1980. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1981. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1982. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1983. frustumPlanes[1].normalize();
  1984. // Left
  1985. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1986. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1987. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1988. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1989. frustumPlanes[2].normalize();
  1990. // Right
  1991. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1992. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1993. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1994. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1995. frustumPlanes[3].normalize();
  1996. // Top
  1997. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1998. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1999. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2000. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2001. frustumPlanes[4].normalize();
  2002. // Bottom
  2003. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2004. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2005. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2006. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2007. frustumPlanes[5].normalize();
  2008. };
  2009. return Frustum;
  2010. })();
  2011. BABYLON.Frustum = Frustum;
  2012. var Ray = (function () {
  2013. function Ray(origin, direction, length) {
  2014. if (length === void 0) { length = Number.MAX_VALUE; }
  2015. this.origin = origin;
  2016. this.direction = direction;
  2017. this.length = length;
  2018. }
  2019. // Methods
  2020. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2021. var d = 0.0;
  2022. var maxValue = Number.MAX_VALUE;
  2023. if (Math.abs(this.direction.x) < 0.0000001) {
  2024. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2025. return false;
  2026. }
  2027. }
  2028. else {
  2029. var inv = 1.0 / this.direction.x;
  2030. var min = (minimum.x - this.origin.x) * inv;
  2031. var max = (maximum.x - this.origin.x) * inv;
  2032. if (max === -Infinity) {
  2033. max = Infinity;
  2034. }
  2035. if (min > max) {
  2036. var temp = min;
  2037. min = max;
  2038. max = temp;
  2039. }
  2040. d = Math.max(min, d);
  2041. maxValue = Math.min(max, maxValue);
  2042. if (d > maxValue) {
  2043. return false;
  2044. }
  2045. }
  2046. if (Math.abs(this.direction.y) < 0.0000001) {
  2047. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2048. return false;
  2049. }
  2050. }
  2051. else {
  2052. inv = 1.0 / this.direction.y;
  2053. min = (minimum.y - this.origin.y) * inv;
  2054. max = (maximum.y - this.origin.y) * inv;
  2055. if (max === -Infinity) {
  2056. max = Infinity;
  2057. }
  2058. if (min > max) {
  2059. temp = min;
  2060. min = max;
  2061. max = temp;
  2062. }
  2063. d = Math.max(min, d);
  2064. maxValue = Math.min(max, maxValue);
  2065. if (d > maxValue) {
  2066. return false;
  2067. }
  2068. }
  2069. if (Math.abs(this.direction.z) < 0.0000001) {
  2070. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2071. return false;
  2072. }
  2073. }
  2074. else {
  2075. inv = 1.0 / this.direction.z;
  2076. min = (minimum.z - this.origin.z) * inv;
  2077. max = (maximum.z - this.origin.z) * inv;
  2078. if (max === -Infinity) {
  2079. max = Infinity;
  2080. }
  2081. if (min > max) {
  2082. temp = min;
  2083. min = max;
  2084. max = temp;
  2085. }
  2086. d = Math.max(min, d);
  2087. maxValue = Math.min(max, maxValue);
  2088. if (d > maxValue) {
  2089. return false;
  2090. }
  2091. }
  2092. return true;
  2093. };
  2094. Ray.prototype.intersectsBox = function (box) {
  2095. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2096. };
  2097. Ray.prototype.intersectsSphere = function (sphere) {
  2098. var x = sphere.center.x - this.origin.x;
  2099. var y = sphere.center.y - this.origin.y;
  2100. var z = sphere.center.z - this.origin.z;
  2101. var pyth = (x * x) + (y * y) + (z * z);
  2102. var rr = sphere.radius * sphere.radius;
  2103. if (pyth <= rr) {
  2104. return true;
  2105. }
  2106. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2107. if (dot < 0.0) {
  2108. return false;
  2109. }
  2110. var temp = pyth - (dot * dot);
  2111. return temp <= rr;
  2112. };
  2113. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2114. if (!this._edge1) {
  2115. this._edge1 = Vector3.Zero();
  2116. this._edge2 = Vector3.Zero();
  2117. this._pvec = Vector3.Zero();
  2118. this._tvec = Vector3.Zero();
  2119. this._qvec = Vector3.Zero();
  2120. }
  2121. vertex1.subtractToRef(vertex0, this._edge1);
  2122. vertex2.subtractToRef(vertex0, this._edge2);
  2123. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2124. var det = Vector3.Dot(this._edge1, this._pvec);
  2125. if (det === 0) {
  2126. return null;
  2127. }
  2128. var invdet = 1 / det;
  2129. this.origin.subtractToRef(vertex0, this._tvec);
  2130. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2131. if (bu < 0 || bu > 1.0) {
  2132. return null;
  2133. }
  2134. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2135. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2136. if (bv < 0 || bu + bv > 1.0) {
  2137. return null;
  2138. }
  2139. //check if the distance is longer than the predefined length.
  2140. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2141. if (distance > this.length) {
  2142. return null;
  2143. }
  2144. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2145. };
  2146. // Statics
  2147. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2148. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2149. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2150. var direction = end.subtract(start);
  2151. direction.normalize();
  2152. return new Ray(start, direction);
  2153. };
  2154. /**
  2155. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2156. * transformed to the given world matrix.
  2157. * @param origin The origin point
  2158. * @param end The end point
  2159. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2160. */
  2161. Ray.CreateNewFromTo = function (origin, end, world) {
  2162. if (world === void 0) { world = Matrix.Identity(); }
  2163. var direction = end.subtract(origin);
  2164. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2165. direction.normalize();
  2166. return Ray.Transform(new Ray(origin, direction, length), world);
  2167. };
  2168. Ray.Transform = function (ray, matrix) {
  2169. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2170. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2171. return new Ray(newOrigin, newDirection, ray.length);
  2172. };
  2173. return Ray;
  2174. })();
  2175. BABYLON.Ray = Ray;
  2176. (function (Space) {
  2177. Space[Space["LOCAL"] = 0] = "LOCAL";
  2178. Space[Space["WORLD"] = 1] = "WORLD";
  2179. })(BABYLON.Space || (BABYLON.Space = {}));
  2180. var Space = BABYLON.Space;
  2181. var Axis = (function () {
  2182. function Axis() {
  2183. }
  2184. Axis.X = new Vector3(1, 0, 0);
  2185. Axis.Y = new Vector3(0, 1, 0);
  2186. Axis.Z = new Vector3(0, 0, 1);
  2187. return Axis;
  2188. })();
  2189. BABYLON.Axis = Axis;
  2190. ;
  2191. var BezierCurve = (function () {
  2192. function BezierCurve() {
  2193. }
  2194. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2195. // Extract X (which is equal to time here)
  2196. var f0 = 1 - 3 * x2 + 3 * x1;
  2197. var f1 = 3 * x2 - 6 * x1;
  2198. var f2 = 3 * x1;
  2199. var refinedT = t;
  2200. for (var i = 0; i < 5; i++) {
  2201. var refinedT2 = refinedT * refinedT;
  2202. var refinedT3 = refinedT2 * refinedT;
  2203. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2204. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2205. refinedT -= (x - t) * slope;
  2206. refinedT = Math.min(1, Math.max(0, refinedT));
  2207. }
  2208. // Resolve cubic bezier for the given x
  2209. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2210. };
  2211. return BezierCurve;
  2212. })();
  2213. BABYLON.BezierCurve = BezierCurve;
  2214. (function (Orientation) {
  2215. Orientation[Orientation["CW"] = 0] = "CW";
  2216. Orientation[Orientation["CCW"] = 1] = "CCW";
  2217. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2218. var Orientation = BABYLON.Orientation;
  2219. var Angle = (function () {
  2220. function Angle(radians) {
  2221. var _this = this;
  2222. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2223. this.radians = function () { return _this._radians; };
  2224. this._radians = radians;
  2225. if (this._radians < 0)
  2226. this._radians += (2 * Math.PI);
  2227. }
  2228. Angle.BetweenTwoPoints = function (a, b) {
  2229. var delta = b.subtract(a);
  2230. var theta = Math.atan2(delta.y, delta.x);
  2231. return new Angle(theta);
  2232. };
  2233. Angle.FromRadians = function (radians) {
  2234. return new Angle(radians);
  2235. };
  2236. Angle.FromDegrees = function (degrees) {
  2237. return new Angle(degrees * Math.PI / 180);
  2238. };
  2239. return Angle;
  2240. })();
  2241. BABYLON.Angle = Angle;
  2242. var Arc2 = (function () {
  2243. function Arc2(startPoint, midPoint, endPoint) {
  2244. this.startPoint = startPoint;
  2245. this.midPoint = midPoint;
  2246. this.endPoint = endPoint;
  2247. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2248. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2249. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2250. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2251. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2252. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2253. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2254. var a1 = this.startAngle.degrees();
  2255. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2256. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2257. // angles correction
  2258. if (a2 - a1 > +180.0)
  2259. a2 -= 360.0;
  2260. if (a2 - a1 < -180.0)
  2261. a2 += 360.0;
  2262. if (a3 - a2 > +180.0)
  2263. a3 -= 360.0;
  2264. if (a3 - a2 < -180.0)
  2265. a3 += 360.0;
  2266. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2267. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2268. }
  2269. return Arc2;
  2270. })();
  2271. BABYLON.Arc2 = Arc2;
  2272. var PathCursor = (function () {
  2273. function PathCursor(path) {
  2274. this.path = path;
  2275. this._onchange = new Array();
  2276. this.value = 0;
  2277. this.animations = new Array();
  2278. }
  2279. PathCursor.prototype.getPoint = function () {
  2280. var point = this.path.getPointAtLengthPosition(this.value);
  2281. return new Vector3(point.x, 0, point.y);
  2282. };
  2283. PathCursor.prototype.moveAhead = function (step) {
  2284. if (step === void 0) { step = 0.002; }
  2285. this.move(step);
  2286. return this;
  2287. };
  2288. PathCursor.prototype.moveBack = function (step) {
  2289. if (step === void 0) { step = 0.002; }
  2290. this.move(-step);
  2291. return this;
  2292. };
  2293. PathCursor.prototype.move = function (step) {
  2294. if (Math.abs(step) > 1) {
  2295. throw "step size should be less than 1.";
  2296. }
  2297. this.value += step;
  2298. this.ensureLimits();
  2299. this.raiseOnChange();
  2300. return this;
  2301. };
  2302. PathCursor.prototype.ensureLimits = function () {
  2303. while (this.value > 1) {
  2304. this.value -= 1;
  2305. }
  2306. while (this.value < 0) {
  2307. this.value += 1;
  2308. }
  2309. return this;
  2310. };
  2311. // used by animation engine
  2312. PathCursor.prototype.markAsDirty = function (propertyName) {
  2313. this.ensureLimits();
  2314. this.raiseOnChange();
  2315. return this;
  2316. };
  2317. PathCursor.prototype.raiseOnChange = function () {
  2318. var _this = this;
  2319. this._onchange.forEach(function (f) { return f(_this); });
  2320. return this;
  2321. };
  2322. PathCursor.prototype.onchange = function (f) {
  2323. this._onchange.push(f);
  2324. return this;
  2325. };
  2326. return PathCursor;
  2327. })();
  2328. BABYLON.PathCursor = PathCursor;
  2329. var Path2 = (function () {
  2330. function Path2(x, y) {
  2331. this._points = [];
  2332. this._length = 0;
  2333. this.closed = false;
  2334. this._points.push(new Vector2(x, y));
  2335. }
  2336. Path2.prototype.addLineTo = function (x, y) {
  2337. if (closed) {
  2338. BABYLON.Tools.Error("cannot add lines to closed paths");
  2339. return this;
  2340. }
  2341. var newPoint = new Vector2(x, y);
  2342. var previousPoint = this._points[this._points.length - 1];
  2343. this._points.push(newPoint);
  2344. this._length += newPoint.subtract(previousPoint).length();
  2345. return this;
  2346. };
  2347. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2348. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2349. if (closed) {
  2350. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2351. return this;
  2352. }
  2353. var startPoint = this._points[this._points.length - 1];
  2354. var midPoint = new Vector2(midX, midY);
  2355. var endPoint = new Vector2(endX, endY);
  2356. var arc = new Arc2(startPoint, midPoint, endPoint);
  2357. var increment = arc.angle.radians() / numberOfSegments;
  2358. if (arc.orientation === 0 /* CW */)
  2359. increment *= -1;
  2360. var currentAngle = arc.startAngle.radians() + increment;
  2361. for (var i = 0; i < numberOfSegments; i++) {
  2362. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2363. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2364. this.addLineTo(x, y);
  2365. currentAngle += increment;
  2366. }
  2367. return this;
  2368. };
  2369. Path2.prototype.close = function () {
  2370. this.closed = true;
  2371. return this;
  2372. };
  2373. Path2.prototype.length = function () {
  2374. var result = this._length;
  2375. if (!this.closed) {
  2376. var lastPoint = this._points[this._points.length - 1];
  2377. var firstPoint = this._points[0];
  2378. result += (firstPoint.subtract(lastPoint).length());
  2379. }
  2380. return result;
  2381. };
  2382. Path2.prototype.getPoints = function () {
  2383. return this._points;
  2384. };
  2385. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2386. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2387. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2388. return Vector2.Zero();
  2389. }
  2390. var lengthPosition = normalizedLengthPosition * this.length();
  2391. var previousOffset = 0;
  2392. for (var i = 0; i < this._points.length; i++) {
  2393. var j = (i + 1) % this._points.length;
  2394. var a = this._points[i];
  2395. var b = this._points[j];
  2396. var bToA = b.subtract(a);
  2397. var nextOffset = (bToA.length() + previousOffset);
  2398. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2399. var dir = bToA.normalize();
  2400. var localOffset = lengthPosition - previousOffset;
  2401. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2402. }
  2403. previousOffset = nextOffset;
  2404. }
  2405. BABYLON.Tools.Error("internal error");
  2406. return Vector2.Zero();
  2407. };
  2408. Path2.StartingAt = function (x, y) {
  2409. return new Path2(x, y);
  2410. };
  2411. return Path2;
  2412. })();
  2413. BABYLON.Path2 = Path2;
  2414. var Path3D = (function () {
  2415. function Path3D(path) {
  2416. this.path = path;
  2417. this._curve = [];
  2418. this._distances = [];
  2419. this._tangents = [];
  2420. this._normals = [];
  2421. this._binormals = [];
  2422. this._curve = path.slice(); // copy array
  2423. var l = this._curve.length;
  2424. // first and last tangents
  2425. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2426. this._tangents[0].normalize();
  2427. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2428. this._tangents[l - 1].normalize();
  2429. // normals and binormals at first point : arbitrary vector with _normalVector()
  2430. var tg0 = this._tangents[0];
  2431. var pp0 = this._normalVector(this._curve[0], tg0);
  2432. this._normals[0] = pp0;
  2433. this._normals[0].normalize();
  2434. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2435. this._normals[0].normalize();
  2436. this._distances[0] = 0;
  2437. // normals and binormals : next points
  2438. var prev; // previous vector (segment)
  2439. var cur; // current vector (segment)
  2440. var curTang; // current tangent
  2441. var prevNorm; // previous normal
  2442. var prevBinor; // previous binormal
  2443. for (var i = 1; i < l; i++) {
  2444. // tangents
  2445. prev = this._curve[i].subtract(this._curve[i - 1]);
  2446. if (i < l - 1) {
  2447. cur = this._curve[i + 1].subtract(this._curve[i]);
  2448. this._tangents[i] = prev.add(cur);
  2449. this._tangents[i].normalize();
  2450. }
  2451. this._distances[i] = this._distances[i - 1] + prev.length();
  2452. // normals and binormals
  2453. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2454. curTang = this._tangents[i];
  2455. prevNorm = this._normals[i - 1];
  2456. prevBinor = this._binormals[i - 1];
  2457. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2458. this._normals[i].normalize();
  2459. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2460. this._binormals[i].normalize();
  2461. }
  2462. }
  2463. Path3D.prototype.getCurve = function () {
  2464. return this._curve;
  2465. };
  2466. Path3D.prototype.getTangents = function () {
  2467. return this._tangents;
  2468. };
  2469. Path3D.prototype.getNormals = function () {
  2470. return this._normals;
  2471. };
  2472. Path3D.prototype.getBinormals = function () {
  2473. return this._binormals;
  2474. };
  2475. Path3D.prototype.getDistances = function () {
  2476. return this._distances;
  2477. };
  2478. // private function normalVector(v0, vt) :
  2479. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2480. Path3D.prototype._normalVector = function (v0, vt) {
  2481. var point;
  2482. if (vt.x !== 1) {
  2483. point = new Vector3(1, 0, 0);
  2484. }
  2485. else if (vt.y !== 1) {
  2486. point = new Vector3(0, 1, 0);
  2487. }
  2488. else if (vt.z !== 1) {
  2489. point = new Vector3(0, 0, 1);
  2490. }
  2491. var normal0 = Vector3.Cross(vt, point);
  2492. normal0.normalize();
  2493. return normal0;
  2494. };
  2495. return Path3D;
  2496. })();
  2497. BABYLON.Path3D = Path3D;
  2498. })(BABYLON || (BABYLON = {}));
  2499. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2500. (function (BABYLON) {
  2501. // Screenshots
  2502. var screenshotCanvas;
  2503. var cloneValue = function (source, destinationObject) {
  2504. if (!source)
  2505. return null;
  2506. if (source instanceof BABYLON.Mesh) {
  2507. return null;
  2508. }
  2509. if (source instanceof BABYLON.SubMesh) {
  2510. return source.clone(destinationObject);
  2511. }
  2512. else if (source.clone) {
  2513. return source.clone();
  2514. }
  2515. return null;
  2516. };
  2517. var Tools = (function () {
  2518. function Tools() {
  2519. }
  2520. Tools.GetFilename = function (path) {
  2521. var index = path.lastIndexOf("/");
  2522. if (index < 0)
  2523. return path;
  2524. return path.substring(index + 1);
  2525. };
  2526. Tools.GetDOMTextContent = function (element) {
  2527. var result = "";
  2528. var child = element.firstChild;
  2529. while (child) {
  2530. if (child.nodeType === 3) {
  2531. result += child.textContent;
  2532. }
  2533. child = child.nextSibling;
  2534. }
  2535. return result;
  2536. };
  2537. Tools.ToDegrees = function (angle) {
  2538. return angle * 180 / Math.PI;
  2539. };
  2540. Tools.ToRadians = function (angle) {
  2541. return angle * Math.PI / 180;
  2542. };
  2543. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2544. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2545. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2546. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2547. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2548. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2549. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2550. }
  2551. return {
  2552. minimum: minimum,
  2553. maximum: maximum
  2554. };
  2555. };
  2556. Tools.ExtractMinAndMax = function (positions, start, count) {
  2557. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2558. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2559. for (var index = start; index < start + count; index++) {
  2560. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2561. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2562. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2563. }
  2564. return {
  2565. minimum: minimum,
  2566. maximum: maximum
  2567. };
  2568. };
  2569. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2570. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2571. return undefined;
  2572. return Array.isArray(obj) ? obj : [obj];
  2573. };
  2574. // Misc.
  2575. Tools.GetPointerPrefix = function () {
  2576. var eventPrefix = "pointer";
  2577. // Check if hand.js is referenced or if the browser natively supports pointer events
  2578. if (!navigator.pointerEnabled) {
  2579. eventPrefix = "mouse";
  2580. }
  2581. return eventPrefix;
  2582. };
  2583. Tools.QueueNewFrame = function (func) {
  2584. if (window.requestAnimationFrame)
  2585. window.requestAnimationFrame(func);
  2586. else if (window.msRequestAnimationFrame)
  2587. window.msRequestAnimationFrame(func);
  2588. else if (window.webkitRequestAnimationFrame)
  2589. window.webkitRequestAnimationFrame(func);
  2590. else if (window.mozRequestAnimationFrame)
  2591. window.mozRequestAnimationFrame(func);
  2592. else if (window.oRequestAnimationFrame)
  2593. window.oRequestAnimationFrame(func);
  2594. else {
  2595. window.setTimeout(func, 16);
  2596. }
  2597. };
  2598. Tools.RequestFullscreen = function (element) {
  2599. if (element.requestFullscreen)
  2600. element.requestFullscreen();
  2601. else if (element.msRequestFullscreen)
  2602. element.msRequestFullscreen();
  2603. else if (element.webkitRequestFullscreen)
  2604. element.webkitRequestFullscreen();
  2605. else if (element.mozRequestFullScreen)
  2606. element.mozRequestFullScreen();
  2607. };
  2608. Tools.ExitFullscreen = function () {
  2609. if (document.exitFullscreen) {
  2610. document.exitFullscreen();
  2611. }
  2612. else if (document.mozCancelFullScreen) {
  2613. document.mozCancelFullScreen();
  2614. }
  2615. else if (document.webkitCancelFullScreen) {
  2616. document.webkitCancelFullScreen();
  2617. }
  2618. else if (document.msCancelFullScreen) {
  2619. document.msCancelFullScreen();
  2620. }
  2621. };
  2622. // External files
  2623. Tools.CleanUrl = function (url) {
  2624. url = url.replace(/#/mg, "%23");
  2625. return url;
  2626. };
  2627. Tools.LoadImage = function (url, onload, onerror, database) {
  2628. url = Tools.CleanUrl(url);
  2629. var img = new Image();
  2630. if (url.substr(0, 5) !== "data:")
  2631. img.crossOrigin = 'anonymous';
  2632. img.onload = function () {
  2633. onload(img);
  2634. };
  2635. img.onerror = function (err) {
  2636. onerror(img, err);
  2637. };
  2638. var noIndexedDB = function () {
  2639. img.src = url;
  2640. };
  2641. var loadFromIndexedDB = function () {
  2642. database.loadImageFromDB(url, img);
  2643. };
  2644. //ANY database to do!
  2645. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2646. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2647. }
  2648. else {
  2649. if (url.indexOf("file:") === -1) {
  2650. noIndexedDB();
  2651. }
  2652. else {
  2653. try {
  2654. var textureName = url.substring(5);
  2655. var blobURL;
  2656. try {
  2657. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2658. }
  2659. catch (ex) {
  2660. // Chrome doesn't support oneTimeOnly parameter
  2661. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2662. }
  2663. img.src = blobURL;
  2664. }
  2665. catch (e) {
  2666. Tools.Log("Error while trying to load texture: " + textureName);
  2667. img.src = null;
  2668. }
  2669. }
  2670. }
  2671. return img;
  2672. };
  2673. //ANY
  2674. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2675. url = Tools.CleanUrl(url);
  2676. var noIndexedDB = function () {
  2677. var request = new XMLHttpRequest();
  2678. var loadUrl = Tools.BaseUrl + url;
  2679. request.open('GET', loadUrl, true);
  2680. if (useArrayBuffer) {
  2681. request.responseType = "arraybuffer";
  2682. }
  2683. request.onprogress = progressCallBack;
  2684. request.onreadystatechange = function () {
  2685. if (request.readyState === 4) {
  2686. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2687. callback(!useArrayBuffer ? request.responseText : request.response);
  2688. }
  2689. else {
  2690. if (onError) {
  2691. onError();
  2692. }
  2693. else {
  2694. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2695. }
  2696. }
  2697. }
  2698. };
  2699. request.send(null);
  2700. };
  2701. var loadFromIndexedDB = function () {
  2702. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2703. };
  2704. if (url.indexOf("file:") !== -1) {
  2705. var fileName = url.substring(5);
  2706. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2707. }
  2708. else {
  2709. // Caching all files
  2710. if (database && database.enableSceneOffline) {
  2711. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2712. }
  2713. else {
  2714. noIndexedDB();
  2715. }
  2716. }
  2717. };
  2718. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2719. var reader = new FileReader();
  2720. reader.onload = function (e) {
  2721. //target doesn't have result from ts 1.3
  2722. callback(e.target['result']);
  2723. };
  2724. reader.onprogress = progressCallback;
  2725. reader.readAsDataURL(fileToLoad);
  2726. };
  2727. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2728. var reader = new FileReader();
  2729. reader.onerror = function (e) {
  2730. Tools.Log("Error while reading file: " + fileToLoad.name);
  2731. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  2732. };
  2733. reader.onload = function (e) {
  2734. //target doesn't have result from ts 1.3
  2735. callback(e.target['result']);
  2736. };
  2737. reader.onprogress = progressCallBack;
  2738. if (!useArrayBuffer) {
  2739. // Asynchronous read
  2740. reader.readAsText(fileToLoad);
  2741. }
  2742. else {
  2743. reader.readAsArrayBuffer(fileToLoad);
  2744. }
  2745. };
  2746. // Misc.
  2747. Tools.Clamp = function (value, min, max) {
  2748. if (min === void 0) { min = 0; }
  2749. if (max === void 0) { max = 1; }
  2750. return Math.min(max, Math.max(min, value));
  2751. };
  2752. // Returns -1 when value is a negative number and
  2753. // +1 when value is a positive number.
  2754. Tools.Sign = function (value) {
  2755. value = +value; // convert to a number
  2756. if (value === 0 || isNaN(value))
  2757. return value;
  2758. return value > 0 ? 1 : -1;
  2759. };
  2760. Tools.Format = function (value, decimals) {
  2761. if (decimals === void 0) { decimals = 2; }
  2762. return value.toFixed(decimals);
  2763. };
  2764. Tools.CheckExtends = function (v, min, max) {
  2765. if (v.x < min.x)
  2766. min.x = v.x;
  2767. if (v.y < min.y)
  2768. min.y = v.y;
  2769. if (v.z < min.z)
  2770. min.z = v.z;
  2771. if (v.x > max.x)
  2772. max.x = v.x;
  2773. if (v.y > max.y)
  2774. max.y = v.y;
  2775. if (v.z > max.z)
  2776. max.z = v.z;
  2777. };
  2778. Tools.WithinEpsilon = function (a, b, epsilon) {
  2779. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2780. var num = a - b;
  2781. return -epsilon <= num && num <= epsilon;
  2782. };
  2783. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2784. for (var prop in source) {
  2785. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2786. continue;
  2787. }
  2788. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2789. continue;
  2790. }
  2791. var sourceValue = source[prop];
  2792. var typeOfSourceValue = typeof sourceValue;
  2793. if (typeOfSourceValue === "function") {
  2794. continue;
  2795. }
  2796. if (typeOfSourceValue === "object") {
  2797. if (sourceValue instanceof Array) {
  2798. destination[prop] = [];
  2799. if (sourceValue.length > 0) {
  2800. if (typeof sourceValue[0] == "object") {
  2801. for (var index = 0; index < sourceValue.length; index++) {
  2802. var clonedValue = cloneValue(sourceValue[index], destination);
  2803. if (destination[prop].indexOf(clonedValue) === -1) {
  2804. destination[prop].push(clonedValue);
  2805. }
  2806. }
  2807. }
  2808. else {
  2809. destination[prop] = sourceValue.slice(0);
  2810. }
  2811. }
  2812. }
  2813. else {
  2814. destination[prop] = cloneValue(sourceValue, destination);
  2815. }
  2816. }
  2817. else {
  2818. destination[prop] = sourceValue;
  2819. }
  2820. }
  2821. };
  2822. Tools.IsEmpty = function (obj) {
  2823. for (var i in obj) {
  2824. return false;
  2825. }
  2826. return true;
  2827. };
  2828. Tools.RegisterTopRootEvents = function (events) {
  2829. for (var index = 0; index < events.length; index++) {
  2830. var event = events[index];
  2831. window.addEventListener(event.name, event.handler, false);
  2832. try {
  2833. if (window.parent) {
  2834. window.parent.addEventListener(event.name, event.handler, false);
  2835. }
  2836. }
  2837. catch (e) {
  2838. }
  2839. }
  2840. };
  2841. Tools.UnregisterTopRootEvents = function (events) {
  2842. for (var index = 0; index < events.length; index++) {
  2843. var event = events[index];
  2844. window.removeEventListener(event.name, event.handler);
  2845. try {
  2846. if (window.parent) {
  2847. window.parent.removeEventListener(event.name, event.handler);
  2848. }
  2849. }
  2850. catch (e) {
  2851. }
  2852. }
  2853. };
  2854. Tools.DumpFramebuffer = function (width, height, engine) {
  2855. // Read the contents of the framebuffer
  2856. var numberOfChannelsByLine = width * 4;
  2857. var halfHeight = height / 2;
  2858. //Reading datas from WebGL
  2859. var data = engine.readPixels(0, 0, width, height);
  2860. for (var i = 0; i < halfHeight; i++) {
  2861. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2862. var currentCell = j + i * numberOfChannelsByLine;
  2863. var targetLine = height - i - 1;
  2864. var targetCell = j + targetLine * numberOfChannelsByLine;
  2865. var temp = data[currentCell];
  2866. data[currentCell] = data[targetCell];
  2867. data[targetCell] = temp;
  2868. }
  2869. }
  2870. // Create a 2D canvas to store the result
  2871. if (!screenshotCanvas) {
  2872. screenshotCanvas = document.createElement('canvas');
  2873. }
  2874. screenshotCanvas.width = width;
  2875. screenshotCanvas.height = height;
  2876. var context = screenshotCanvas.getContext('2d');
  2877. // Copy the pixels to a 2D canvas
  2878. var imageData = context.createImageData(width, height);
  2879. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2880. var castData = imageData.data;
  2881. castData.set(data);
  2882. context.putImageData(imageData, 0, 0);
  2883. var base64Image = screenshotCanvas.toDataURL();
  2884. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2885. if (("download" in document.createElement("a"))) {
  2886. var a = window.document.createElement("a");
  2887. a.href = base64Image;
  2888. var date = new Date();
  2889. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2890. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2891. window.document.body.appendChild(a);
  2892. a.addEventListener("click", function () {
  2893. a.parentElement.removeChild(a);
  2894. });
  2895. a.click();
  2896. }
  2897. else {
  2898. var newWindow = window.open("");
  2899. var img = newWindow.document.createElement("img");
  2900. img.src = base64Image;
  2901. newWindow.document.body.appendChild(img);
  2902. }
  2903. };
  2904. Tools.CreateScreenshot = function (engine, camera, size) {
  2905. var width;
  2906. var height;
  2907. var scene = camera.getScene();
  2908. var previousCamera = null;
  2909. if (scene.activeCamera !== camera) {
  2910. previousCamera = scene.activeCamera;
  2911. scene.activeCamera = camera;
  2912. }
  2913. //If a precision value is specified
  2914. if (size.precision) {
  2915. width = Math.round(engine.getRenderWidth() * size.precision);
  2916. height = Math.round(width / engine.getAspectRatio(camera));
  2917. size = { width: width, height: height };
  2918. }
  2919. else if (size.width && size.height) {
  2920. width = size.width;
  2921. height = size.height;
  2922. }
  2923. else if (size.width && !size.height) {
  2924. width = size.width;
  2925. height = Math.round(width / engine.getAspectRatio(camera));
  2926. size = { width: width, height: height };
  2927. }
  2928. else if (size.height && !size.width) {
  2929. height = size.height;
  2930. width = Math.round(height * engine.getAspectRatio(camera));
  2931. size = { width: width, height: height };
  2932. }
  2933. else if (!isNaN(size)) {
  2934. height = size;
  2935. width = size;
  2936. }
  2937. else {
  2938. Tools.Error("Invalid 'size' parameter !");
  2939. return;
  2940. }
  2941. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2942. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2943. texture.renderList = scene.meshes;
  2944. texture.onAfterRender = function () {
  2945. Tools.DumpFramebuffer(width, height, engine);
  2946. };
  2947. scene.incrementRenderId();
  2948. texture.render(true);
  2949. texture.dispose();
  2950. if (previousCamera) {
  2951. scene.activeCamera = previousCamera;
  2952. }
  2953. };
  2954. // XHR response validator for local file scenario
  2955. Tools.ValidateXHRData = function (xhr, dataType) {
  2956. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2957. if (dataType === void 0) { dataType = 7; }
  2958. try {
  2959. if (dataType & 1) {
  2960. if (xhr.responseText && xhr.responseText.length > 0) {
  2961. return true;
  2962. }
  2963. else if (dataType === 1) {
  2964. return false;
  2965. }
  2966. }
  2967. if (dataType & 2) {
  2968. // Check header width and height since there is no "TGA" magic number
  2969. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2970. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2971. return true;
  2972. }
  2973. else if (dataType === 2) {
  2974. return false;
  2975. }
  2976. }
  2977. if (dataType & 4) {
  2978. // Check for the "DDS" magic number
  2979. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2980. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2981. return true;
  2982. }
  2983. else {
  2984. return false;
  2985. }
  2986. }
  2987. }
  2988. catch (e) {
  2989. }
  2990. return false;
  2991. };
  2992. Object.defineProperty(Tools, "NoneLogLevel", {
  2993. get: function () {
  2994. return Tools._NoneLogLevel;
  2995. },
  2996. enumerable: true,
  2997. configurable: true
  2998. });
  2999. Object.defineProperty(Tools, "MessageLogLevel", {
  3000. get: function () {
  3001. return Tools._MessageLogLevel;
  3002. },
  3003. enumerable: true,
  3004. configurable: true
  3005. });
  3006. Object.defineProperty(Tools, "WarningLogLevel", {
  3007. get: function () {
  3008. return Tools._WarningLogLevel;
  3009. },
  3010. enumerable: true,
  3011. configurable: true
  3012. });
  3013. Object.defineProperty(Tools, "ErrorLogLevel", {
  3014. get: function () {
  3015. return Tools._ErrorLogLevel;
  3016. },
  3017. enumerable: true,
  3018. configurable: true
  3019. });
  3020. Object.defineProperty(Tools, "AllLogLevel", {
  3021. get: function () {
  3022. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3023. },
  3024. enumerable: true,
  3025. configurable: true
  3026. });
  3027. Tools._AddLogEntry = function (entry) {
  3028. Tools._LogCache = entry + Tools._LogCache;
  3029. if (Tools.OnNewCacheEntry) {
  3030. Tools.OnNewCacheEntry(entry);
  3031. }
  3032. };
  3033. Tools._FormatMessage = function (message) {
  3034. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3035. var date = new Date();
  3036. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3037. };
  3038. Tools._LogDisabled = function (message) {
  3039. // nothing to do
  3040. };
  3041. Tools._LogEnabled = function (message) {
  3042. var formattedMessage = Tools._FormatMessage(message);
  3043. console.log("BJS - " + formattedMessage);
  3044. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3045. Tools._AddLogEntry(entry);
  3046. };
  3047. Tools._WarnDisabled = function (message) {
  3048. // nothing to do
  3049. };
  3050. Tools._WarnEnabled = function (message) {
  3051. var formattedMessage = Tools._FormatMessage(message);
  3052. console.warn("BJS - " + formattedMessage);
  3053. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3054. Tools._AddLogEntry(entry);
  3055. };
  3056. Tools._ErrorDisabled = function (message) {
  3057. // nothing to do
  3058. };
  3059. Tools._ErrorEnabled = function (message) {
  3060. var formattedMessage = Tools._FormatMessage(message);
  3061. console.error("BJS - " + formattedMessage);
  3062. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3063. Tools._AddLogEntry(entry);
  3064. };
  3065. Object.defineProperty(Tools, "LogCache", {
  3066. get: function () {
  3067. return Tools._LogCache;
  3068. },
  3069. enumerable: true,
  3070. configurable: true
  3071. });
  3072. Object.defineProperty(Tools, "LogLevels", {
  3073. set: function (level) {
  3074. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3075. Tools.Log = Tools._LogEnabled;
  3076. }
  3077. else {
  3078. Tools.Log = Tools._LogDisabled;
  3079. }
  3080. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3081. Tools.Warn = Tools._WarnEnabled;
  3082. }
  3083. else {
  3084. Tools.Warn = Tools._WarnDisabled;
  3085. }
  3086. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3087. Tools.Error = Tools._ErrorEnabled;
  3088. }
  3089. else {
  3090. Tools.Error = Tools._ErrorDisabled;
  3091. }
  3092. },
  3093. enumerable: true,
  3094. configurable: true
  3095. });
  3096. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3097. get: function () {
  3098. return Tools._PerformanceNoneLogLevel;
  3099. },
  3100. enumerable: true,
  3101. configurable: true
  3102. });
  3103. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3104. get: function () {
  3105. return Tools._PerformanceUserMarkLogLevel;
  3106. },
  3107. enumerable: true,
  3108. configurable: true
  3109. });
  3110. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3111. get: function () {
  3112. return Tools._PerformanceConsoleLogLevel;
  3113. },
  3114. enumerable: true,
  3115. configurable: true
  3116. });
  3117. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3118. set: function (level) {
  3119. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3120. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3121. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3122. return;
  3123. }
  3124. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3125. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3126. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3127. return;
  3128. }
  3129. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3130. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3131. },
  3132. enumerable: true,
  3133. configurable: true
  3134. });
  3135. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3136. };
  3137. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3138. };
  3139. Tools._StartUserMark = function (counterName, condition) {
  3140. if (condition === void 0) { condition = true; }
  3141. if (!condition || !Tools._performance.mark) {
  3142. return;
  3143. }
  3144. Tools._performance.mark(counterName + "-Begin");
  3145. };
  3146. Tools._EndUserMark = function (counterName, condition) {
  3147. if (condition === void 0) { condition = true; }
  3148. if (!condition || !Tools._performance.mark) {
  3149. return;
  3150. }
  3151. Tools._performance.mark(counterName + "-End");
  3152. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3153. };
  3154. Tools._StartPerformanceConsole = function (counterName, condition) {
  3155. if (condition === void 0) { condition = true; }
  3156. if (!condition) {
  3157. return;
  3158. }
  3159. Tools._StartUserMark(counterName, condition);
  3160. if (console.time) {
  3161. console.time(counterName);
  3162. }
  3163. };
  3164. Tools._EndPerformanceConsole = function (counterName, condition) {
  3165. if (condition === void 0) { condition = true; }
  3166. if (!condition) {
  3167. return;
  3168. }
  3169. Tools._EndUserMark(counterName, condition);
  3170. if (console.time) {
  3171. console.timeEnd(counterName);
  3172. }
  3173. };
  3174. Object.defineProperty(Tools, "Now", {
  3175. get: function () {
  3176. if (window.performance && window.performance.now) {
  3177. return window.performance.now();
  3178. }
  3179. return new Date().getTime();
  3180. },
  3181. enumerable: true,
  3182. configurable: true
  3183. });
  3184. // Deprecated
  3185. Tools.GetFps = function () {
  3186. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3187. return 0;
  3188. };
  3189. Tools.BaseUrl = "";
  3190. Tools.GetExponantOfTwo = function (value, max) {
  3191. var count = 1;
  3192. do {
  3193. count *= 2;
  3194. } while (count < value);
  3195. if (count > max)
  3196. count = max;
  3197. return count;
  3198. };
  3199. // Logs
  3200. Tools._NoneLogLevel = 0;
  3201. Tools._MessageLogLevel = 1;
  3202. Tools._WarningLogLevel = 2;
  3203. Tools._ErrorLogLevel = 4;
  3204. Tools._LogCache = "";
  3205. Tools.Log = Tools._LogEnabled;
  3206. Tools.Warn = Tools._WarnEnabled;
  3207. Tools.Error = Tools._ErrorEnabled;
  3208. // Performances
  3209. Tools._PerformanceNoneLogLevel = 0;
  3210. Tools._PerformanceUserMarkLogLevel = 1;
  3211. Tools._PerformanceConsoleLogLevel = 2;
  3212. Tools._performance = window.performance;
  3213. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3214. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3215. return Tools;
  3216. })();
  3217. BABYLON.Tools = Tools;
  3218. /**
  3219. * An implementation of a loop for asynchronous functions.
  3220. */
  3221. var AsyncLoop = (function () {
  3222. /**
  3223. * Constroctor.
  3224. * @param iterations the number of iterations.
  3225. * @param _fn the function to run each iteration
  3226. * @param _successCallback the callback that will be called upon succesful execution
  3227. * @param offset starting offset.
  3228. */
  3229. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3230. if (offset === void 0) { offset = 0; }
  3231. this.iterations = iterations;
  3232. this._fn = _fn;
  3233. this._successCallback = _successCallback;
  3234. this.index = offset - 1;
  3235. this._done = false;
  3236. }
  3237. /**
  3238. * Execute the next iteration. Must be called after the last iteration was finished.
  3239. */
  3240. AsyncLoop.prototype.executeNext = function () {
  3241. if (!this._done) {
  3242. if (this.index + 1 < this.iterations) {
  3243. ++this.index;
  3244. this._fn(this);
  3245. }
  3246. else {
  3247. this.breakLoop();
  3248. }
  3249. }
  3250. };
  3251. /**
  3252. * Break the loop and run the success callback.
  3253. */
  3254. AsyncLoop.prototype.breakLoop = function () {
  3255. this._done = true;
  3256. this._successCallback();
  3257. };
  3258. /**
  3259. * Helper function
  3260. */
  3261. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3262. if (offset === void 0) { offset = 0; }
  3263. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3264. loop.executeNext();
  3265. return loop;
  3266. };
  3267. /**
  3268. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3269. * @param iterations total number of iterations
  3270. * @param syncedIterations number of synchronous iterations in each async iteration.
  3271. * @param fn the function to call each iteration.
  3272. * @param callback a success call back that will be called when iterating stops.
  3273. * @param breakFunction a break condition (optional)
  3274. * @param timeout timeout settings for the setTimeout function. default - 0.
  3275. * @constructor
  3276. */
  3277. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3278. if (timeout === void 0) { timeout = 0; }
  3279. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3280. if (breakFunction && breakFunction())
  3281. loop.breakLoop();
  3282. else {
  3283. setTimeout(function () {
  3284. for (var i = 0; i < syncedIterations; ++i) {
  3285. var iteration = (loop.index * syncedIterations) + i;
  3286. if (iteration >= iterations)
  3287. break;
  3288. fn(iteration);
  3289. if (breakFunction && breakFunction()) {
  3290. loop.breakLoop();
  3291. break;
  3292. }
  3293. }
  3294. loop.executeNext();
  3295. }, timeout);
  3296. }
  3297. }, callback);
  3298. };
  3299. return AsyncLoop;
  3300. })();
  3301. BABYLON.AsyncLoop = AsyncLoop;
  3302. })(BABYLON || (BABYLON = {}));
  3303. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3304. (function (BABYLON) {
  3305. var _DepthCullingState = (function () {
  3306. function _DepthCullingState() {
  3307. this._isDepthTestDirty = false;
  3308. this._isDepthMaskDirty = false;
  3309. this._isDepthFuncDirty = false;
  3310. this._isCullFaceDirty = false;
  3311. this._isCullDirty = false;
  3312. }
  3313. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3314. get: function () {
  3315. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3316. },
  3317. enumerable: true,
  3318. configurable: true
  3319. });
  3320. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3321. get: function () {
  3322. return this._cullFace;
  3323. },
  3324. set: function (value) {
  3325. if (this._cullFace === value) {
  3326. return;
  3327. }
  3328. this._cullFace = value;
  3329. this._isCullFaceDirty = true;
  3330. },
  3331. enumerable: true,
  3332. configurable: true
  3333. });
  3334. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3335. get: function () {
  3336. return this._cull;
  3337. },
  3338. set: function (value) {
  3339. if (this._cull === value) {
  3340. return;
  3341. }
  3342. this._cull = value;
  3343. this._isCullDirty = true;
  3344. },
  3345. enumerable: true,
  3346. configurable: true
  3347. });
  3348. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3349. get: function () {
  3350. return this._depthFunc;
  3351. },
  3352. set: function (value) {
  3353. if (this._depthFunc === value) {
  3354. return;
  3355. }
  3356. this._depthFunc = value;
  3357. this._isDepthFuncDirty = true;
  3358. },
  3359. enumerable: true,
  3360. configurable: true
  3361. });
  3362. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3363. get: function () {
  3364. return this._depthMask;
  3365. },
  3366. set: function (value) {
  3367. if (this._depthMask === value) {
  3368. return;
  3369. }
  3370. this._depthMask = value;
  3371. this._isDepthMaskDirty = true;
  3372. },
  3373. enumerable: true,
  3374. configurable: true
  3375. });
  3376. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3377. get: function () {
  3378. return this._depthTest;
  3379. },
  3380. set: function (value) {
  3381. if (this._depthTest === value) {
  3382. return;
  3383. }
  3384. this._depthTest = value;
  3385. this._isDepthTestDirty = true;
  3386. },
  3387. enumerable: true,
  3388. configurable: true
  3389. });
  3390. _DepthCullingState.prototype.reset = function () {
  3391. this._depthMask = true;
  3392. this._depthTest = true;
  3393. this._depthFunc = null;
  3394. this._cull = null;
  3395. this._cullFace = null;
  3396. this._isDepthTestDirty = true;
  3397. this._isDepthMaskDirty = true;
  3398. this._isDepthFuncDirty = false;
  3399. this._isCullFaceDirty = false;
  3400. this._isCullDirty = false;
  3401. };
  3402. _DepthCullingState.prototype.apply = function (gl) {
  3403. if (!this.isDirty) {
  3404. return;
  3405. }
  3406. // Cull
  3407. if (this._isCullDirty) {
  3408. if (this.cull) {
  3409. gl.enable(gl.CULL_FACE);
  3410. }
  3411. else {
  3412. gl.disable(gl.CULL_FACE);
  3413. }
  3414. this._isCullDirty = false;
  3415. }
  3416. // Cull face
  3417. if (this._isCullFaceDirty) {
  3418. gl.cullFace(this.cullFace);
  3419. this._isCullFaceDirty = false;
  3420. }
  3421. // Depth mask
  3422. if (this._isDepthMaskDirty) {
  3423. gl.depthMask(this.depthMask);
  3424. this._isDepthMaskDirty = false;
  3425. }
  3426. // Depth test
  3427. if (this._isDepthTestDirty) {
  3428. if (this.depthTest) {
  3429. gl.enable(gl.DEPTH_TEST);
  3430. }
  3431. else {
  3432. gl.disable(gl.DEPTH_TEST);
  3433. }
  3434. this._isDepthTestDirty = false;
  3435. }
  3436. // Depth func
  3437. if (this._isDepthFuncDirty) {
  3438. gl.depthFunc(this.depthFunc);
  3439. this._isDepthFuncDirty = false;
  3440. }
  3441. };
  3442. return _DepthCullingState;
  3443. })();
  3444. BABYLON._DepthCullingState = _DepthCullingState;
  3445. var _AlphaState = (function () {
  3446. function _AlphaState() {
  3447. this._isAlphaBlendDirty = false;
  3448. this._isBlendFunctionParametersDirty = false;
  3449. this._alphaBlend = false;
  3450. this._blendFunctionParameters = new Array(4);
  3451. }
  3452. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3453. get: function () {
  3454. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3455. },
  3456. enumerable: true,
  3457. configurable: true
  3458. });
  3459. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3460. get: function () {
  3461. return this._alphaBlend;
  3462. },
  3463. set: function (value) {
  3464. if (this._alphaBlend === value) {
  3465. return;
  3466. }
  3467. this._alphaBlend = value;
  3468. this._isAlphaBlendDirty = true;
  3469. },
  3470. enumerable: true,
  3471. configurable: true
  3472. });
  3473. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3474. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3475. return;
  3476. }
  3477. this._blendFunctionParameters[0] = value0;
  3478. this._blendFunctionParameters[1] = value1;
  3479. this._blendFunctionParameters[2] = value2;
  3480. this._blendFunctionParameters[3] = value3;
  3481. this._isBlendFunctionParametersDirty = true;
  3482. };
  3483. _AlphaState.prototype.reset = function () {
  3484. this._alphaBlend = false;
  3485. this._blendFunctionParameters[0] = null;
  3486. this._blendFunctionParameters[1] = null;
  3487. this._blendFunctionParameters[2] = null;
  3488. this._blendFunctionParameters[3] = null;
  3489. this._isAlphaBlendDirty = true;
  3490. this._isBlendFunctionParametersDirty = false;
  3491. };
  3492. _AlphaState.prototype.apply = function (gl) {
  3493. if (!this.isDirty) {
  3494. return;
  3495. }
  3496. // Alpha blend
  3497. if (this._isAlphaBlendDirty) {
  3498. if (this._alphaBlend) {
  3499. gl.enable(gl.BLEND);
  3500. }
  3501. else {
  3502. gl.disable(gl.BLEND);
  3503. }
  3504. this._isAlphaBlendDirty = false;
  3505. }
  3506. // Alpha function
  3507. if (this._isBlendFunctionParametersDirty) {
  3508. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3509. this._isBlendFunctionParametersDirty = false;
  3510. }
  3511. };
  3512. return _AlphaState;
  3513. })();
  3514. BABYLON._AlphaState = _AlphaState;
  3515. var compileShader = function (gl, source, type, defines) {
  3516. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3517. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3518. gl.compileShader(shader);
  3519. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3520. throw new Error(gl.getShaderInfoLog(shader));
  3521. }
  3522. return shader;
  3523. };
  3524. var getWebGLTextureType = function (gl, type) {
  3525. var textureType = gl.UNSIGNED_BYTE;
  3526. if (type === Engine.TEXTURETYPE_FLOAT)
  3527. textureType = gl.FLOAT;
  3528. return textureType;
  3529. };
  3530. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3531. var magFilter = gl.NEAREST;
  3532. var minFilter = gl.NEAREST;
  3533. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3534. magFilter = gl.LINEAR;
  3535. if (generateMipMaps) {
  3536. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3537. }
  3538. else {
  3539. minFilter = gl.LINEAR;
  3540. }
  3541. }
  3542. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3543. magFilter = gl.LINEAR;
  3544. if (generateMipMaps) {
  3545. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3546. }
  3547. else {
  3548. minFilter = gl.LINEAR;
  3549. }
  3550. }
  3551. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3552. magFilter = gl.NEAREST;
  3553. if (generateMipMaps) {
  3554. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3555. }
  3556. else {
  3557. minFilter = gl.NEAREST;
  3558. }
  3559. }
  3560. return {
  3561. min: minFilter,
  3562. mag: magFilter
  3563. };
  3564. };
  3565. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3567. var engine = scene.getEngine();
  3568. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3569. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3570. gl.bindTexture(gl.TEXTURE_2D, texture);
  3571. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3572. processFunction(potWidth, potHeight);
  3573. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3576. if (!noMipmap && !isCompressed) {
  3577. gl.generateMipmap(gl.TEXTURE_2D);
  3578. }
  3579. gl.bindTexture(gl.TEXTURE_2D, null);
  3580. engine._activeTexturesCache = [];
  3581. texture._baseWidth = width;
  3582. texture._baseHeight = height;
  3583. texture._width = potWidth;
  3584. texture._height = potHeight;
  3585. texture.isReady = true;
  3586. texture.samplingMode = samplingMode;
  3587. scene._removePendingData(texture);
  3588. };
  3589. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3590. var onload = function () {
  3591. loadedImages[index] = img;
  3592. loadedImages._internalCount++;
  3593. scene._removePendingData(img);
  3594. if (loadedImages._internalCount === 6) {
  3595. onfinish(loadedImages);
  3596. }
  3597. };
  3598. var onerror = function () {
  3599. scene._removePendingData(img);
  3600. };
  3601. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3602. scene._addPendingData(img);
  3603. };
  3604. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3605. var loadedImages = [];
  3606. loadedImages._internalCount = 0;
  3607. for (var index = 0; index < 6; index++) {
  3608. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3609. }
  3610. };
  3611. var EngineCapabilities = (function () {
  3612. function EngineCapabilities() {
  3613. }
  3614. return EngineCapabilities;
  3615. })();
  3616. BABYLON.EngineCapabilities = EngineCapabilities;
  3617. /**
  3618. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3619. */
  3620. var Engine = (function () {
  3621. /**
  3622. * @constructor
  3623. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3624. * @param {boolean} [antialias] - enable antialias
  3625. * @param options - further options to be sent to the getContext function
  3626. */
  3627. function Engine(canvas, antialias, options) {
  3628. var _this = this;
  3629. // Public members
  3630. this.isFullscreen = false;
  3631. this.isPointerLock = false;
  3632. this.cullBackFaces = true;
  3633. this.renderEvenInBackground = true;
  3634. this.scenes = new Array();
  3635. this._windowIsBackground = false;
  3636. this._loadingDivBackgroundColor = "black";
  3637. this._drawCalls = 0;
  3638. this._renderingQueueLaunched = false;
  3639. this._activeRenderLoops = [];
  3640. // FPS
  3641. this.fpsRange = 60;
  3642. this.previousFramesDuration = [];
  3643. this.fps = 60;
  3644. this.deltaTime = 0;
  3645. // States
  3646. this._depthCullingState = new _DepthCullingState();
  3647. this._alphaState = new _AlphaState();
  3648. this._alphaMode = Engine.ALPHA_DISABLE;
  3649. // Cache
  3650. this._loadedTexturesCache = new Array();
  3651. this._activeTexturesCache = new Array();
  3652. this._compiledEffects = {};
  3653. this._uintIndicesCurrentlySet = false;
  3654. this._renderingCanvas = canvas;
  3655. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3656. options = options || {};
  3657. options.antialias = antialias;
  3658. try {
  3659. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3660. }
  3661. catch (e) {
  3662. throw new Error("WebGL not supported");
  3663. }
  3664. if (!this._gl) {
  3665. throw new Error("WebGL not supported");
  3666. }
  3667. this._onBlur = function () {
  3668. _this._windowIsBackground = true;
  3669. };
  3670. this._onFocus = function () {
  3671. _this._windowIsBackground = false;
  3672. };
  3673. window.addEventListener("blur", this._onBlur);
  3674. window.addEventListener("focus", this._onFocus);
  3675. // Textures
  3676. this._workingCanvas = document.createElement("canvas");
  3677. this._workingContext = this._workingCanvas.getContext("2d");
  3678. // Viewport
  3679. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3680. this.resize();
  3681. // Caps
  3682. this._caps = new EngineCapabilities();
  3683. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3684. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3685. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3686. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3687. // Infos
  3688. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3689. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3690. if (rendererInfo != null) {
  3691. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3692. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3693. }
  3694. if (!this._glVendor) {
  3695. this._glVendor = "Unknown vendor";
  3696. }
  3697. if (!this._glRenderer) {
  3698. this._glRenderer = "Unknown renderer";
  3699. }
  3700. // Extensions
  3701. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3702. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3703. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3704. 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');
  3705. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3706. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3707. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3708. // Depth buffer
  3709. this.setDepthBuffer(true);
  3710. this.setDepthFunctionToLessOrEqual();
  3711. this.setDepthWrite(true);
  3712. // Fullscreen
  3713. this._onFullscreenChange = function () {
  3714. if (document.fullscreen !== undefined) {
  3715. _this.isFullscreen = document.fullscreen;
  3716. }
  3717. else if (document.mozFullScreen !== undefined) {
  3718. _this.isFullscreen = document.mozFullScreen;
  3719. }
  3720. else if (document.webkitIsFullScreen !== undefined) {
  3721. _this.isFullscreen = document.webkitIsFullScreen;
  3722. }
  3723. else if (document.msIsFullScreen !== undefined) {
  3724. _this.isFullscreen = document.msIsFullScreen;
  3725. }
  3726. // Pointer lock
  3727. if (_this.isFullscreen && _this._pointerLockRequested) {
  3728. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3729. if (canvas.requestPointerLock) {
  3730. canvas.requestPointerLock();
  3731. }
  3732. }
  3733. };
  3734. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3735. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3736. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3737. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3738. // Pointer lock
  3739. this._onPointerLockChange = function () {
  3740. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3741. };
  3742. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3743. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3744. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3745. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3746. if (!Engine.audioEngine) {
  3747. Engine.audioEngine = new BABYLON.AudioEngine();
  3748. }
  3749. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3750. }
  3751. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3752. get: function () {
  3753. return Engine._ALPHA_DISABLE;
  3754. },
  3755. enumerable: true,
  3756. configurable: true
  3757. });
  3758. Object.defineProperty(Engine, "ALPHA_ADD", {
  3759. get: function () {
  3760. return Engine._ALPHA_ADD;
  3761. },
  3762. enumerable: true,
  3763. configurable: true
  3764. });
  3765. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3766. get: function () {
  3767. return Engine._ALPHA_COMBINE;
  3768. },
  3769. enumerable: true,
  3770. configurable: true
  3771. });
  3772. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3773. get: function () {
  3774. return Engine._DELAYLOADSTATE_NONE;
  3775. },
  3776. enumerable: true,
  3777. configurable: true
  3778. });
  3779. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3780. get: function () {
  3781. return Engine._DELAYLOADSTATE_LOADED;
  3782. },
  3783. enumerable: true,
  3784. configurable: true
  3785. });
  3786. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3787. get: function () {
  3788. return Engine._DELAYLOADSTATE_LOADING;
  3789. },
  3790. enumerable: true,
  3791. configurable: true
  3792. });
  3793. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3794. get: function () {
  3795. return Engine._DELAYLOADSTATE_NOTLOADED;
  3796. },
  3797. enumerable: true,
  3798. configurable: true
  3799. });
  3800. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3801. get: function () {
  3802. return Engine._TEXTUREFORMAT_ALPHA;
  3803. },
  3804. enumerable: true,
  3805. configurable: true
  3806. });
  3807. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3808. get: function () {
  3809. return Engine._TEXTUREFORMAT_LUMINANCE;
  3810. },
  3811. enumerable: true,
  3812. configurable: true
  3813. });
  3814. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3815. get: function () {
  3816. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3817. },
  3818. enumerable: true,
  3819. configurable: true
  3820. });
  3821. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3822. get: function () {
  3823. return Engine._TEXTUREFORMAT_RGB;
  3824. },
  3825. enumerable: true,
  3826. configurable: true
  3827. });
  3828. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3829. get: function () {
  3830. return Engine._TEXTUREFORMAT_RGBA;
  3831. },
  3832. enumerable: true,
  3833. configurable: true
  3834. });
  3835. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3836. get: function () {
  3837. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3838. },
  3839. enumerable: true,
  3840. configurable: true
  3841. });
  3842. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3843. get: function () {
  3844. return Engine._TEXTURETYPE_FLOAT;
  3845. },
  3846. enumerable: true,
  3847. configurable: true
  3848. });
  3849. Object.defineProperty(Engine, "Version", {
  3850. get: function () {
  3851. return "2.0.0";
  3852. },
  3853. enumerable: true,
  3854. configurable: true
  3855. });
  3856. Engine.prototype.getGlInfo = function () {
  3857. return {
  3858. vendor: this._glVendor,
  3859. renderer: this._glRenderer,
  3860. version: this._glVersion
  3861. };
  3862. };
  3863. Engine.prototype.getAspectRatio = function (camera) {
  3864. var viewport = camera.viewport;
  3865. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3866. };
  3867. Engine.prototype.getRenderWidth = function () {
  3868. if (this._currentRenderTarget) {
  3869. return this._currentRenderTarget._width;
  3870. }
  3871. return this._renderingCanvas.width;
  3872. };
  3873. Engine.prototype.getRenderHeight = function () {
  3874. if (this._currentRenderTarget) {
  3875. return this._currentRenderTarget._height;
  3876. }
  3877. return this._renderingCanvas.height;
  3878. };
  3879. Engine.prototype.getRenderingCanvas = function () {
  3880. return this._renderingCanvas;
  3881. };
  3882. Engine.prototype.getRenderingCanvasClientRect = function () {
  3883. return this._renderingCanvas.getBoundingClientRect();
  3884. };
  3885. Engine.prototype.setHardwareScalingLevel = function (level) {
  3886. this._hardwareScalingLevel = level;
  3887. this.resize();
  3888. };
  3889. Engine.prototype.getHardwareScalingLevel = function () {
  3890. return this._hardwareScalingLevel;
  3891. };
  3892. Engine.prototype.getLoadedTexturesCache = function () {
  3893. return this._loadedTexturesCache;
  3894. };
  3895. Engine.prototype.getCaps = function () {
  3896. return this._caps;
  3897. };
  3898. Object.defineProperty(Engine.prototype, "drawCalls", {
  3899. get: function () {
  3900. return this._drawCalls;
  3901. },
  3902. enumerable: true,
  3903. configurable: true
  3904. });
  3905. // Methods
  3906. Engine.prototype.resetDrawCalls = function () {
  3907. this._drawCalls = 0;
  3908. };
  3909. Engine.prototype.setDepthFunctionToGreater = function () {
  3910. this._depthCullingState.depthFunc = this._gl.GREATER;
  3911. };
  3912. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3913. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3914. };
  3915. Engine.prototype.setDepthFunctionToLess = function () {
  3916. this._depthCullingState.depthFunc = this._gl.LESS;
  3917. };
  3918. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3919. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3920. };
  3921. /**
  3922. * stop executing a render loop function and remove it from the execution array
  3923. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3924. */
  3925. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3926. if (!renderFunction) {
  3927. this._activeRenderLoops = [];
  3928. return;
  3929. }
  3930. var index = this._activeRenderLoops.indexOf(renderFunction);
  3931. if (index >= 0) {
  3932. this._activeRenderLoops.splice(index, 1);
  3933. }
  3934. };
  3935. Engine.prototype._renderLoop = function () {
  3936. var _this = this;
  3937. var shouldRender = true;
  3938. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3939. shouldRender = false;
  3940. }
  3941. if (shouldRender) {
  3942. // Start new frame
  3943. this.beginFrame();
  3944. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3945. var renderFunction = this._activeRenderLoops[index];
  3946. renderFunction();
  3947. }
  3948. // Present
  3949. this.endFrame();
  3950. }
  3951. if (this._activeRenderLoops.length > 0) {
  3952. // Register new frame
  3953. BABYLON.Tools.QueueNewFrame(function () {
  3954. _this._renderLoop();
  3955. });
  3956. }
  3957. else {
  3958. this._renderingQueueLaunched = false;
  3959. }
  3960. };
  3961. /**
  3962. * Register and execute a render loop. The engine can have more than one render function.
  3963. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3964. * @example
  3965. * engine.runRenderLoop(function () {
  3966. * scene.render()
  3967. * })
  3968. */
  3969. Engine.prototype.runRenderLoop = function (renderFunction) {
  3970. var _this = this;
  3971. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3972. return;
  3973. }
  3974. this._activeRenderLoops.push(renderFunction);
  3975. if (!this._renderingQueueLaunched) {
  3976. this._renderingQueueLaunched = true;
  3977. BABYLON.Tools.QueueNewFrame(function () {
  3978. _this._renderLoop();
  3979. });
  3980. }
  3981. };
  3982. /**
  3983. * Toggle full screen mode.
  3984. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3985. */
  3986. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3987. if (this.isFullscreen) {
  3988. BABYLON.Tools.ExitFullscreen();
  3989. }
  3990. else {
  3991. this._pointerLockRequested = requestPointerLock;
  3992. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3993. }
  3994. };
  3995. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3996. this.applyStates();
  3997. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3998. if (this._depthCullingState.depthMask) {
  3999. this._gl.clearDepth(1.0);
  4000. }
  4001. var mode = 0;
  4002. if (backBuffer)
  4003. mode |= this._gl.COLOR_BUFFER_BIT;
  4004. if (depthStencil && this._depthCullingState.depthMask)
  4005. mode |= this._gl.DEPTH_BUFFER_BIT;
  4006. this._gl.clear(mode);
  4007. };
  4008. /**
  4009. * Set the WebGL's viewport
  4010. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4011. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4012. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4013. */
  4014. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4015. var width = requiredWidth || this._renderingCanvas.width;
  4016. var height = requiredHeight || this._renderingCanvas.height;
  4017. var x = viewport.x || 0;
  4018. var y = viewport.y || 0;
  4019. this._cachedViewport = viewport;
  4020. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4021. };
  4022. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4023. this._cachedViewport = null;
  4024. this._gl.viewport(x, y, width, height);
  4025. };
  4026. Engine.prototype.beginFrame = function () {
  4027. this._measureFps();
  4028. };
  4029. Engine.prototype.endFrame = function () {
  4030. //this.flushFramebuffer();
  4031. };
  4032. /**
  4033. * resize the view according to the canvas' size.
  4034. * @example
  4035. * window.addEventListener("resize", function () {
  4036. * engine.resize();
  4037. * });
  4038. */
  4039. Engine.prototype.resize = function () {
  4040. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4041. };
  4042. /**
  4043. * force a specific size of the canvas
  4044. * @param {number} width - the new canvas' width
  4045. * @param {number} height - the new canvas' height
  4046. */
  4047. Engine.prototype.setSize = function (width, height) {
  4048. this._renderingCanvas.width = width;
  4049. this._renderingCanvas.height = height;
  4050. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4051. };
  4052. Engine.prototype.bindFramebuffer = function (texture) {
  4053. this._currentRenderTarget = texture;
  4054. var gl = this._gl;
  4055. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4056. this._gl.viewport(0, 0, texture._width, texture._height);
  4057. this.wipeCaches();
  4058. };
  4059. Engine.prototype.unBindFramebuffer = function (texture) {
  4060. this._currentRenderTarget = null;
  4061. if (texture.generateMipMaps) {
  4062. var gl = this._gl;
  4063. gl.bindTexture(gl.TEXTURE_2D, texture);
  4064. gl.generateMipmap(gl.TEXTURE_2D);
  4065. gl.bindTexture(gl.TEXTURE_2D, null);
  4066. }
  4067. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4068. };
  4069. Engine.prototype.flushFramebuffer = function () {
  4070. this._gl.flush();
  4071. };
  4072. Engine.prototype.restoreDefaultFramebuffer = function () {
  4073. this._currentRenderTarget = null;
  4074. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4075. this.setViewport(this._cachedViewport);
  4076. this.wipeCaches();
  4077. };
  4078. // VBOs
  4079. Engine.prototype._resetVertexBufferBinding = function () {
  4080. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4081. this._cachedVertexBuffers = null;
  4082. };
  4083. Engine.prototype.createVertexBuffer = function (vertices) {
  4084. var vbo = this._gl.createBuffer();
  4085. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4086. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4087. this._resetVertexBufferBinding();
  4088. vbo.references = 1;
  4089. return vbo;
  4090. };
  4091. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4092. var vbo = this._gl.createBuffer();
  4093. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4094. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4095. this._resetVertexBufferBinding();
  4096. vbo.references = 1;
  4097. return vbo;
  4098. };
  4099. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4100. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4101. if (offset === undefined) {
  4102. offset = 0;
  4103. }
  4104. if (vertices instanceof Float32Array) {
  4105. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4106. }
  4107. else {
  4108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4109. }
  4110. this._resetVertexBufferBinding();
  4111. };
  4112. Engine.prototype._resetIndexBufferBinding = function () {
  4113. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4114. this._cachedIndexBuffer = null;
  4115. };
  4116. Engine.prototype.createIndexBuffer = function (indices) {
  4117. var vbo = this._gl.createBuffer();
  4118. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4119. // Check for 32 bits indices
  4120. var arrayBuffer;
  4121. var need32Bits = false;
  4122. if (this._caps.uintIndices) {
  4123. for (var index = 0; index < indices.length; index++) {
  4124. if (indices[index] > 65535) {
  4125. need32Bits = true;
  4126. break;
  4127. }
  4128. }
  4129. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4130. }
  4131. else {
  4132. arrayBuffer = new Uint16Array(indices);
  4133. }
  4134. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4135. this._resetIndexBufferBinding();
  4136. vbo.references = 1;
  4137. vbo.is32Bits = need32Bits;
  4138. return vbo;
  4139. };
  4140. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4141. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4142. this._cachedVertexBuffers = vertexBuffer;
  4143. this._cachedEffectForVertexBuffers = effect;
  4144. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4145. var offset = 0;
  4146. for (var index = 0; index < vertexDeclaration.length; index++) {
  4147. var order = effect.getAttributeLocation(index);
  4148. if (order >= 0) {
  4149. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4150. }
  4151. offset += vertexDeclaration[index] * 4;
  4152. }
  4153. }
  4154. if (this._cachedIndexBuffer !== indexBuffer) {
  4155. this._cachedIndexBuffer = indexBuffer;
  4156. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4157. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4158. }
  4159. };
  4160. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4161. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4162. this._cachedVertexBuffers = vertexBuffers;
  4163. this._cachedEffectForVertexBuffers = effect;
  4164. var attributes = effect.getAttributesNames();
  4165. for (var index = 0; index < attributes.length; index++) {
  4166. var order = effect.getAttributeLocation(index);
  4167. if (order >= 0) {
  4168. var vertexBuffer = vertexBuffers[attributes[index]];
  4169. if (!vertexBuffer) {
  4170. continue;
  4171. }
  4172. var stride = vertexBuffer.getStrideSize();
  4173. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4174. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4175. }
  4176. }
  4177. }
  4178. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4179. this._cachedIndexBuffer = indexBuffer;
  4180. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4181. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4182. }
  4183. };
  4184. Engine.prototype._releaseBuffer = function (buffer) {
  4185. buffer.references--;
  4186. if (buffer.references === 0) {
  4187. this._gl.deleteBuffer(buffer);
  4188. return true;
  4189. }
  4190. return false;
  4191. };
  4192. Engine.prototype.createInstancesBuffer = function (capacity) {
  4193. var buffer = this._gl.createBuffer();
  4194. buffer.capacity = capacity;
  4195. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4196. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4197. return buffer;
  4198. };
  4199. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4200. this._gl.deleteBuffer(buffer);
  4201. };
  4202. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4203. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4204. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4205. for (var index = 0; index < 4; index++) {
  4206. var offsetLocation = offsetLocations[index];
  4207. this._gl.enableVertexAttribArray(offsetLocation);
  4208. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4209. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4210. }
  4211. };
  4212. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4213. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4214. for (var index = 0; index < 4; index++) {
  4215. var offsetLocation = offsetLocations[index];
  4216. this._gl.disableVertexAttribArray(offsetLocation);
  4217. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4218. }
  4219. };
  4220. Engine.prototype.applyStates = function () {
  4221. this._depthCullingState.apply(this._gl);
  4222. this._alphaState.apply(this._gl);
  4223. };
  4224. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4225. // Apply states
  4226. this.applyStates();
  4227. this._drawCalls++;
  4228. // Render
  4229. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4230. if (instancesCount) {
  4231. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4232. return;
  4233. }
  4234. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4235. };
  4236. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4237. // Apply states
  4238. this.applyStates();
  4239. this._drawCalls++;
  4240. if (instancesCount) {
  4241. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4242. return;
  4243. }
  4244. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4245. };
  4246. // Shaders
  4247. Engine.prototype._releaseEffect = function (effect) {
  4248. if (this._compiledEffects[effect._key]) {
  4249. delete this._compiledEffects[effect._key];
  4250. if (effect.getProgram()) {
  4251. this._gl.deleteProgram(effect.getProgram());
  4252. }
  4253. }
  4254. };
  4255. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4256. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4257. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4258. var name = vertex + "+" + fragment + "@" + defines;
  4259. if (this._compiledEffects[name]) {
  4260. return this._compiledEffects[name];
  4261. }
  4262. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4263. effect._key = name;
  4264. this._compiledEffects[name] = effect;
  4265. return effect;
  4266. };
  4267. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4268. if (uniformsNames === void 0) { uniformsNames = []; }
  4269. if (samplers === void 0) { samplers = []; }
  4270. if (defines === void 0) { defines = ""; }
  4271. return this.createEffect({
  4272. vertex: "particles",
  4273. fragmentElement: fragmentName
  4274. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4275. };
  4276. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4277. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4278. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4279. var shaderProgram = this._gl.createProgram();
  4280. this._gl.attachShader(shaderProgram, vertexShader);
  4281. this._gl.attachShader(shaderProgram, fragmentShader);
  4282. this._gl.linkProgram(shaderProgram);
  4283. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4284. if (!linked) {
  4285. var error = this._gl.getProgramInfoLog(shaderProgram);
  4286. if (error) {
  4287. throw new Error(error);
  4288. }
  4289. }
  4290. this._gl.deleteShader(vertexShader);
  4291. this._gl.deleteShader(fragmentShader);
  4292. return shaderProgram;
  4293. };
  4294. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4295. var results = [];
  4296. for (var index = 0; index < uniformsNames.length; index++) {
  4297. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4298. }
  4299. return results;
  4300. };
  4301. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4302. var results = [];
  4303. for (var index = 0; index < attributesNames.length; index++) {
  4304. try {
  4305. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4306. }
  4307. catch (e) {
  4308. results.push(-1);
  4309. }
  4310. }
  4311. return results;
  4312. };
  4313. Engine.prototype.enableEffect = function (effect) {
  4314. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4315. if (effect && effect.onBind) {
  4316. effect.onBind(effect);
  4317. }
  4318. return;
  4319. }
  4320. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4321. // Use program
  4322. this._gl.useProgram(effect.getProgram());
  4323. for (var i in this._vertexAttribArrays) {
  4324. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4325. continue;
  4326. }
  4327. this._vertexAttribArrays[i] = false;
  4328. this._gl.disableVertexAttribArray(i);
  4329. }
  4330. var attributesCount = effect.getAttributesCount();
  4331. for (var index = 0; index < attributesCount; index++) {
  4332. // Attributes
  4333. var order = effect.getAttributeLocation(index);
  4334. if (order >= 0) {
  4335. this._vertexAttribArrays[order] = true;
  4336. this._gl.enableVertexAttribArray(order);
  4337. }
  4338. }
  4339. this._currentEffect = effect;
  4340. if (effect.onBind) {
  4341. effect.onBind(effect);
  4342. }
  4343. };
  4344. Engine.prototype.setArray = function (uniform, array) {
  4345. if (!uniform)
  4346. return;
  4347. this._gl.uniform1fv(uniform, array);
  4348. };
  4349. Engine.prototype.setArray2 = function (uniform, array) {
  4350. if (!uniform || array.length % 2 !== 0)
  4351. return;
  4352. this._gl.uniform2fv(uniform, array);
  4353. };
  4354. Engine.prototype.setArray3 = function (uniform, array) {
  4355. if (!uniform || array.length % 3 !== 0)
  4356. return;
  4357. this._gl.uniform3fv(uniform, array);
  4358. };
  4359. Engine.prototype.setArray4 = function (uniform, array) {
  4360. if (!uniform || array.length % 4 !== 0)
  4361. return;
  4362. this._gl.uniform4fv(uniform, array);
  4363. };
  4364. Engine.prototype.setMatrices = function (uniform, matrices) {
  4365. if (!uniform)
  4366. return;
  4367. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4368. };
  4369. Engine.prototype.setMatrix = function (uniform, matrix) {
  4370. if (!uniform)
  4371. return;
  4372. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4373. };
  4374. Engine.prototype.setFloat = function (uniform, value) {
  4375. if (!uniform)
  4376. return;
  4377. this._gl.uniform1f(uniform, value);
  4378. };
  4379. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4380. if (!uniform)
  4381. return;
  4382. this._gl.uniform2f(uniform, x, y);
  4383. };
  4384. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4385. if (!uniform)
  4386. return;
  4387. this._gl.uniform3f(uniform, x, y, z);
  4388. };
  4389. Engine.prototype.setBool = function (uniform, bool) {
  4390. if (!uniform)
  4391. return;
  4392. this._gl.uniform1i(uniform, bool);
  4393. };
  4394. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4395. if (!uniform)
  4396. return;
  4397. this._gl.uniform4f(uniform, x, y, z, w);
  4398. };
  4399. Engine.prototype.setColor3 = function (uniform, color3) {
  4400. if (!uniform)
  4401. return;
  4402. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4403. };
  4404. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4405. if (!uniform)
  4406. return;
  4407. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4408. };
  4409. // States
  4410. Engine.prototype.setState = function (culling, force) {
  4411. // Culling
  4412. if (this._depthCullingState.cull !== culling || force) {
  4413. if (culling) {
  4414. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4415. this._depthCullingState.cull = true;
  4416. }
  4417. else {
  4418. this._depthCullingState.cull = false;
  4419. }
  4420. }
  4421. };
  4422. Engine.prototype.setDepthBuffer = function (enable) {
  4423. this._depthCullingState.depthTest = enable;
  4424. };
  4425. Engine.prototype.getDepthWrite = function () {
  4426. return this._depthCullingState.depthMask;
  4427. };
  4428. Engine.prototype.setDepthWrite = function (enable) {
  4429. this._depthCullingState.depthMask = enable;
  4430. };
  4431. Engine.prototype.setColorWrite = function (enable) {
  4432. this._gl.colorMask(enable, enable, enable, enable);
  4433. };
  4434. Engine.prototype.setAlphaMode = function (mode) {
  4435. switch (mode) {
  4436. case Engine.ALPHA_DISABLE:
  4437. this.setDepthWrite(true);
  4438. this._alphaState.alphaBlend = false;
  4439. break;
  4440. case Engine.ALPHA_COMBINE:
  4441. this.setDepthWrite(false);
  4442. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4443. this._alphaState.alphaBlend = true;
  4444. break;
  4445. case Engine.ALPHA_ADD:
  4446. this.setDepthWrite(false);
  4447. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4448. this._alphaState.alphaBlend = true;
  4449. break;
  4450. }
  4451. this._alphaMode = mode;
  4452. };
  4453. Engine.prototype.getAlphaMode = function () {
  4454. return this._alphaMode;
  4455. };
  4456. Engine.prototype.setAlphaTesting = function (enable) {
  4457. this._alphaTest = enable;
  4458. };
  4459. Engine.prototype.getAlphaTesting = function () {
  4460. return this._alphaTest;
  4461. };
  4462. // Textures
  4463. Engine.prototype.wipeCaches = function () {
  4464. this._activeTexturesCache = [];
  4465. this._currentEffect = null;
  4466. this._depthCullingState.reset();
  4467. this._alphaState.reset();
  4468. this._cachedVertexBuffers = null;
  4469. this._cachedIndexBuffer = null;
  4470. this._cachedEffectForVertexBuffers = null;
  4471. };
  4472. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4473. var gl = this._gl;
  4474. gl.bindTexture(gl.TEXTURE_2D, texture);
  4475. var magFilter = gl.NEAREST;
  4476. var minFilter = gl.NEAREST;
  4477. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4478. magFilter = gl.LINEAR;
  4479. minFilter = gl.LINEAR;
  4480. }
  4481. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4482. magFilter = gl.LINEAR;
  4483. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4484. }
  4485. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4486. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4487. gl.bindTexture(gl.TEXTURE_2D, null);
  4488. texture.samplingMode = samplingMode;
  4489. };
  4490. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4491. var _this = this;
  4492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4493. if (onLoad === void 0) { onLoad = null; }
  4494. if (onError === void 0) { onError = null; }
  4495. if (buffer === void 0) { buffer = null; }
  4496. var texture = this._gl.createTexture();
  4497. var extension;
  4498. var fromData = false;
  4499. if (url.substr(0, 5) === "data:") {
  4500. fromData = true;
  4501. }
  4502. if (!fromData)
  4503. extension = url.substr(url.length - 4, 4).toLowerCase();
  4504. else {
  4505. var oldUrl = url;
  4506. fromData = oldUrl.split(':');
  4507. url = oldUrl;
  4508. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4509. }
  4510. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4511. var isTGA = (extension === ".tga");
  4512. scene._addPendingData(texture);
  4513. texture.url = url;
  4514. texture.noMipmap = noMipmap;
  4515. texture.references = 1;
  4516. this._loadedTexturesCache.push(texture);
  4517. var onerror = function () {
  4518. scene._removePendingData(texture);
  4519. if (onError) {
  4520. onError();
  4521. }
  4522. };
  4523. if (isTGA) {
  4524. var callback = function (arrayBuffer) {
  4525. var data = new Uint8Array(arrayBuffer);
  4526. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4527. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4528. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4529. if (onLoad) {
  4530. onLoad();
  4531. }
  4532. }, samplingMode);
  4533. };
  4534. if (!(fromData instanceof Array))
  4535. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4536. callback(arrayBuffer);
  4537. }, onerror, scene.database, true);
  4538. else
  4539. callback(buffer);
  4540. }
  4541. else if (isDDS) {
  4542. callback = function (data) {
  4543. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4544. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4545. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4546. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4547. if (onLoad) {
  4548. onLoad();
  4549. }
  4550. }, samplingMode);
  4551. };
  4552. if (!(fromData instanceof Array))
  4553. BABYLON.Tools.LoadFile(url, function (data) {
  4554. callback(data);
  4555. }, onerror, scene.database, true);
  4556. else
  4557. callback(buffer);
  4558. }
  4559. else {
  4560. var onload = function (img) {
  4561. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4562. var isPot = (img.width === potWidth && img.height === potHeight);
  4563. if (!isPot) {
  4564. _this._workingCanvas.width = potWidth;
  4565. _this._workingCanvas.height = potHeight;
  4566. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4567. _this._workingContext.imageSmoothingEnabled = false;
  4568. _this._workingContext.mozImageSmoothingEnabled = false;
  4569. _this._workingContext.oImageSmoothingEnabled = false;
  4570. _this._workingContext.webkitImageSmoothingEnabled = false;
  4571. _this._workingContext.msImageSmoothingEnabled = false;
  4572. }
  4573. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4574. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4575. _this._workingContext.imageSmoothingEnabled = true;
  4576. _this._workingContext.mozImageSmoothingEnabled = true;
  4577. _this._workingContext.oImageSmoothingEnabled = true;
  4578. _this._workingContext.webkitImageSmoothingEnabled = true;
  4579. _this._workingContext.msImageSmoothingEnabled = true;
  4580. }
  4581. }
  4582. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4583. if (onLoad) {
  4584. onLoad();
  4585. }
  4586. }, samplingMode);
  4587. };
  4588. if (!(fromData instanceof Array))
  4589. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4590. else
  4591. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4592. }
  4593. return texture;
  4594. };
  4595. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4596. var texture = this._gl.createTexture();
  4597. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4598. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4599. // Format
  4600. var internalFormat = this._gl.RGBA;
  4601. switch (format) {
  4602. case Engine.TEXTUREFORMAT_ALPHA:
  4603. internalFormat = this._gl.ALPHA;
  4604. break;
  4605. case Engine.TEXTUREFORMAT_LUMINANCE:
  4606. internalFormat = this._gl.LUMINANCE;
  4607. break;
  4608. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4609. internalFormat = this._gl.LUMINANCE_ALPHA;
  4610. break;
  4611. case Engine.TEXTUREFORMAT_RGB:
  4612. internalFormat = this._gl.RGB;
  4613. break;
  4614. case Engine.TEXTUREFORMAT_RGBA:
  4615. internalFormat = this._gl.RGBA;
  4616. break;
  4617. }
  4618. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4619. if (generateMipMaps) {
  4620. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4621. }
  4622. // Filters
  4623. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4626. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4627. this._activeTexturesCache = [];
  4628. texture._baseWidth = width;
  4629. texture._baseHeight = height;
  4630. texture._width = width;
  4631. texture._height = height;
  4632. texture.isReady = true;
  4633. texture.references = 1;
  4634. texture.samplingMode = samplingMode;
  4635. this._loadedTexturesCache.push(texture);
  4636. return texture;
  4637. };
  4638. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4639. var texture = this._gl.createTexture();
  4640. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4641. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4642. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4643. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4644. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4645. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4646. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4647. this._activeTexturesCache = [];
  4648. texture._baseWidth = width;
  4649. texture._baseHeight = height;
  4650. texture._width = width;
  4651. texture._height = height;
  4652. texture.isReady = false;
  4653. texture.generateMipMaps = generateMipMaps;
  4654. texture.references = 1;
  4655. texture.samplingMode = samplingMode;
  4656. this._loadedTexturesCache.push(texture);
  4657. return texture;
  4658. };
  4659. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4660. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4661. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4662. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4663. if (texture.generateMipMaps) {
  4664. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4665. }
  4666. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4667. this._activeTexturesCache = [];
  4668. texture.isReady = true;
  4669. };
  4670. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4671. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4672. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4673. // Scale the video if it is a NPOT using the current working canvas
  4674. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4675. if (!texture._workingCanvas) {
  4676. texture._workingCanvas = document.createElement("canvas");
  4677. texture._workingContext = texture._workingCanvas.getContext("2d");
  4678. texture._workingCanvas.width = texture._width;
  4679. texture._workingCanvas.height = texture._height;
  4680. }
  4681. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4682. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4683. }
  4684. else {
  4685. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4686. }
  4687. if (texture.generateMipMaps) {
  4688. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4689. }
  4690. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4691. this._activeTexturesCache = [];
  4692. texture.isReady = true;
  4693. };
  4694. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4695. // old version had a "generateMipMaps" arg instead of options.
  4696. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4697. // in the same way, generateDepthBuffer is defaulted to true
  4698. var generateMipMaps = false;
  4699. var generateDepthBuffer = true;
  4700. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4701. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4702. if (options !== undefined) {
  4703. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4704. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4705. type = options.type === undefined ? type : options.type;
  4706. if (options.samplingMode !== undefined) {
  4707. samplingMode = options.samplingMode;
  4708. }
  4709. if (type === Engine.TEXTURETYPE_FLOAT) {
  4710. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4711. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4712. }
  4713. }
  4714. var gl = this._gl;
  4715. var texture = gl.createTexture();
  4716. gl.bindTexture(gl.TEXTURE_2D, texture);
  4717. var width = size.width || size;
  4718. var height = size.height || size;
  4719. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4720. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4721. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4722. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4723. }
  4724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4725. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4726. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4727. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4728. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4729. var depthBuffer;
  4730. // Create the depth buffer
  4731. if (generateDepthBuffer) {
  4732. depthBuffer = gl.createRenderbuffer();
  4733. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4734. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4735. }
  4736. // Create the framebuffer
  4737. var framebuffer = gl.createFramebuffer();
  4738. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4739. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4740. if (generateDepthBuffer) {
  4741. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4742. }
  4743. // Unbind
  4744. gl.bindTexture(gl.TEXTURE_2D, null);
  4745. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4746. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4747. texture._framebuffer = framebuffer;
  4748. if (generateDepthBuffer) {
  4749. texture._depthBuffer = depthBuffer;
  4750. }
  4751. texture._width = width;
  4752. texture._height = height;
  4753. texture.isReady = true;
  4754. texture.generateMipMaps = generateMipMaps;
  4755. texture.references = 1;
  4756. texture.samplingMode = samplingMode;
  4757. this._activeTexturesCache = [];
  4758. this._loadedTexturesCache.push(texture);
  4759. return texture;
  4760. };
  4761. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4762. var _this = this;
  4763. var gl = this._gl;
  4764. var texture = gl.createTexture();
  4765. texture.isCube = true;
  4766. texture.url = rootUrl;
  4767. texture.references = 1;
  4768. this._loadedTexturesCache.push(texture);
  4769. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4770. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4771. if (isDDS) {
  4772. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4773. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4774. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4775. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4776. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4777. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4778. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4779. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4780. }
  4781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4782. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4785. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4786. _this._activeTexturesCache = [];
  4787. texture._width = info.width;
  4788. texture._height = info.height;
  4789. texture.isReady = true;
  4790. }, null, null, true);
  4791. }
  4792. else {
  4793. cascadeLoad(rootUrl, scene, function (imgs) {
  4794. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4795. var height = width;
  4796. _this._workingCanvas.width = width;
  4797. _this._workingCanvas.height = height;
  4798. var faces = [
  4799. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4800. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4801. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4802. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4803. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4804. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4805. ];
  4806. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4807. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4808. for (var index = 0; index < faces.length; index++) {
  4809. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4810. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4811. }
  4812. if (!noMipmap) {
  4813. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4814. }
  4815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4819. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4820. _this._activeTexturesCache = [];
  4821. texture._width = width;
  4822. texture._height = height;
  4823. texture.isReady = true;
  4824. }, extensions);
  4825. }
  4826. return texture;
  4827. };
  4828. Engine.prototype._releaseTexture = function (texture) {
  4829. var gl = this._gl;
  4830. if (texture._framebuffer) {
  4831. gl.deleteFramebuffer(texture._framebuffer);
  4832. }
  4833. if (texture._depthBuffer) {
  4834. gl.deleteRenderbuffer(texture._depthBuffer);
  4835. }
  4836. gl.deleteTexture(texture);
  4837. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4838. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4839. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4840. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4841. this._activeTexturesCache[channel] = null;
  4842. }
  4843. var index = this._loadedTexturesCache.indexOf(texture);
  4844. if (index !== -1) {
  4845. this._loadedTexturesCache.splice(index, 1);
  4846. }
  4847. };
  4848. Engine.prototype.bindSamplers = function (effect) {
  4849. this._gl.useProgram(effect.getProgram());
  4850. var samplers = effect.getSamplers();
  4851. for (var index = 0; index < samplers.length; index++) {
  4852. var uniform = effect.getUniform(samplers[index]);
  4853. this._gl.uniform1i(uniform, index);
  4854. }
  4855. this._currentEffect = null;
  4856. };
  4857. Engine.prototype._bindTexture = function (channel, texture) {
  4858. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4859. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4860. this._activeTexturesCache[channel] = null;
  4861. };
  4862. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4863. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4864. };
  4865. Engine.prototype.setTexture = function (channel, texture) {
  4866. if (channel < 0) {
  4867. return;
  4868. }
  4869. // Not ready?
  4870. if (!texture || !texture.isReady()) {
  4871. if (this._activeTexturesCache[channel] != null) {
  4872. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4873. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4874. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4875. this._activeTexturesCache[channel] = null;
  4876. }
  4877. return;
  4878. }
  4879. // Video
  4880. if (texture instanceof BABYLON.VideoTexture) {
  4881. if (texture.update()) {
  4882. this._activeTexturesCache[channel] = null;
  4883. }
  4884. }
  4885. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4886. texture.delayLoad();
  4887. return;
  4888. }
  4889. if (this._activeTexturesCache[channel] === texture) {
  4890. return;
  4891. }
  4892. this._activeTexturesCache[channel] = texture;
  4893. var internalTexture = texture.getInternalTexture();
  4894. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4895. if (internalTexture.isCube) {
  4896. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4897. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4898. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4899. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4900. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4901. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4902. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4903. }
  4904. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4905. }
  4906. else {
  4907. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4908. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4909. internalTexture._cachedWrapU = texture.wrapU;
  4910. switch (texture.wrapU) {
  4911. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4913. break;
  4914. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4915. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4916. break;
  4917. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4918. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4919. break;
  4920. }
  4921. }
  4922. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4923. internalTexture._cachedWrapV = texture.wrapV;
  4924. switch (texture.wrapV) {
  4925. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4926. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4927. break;
  4928. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4929. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4930. break;
  4931. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4932. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4933. break;
  4934. }
  4935. }
  4936. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4937. }
  4938. };
  4939. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4940. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4941. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4942. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4943. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4944. }
  4945. };
  4946. Engine.prototype.readPixels = function (x, y, width, height) {
  4947. var data = new Uint8Array(height * width * 4);
  4948. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4949. return data;
  4950. };
  4951. // Dispose
  4952. Engine.prototype.dispose = function () {
  4953. this.hideLoadingUI();
  4954. this.stopRenderLoop();
  4955. while (this.scenes.length) {
  4956. this.scenes[0].dispose();
  4957. }
  4958. // Release audio engine
  4959. Engine.audioEngine.dispose();
  4960. for (var name in this._compiledEffects) {
  4961. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4962. }
  4963. for (var i in this._vertexAttribArrays) {
  4964. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4965. continue;
  4966. }
  4967. this._gl.disableVertexAttribArray(i);
  4968. }
  4969. // Events
  4970. window.removeEventListener("blur", this._onBlur);
  4971. window.removeEventListener("focus", this._onFocus);
  4972. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4973. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4974. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4975. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4976. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4977. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4978. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4979. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4980. };
  4981. // Loading screen
  4982. Engine.prototype.displayLoadingUI = function () {
  4983. var _this = this;
  4984. this._loadingDiv = document.createElement("div");
  4985. this._loadingDiv.style.opacity = "0";
  4986. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4987. // Loading text
  4988. this._loadingTextDiv = document.createElement("div");
  4989. this._loadingTextDiv.style.position = "absolute";
  4990. this._loadingTextDiv.style.left = "0";
  4991. this._loadingTextDiv.style.top = "50%";
  4992. this._loadingTextDiv.style.marginTop = "80px";
  4993. this._loadingTextDiv.style.width = "100%";
  4994. this._loadingTextDiv.style.height = "20px";
  4995. this._loadingTextDiv.style.fontFamily = "Arial";
  4996. this._loadingTextDiv.style.fontSize = "14px";
  4997. this._loadingTextDiv.style.color = "white";
  4998. this._loadingTextDiv.style.textAlign = "center";
  4999. this._loadingTextDiv.innerHTML = "Loading";
  5000. this._loadingDiv.appendChild(this._loadingTextDiv);
  5001. // Loading img
  5002. var imgBack = new Image();
  5003. 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==";
  5004. imgBack.style.position = "absolute";
  5005. imgBack.style.left = "50%";
  5006. imgBack.style.top = "50%";
  5007. imgBack.style.marginLeft = "-50px";
  5008. imgBack.style.marginTop = "-50px";
  5009. imgBack.style.transition = "transform 1.0s ease";
  5010. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5011. var deg = 360;
  5012. var onTransitionEnd = function () {
  5013. deg += 360;
  5014. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5015. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5016. };
  5017. imgBack.addEventListener("transitionend", onTransitionEnd);
  5018. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5019. this._loadingDiv.appendChild(imgBack);
  5020. // front image
  5021. var imgFront = new Image();
  5022. 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=";
  5023. imgFront.style.position = "absolute";
  5024. imgFront.style.left = "50%";
  5025. imgFront.style.top = "50%";
  5026. imgFront.style.marginLeft = "-50px";
  5027. imgFront.style.marginTop = "-50px";
  5028. this._loadingDiv.appendChild(imgFront);
  5029. // Resize
  5030. this._resizeLoadingUI = function () {
  5031. var canvasRect = _this.getRenderingCanvasClientRect();
  5032. _this._loadingDiv.style.position = "absolute";
  5033. _this._loadingDiv.style.left = canvasRect.left + "px";
  5034. _this._loadingDiv.style.top = canvasRect.top + "px";
  5035. _this._loadingDiv.style.width = canvasRect.width + "px";
  5036. _this._loadingDiv.style.height = canvasRect.height + "px";
  5037. };
  5038. this._resizeLoadingUI();
  5039. window.addEventListener("resize", this._resizeLoadingUI);
  5040. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5041. document.body.appendChild(this._loadingDiv);
  5042. setTimeout(function () {
  5043. _this._loadingDiv.style.opacity = "1";
  5044. imgBack.style.transform = "rotateZ(360deg)";
  5045. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5046. }, 0);
  5047. };
  5048. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5049. set: function (text) {
  5050. if (!this._loadingDiv) {
  5051. return;
  5052. }
  5053. this._loadingTextDiv.innerHTML = text;
  5054. },
  5055. enumerable: true,
  5056. configurable: true
  5057. });
  5058. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5059. get: function () {
  5060. return this._loadingDivBackgroundColor;
  5061. },
  5062. set: function (color) {
  5063. this._loadingDivBackgroundColor = color;
  5064. if (!this._loadingDiv) {
  5065. return;
  5066. }
  5067. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5068. },
  5069. enumerable: true,
  5070. configurable: true
  5071. });
  5072. Engine.prototype.hideLoadingUI = function () {
  5073. var _this = this;
  5074. if (!this._loadingDiv) {
  5075. return;
  5076. }
  5077. var onTransitionEnd = function () {
  5078. if (!_this._loadingDiv) {
  5079. return;
  5080. }
  5081. document.body.removeChild(_this._loadingDiv);
  5082. window.removeEventListener("resize", _this._resizeLoadingUI);
  5083. _this._loadingDiv = null;
  5084. };
  5085. this._loadingDiv.style.opacity = "0";
  5086. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5087. };
  5088. // FPS
  5089. Engine.prototype.getFps = function () {
  5090. return this.fps;
  5091. };
  5092. Engine.prototype.getDeltaTime = function () {
  5093. return this.deltaTime;
  5094. };
  5095. Engine.prototype._measureFps = function () {
  5096. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5097. var length = this.previousFramesDuration.length;
  5098. if (length >= 2) {
  5099. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5100. }
  5101. if (length >= this.fpsRange) {
  5102. if (length > this.fpsRange) {
  5103. this.previousFramesDuration.splice(0, 1);
  5104. length = this.previousFramesDuration.length;
  5105. }
  5106. var sum = 0;
  5107. for (var id = 0; id < length - 1; id++) {
  5108. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5109. }
  5110. this.fps = 1000.0 / (sum / (length - 1));
  5111. }
  5112. };
  5113. // Statics
  5114. Engine.isSupported = function () {
  5115. try {
  5116. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5117. if (navigator.isCocoonJS) {
  5118. return true;
  5119. }
  5120. var tempcanvas = document.createElement("canvas");
  5121. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5122. return gl != null && !!window.WebGLRenderingContext;
  5123. }
  5124. catch (e) {
  5125. return false;
  5126. }
  5127. };
  5128. // Const statics
  5129. Engine._ALPHA_DISABLE = 0;
  5130. Engine._ALPHA_ADD = 1;
  5131. Engine._ALPHA_COMBINE = 2;
  5132. Engine._DELAYLOADSTATE_NONE = 0;
  5133. Engine._DELAYLOADSTATE_LOADED = 1;
  5134. Engine._DELAYLOADSTATE_LOADING = 2;
  5135. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5136. Engine._TEXTUREFORMAT_ALPHA = 0;
  5137. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5138. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5139. Engine._TEXTUREFORMAT_RGB = 4;
  5140. Engine._TEXTUREFORMAT_RGBA = 4;
  5141. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5142. Engine._TEXTURETYPE_FLOAT = 1;
  5143. // Updatable statics so stick with vars here
  5144. Engine.Epsilon = 0.001;
  5145. Engine.CollisionsEpsilon = 0.001;
  5146. Engine.ShadersRepository = "Babylon/Shaders/";
  5147. return Engine;
  5148. })();
  5149. BABYLON.Engine = Engine;
  5150. })(BABYLON || (BABYLON = {}));
  5151. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5152. (function (BABYLON) {
  5153. /**
  5154. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5155. */
  5156. var Node = (function () {
  5157. /**
  5158. * @constructor
  5159. * @param {string} name - the name and id to be given to this node
  5160. * @param {BABYLON.Scene} the scene this node will be added to
  5161. */
  5162. function Node(name, scene) {
  5163. this.state = "";
  5164. this.animations = new Array();
  5165. this._childrenFlag = -1;
  5166. this._isEnabled = true;
  5167. this._isReady = true;
  5168. this._currentRenderId = -1;
  5169. this.name = name;
  5170. this.id = name;
  5171. this._scene = scene;
  5172. this._initCache();
  5173. }
  5174. Node.prototype.getScene = function () {
  5175. return this._scene;
  5176. };
  5177. Node.prototype.getEngine = function () {
  5178. return this._scene.getEngine();
  5179. };
  5180. // override it in derived class
  5181. Node.prototype.getWorldMatrix = function () {
  5182. return BABYLON.Matrix.Identity();
  5183. };
  5184. // override it in derived class if you add new variables to the cache
  5185. // and call the parent class method
  5186. Node.prototype._initCache = function () {
  5187. this._cache = {};
  5188. this._cache.parent = undefined;
  5189. };
  5190. Node.prototype.updateCache = function (force) {
  5191. if (!force && this.isSynchronized())
  5192. return;
  5193. this._cache.parent = this.parent;
  5194. this._updateCache();
  5195. };
  5196. // override it in derived class if you add new variables to the cache
  5197. // and call the parent class method if !ignoreParentClass
  5198. Node.prototype._updateCache = function (ignoreParentClass) {
  5199. };
  5200. // override it in derived class if you add new variables to the cache
  5201. Node.prototype._isSynchronized = function () {
  5202. return true;
  5203. };
  5204. Node.prototype.isSynchronizedWithParent = function () {
  5205. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5206. };
  5207. Node.prototype.isSynchronized = function (updateCache) {
  5208. var check = this.hasNewParent();
  5209. check = check || !this.isSynchronizedWithParent();
  5210. check = check || !this._isSynchronized();
  5211. if (updateCache)
  5212. this.updateCache(true);
  5213. return !check;
  5214. };
  5215. Node.prototype.hasNewParent = function (update) {
  5216. if (this._cache.parent === this.parent)
  5217. return false;
  5218. if (update)
  5219. this._cache.parent = this.parent;
  5220. return true;
  5221. };
  5222. /**
  5223. * Is this node ready to be used/rendered
  5224. * @return {boolean} is it ready
  5225. */
  5226. Node.prototype.isReady = function () {
  5227. return this._isReady;
  5228. };
  5229. /**
  5230. * Is this node enabled.
  5231. * If the node has a parent and is enabled, the parent will be inspected as well.
  5232. * @return {boolean} whether this node (and its parent) is enabled.
  5233. * @see setEnabled
  5234. */
  5235. Node.prototype.isEnabled = function () {
  5236. if (!this._isEnabled) {
  5237. return false;
  5238. }
  5239. if (this.parent) {
  5240. return this.parent.isEnabled();
  5241. }
  5242. return true;
  5243. };
  5244. /**
  5245. * Set the enabled state of this node.
  5246. * @param {boolean} value - the new enabled state
  5247. * @see isEnabled
  5248. */
  5249. Node.prototype.setEnabled = function (value) {
  5250. this._isEnabled = value;
  5251. };
  5252. /**
  5253. * Is this node a descendant of the given node.
  5254. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5255. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5256. * @see parent
  5257. */
  5258. Node.prototype.isDescendantOf = function (ancestor) {
  5259. if (this.parent) {
  5260. if (this.parent === ancestor) {
  5261. return true;
  5262. }
  5263. return this.parent.isDescendantOf(ancestor);
  5264. }
  5265. return false;
  5266. };
  5267. Node.prototype._getDescendants = function (list, results) {
  5268. for (var index = 0; index < list.length; index++) {
  5269. var item = list[index];
  5270. if (item.isDescendantOf(this)) {
  5271. results.push(item);
  5272. }
  5273. }
  5274. };
  5275. /**
  5276. * Will return all nodes that have this node as parent.
  5277. * @return {BABYLON.Node[]} all children nodes of all types.
  5278. */
  5279. Node.prototype.getDescendants = function () {
  5280. var results = [];
  5281. this._getDescendants(this._scene.meshes, results);
  5282. this._getDescendants(this._scene.lights, results);
  5283. this._getDescendants(this._scene.cameras, results);
  5284. return results;
  5285. };
  5286. Node.prototype._setReady = function (state) {
  5287. if (state == this._isReady) {
  5288. return;
  5289. }
  5290. if (!state) {
  5291. this._isReady = false;
  5292. return;
  5293. }
  5294. this._isReady = true;
  5295. if (this.onReady) {
  5296. this.onReady(this);
  5297. }
  5298. };
  5299. return Node;
  5300. })();
  5301. BABYLON.Node = Node;
  5302. })(BABYLON || (BABYLON = {}));
  5303. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5304. (function (BABYLON) {
  5305. var BoundingSphere = (function () {
  5306. function BoundingSphere(minimum, maximum) {
  5307. this.minimum = minimum;
  5308. this.maximum = maximum;
  5309. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5310. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5311. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5312. this.radius = distance * 0.5;
  5313. this.centerWorld = BABYLON.Vector3.Zero();
  5314. this._update(BABYLON.Matrix.Identity());
  5315. }
  5316. // Methods
  5317. BoundingSphere.prototype._update = function (world) {
  5318. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5319. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5320. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5321. };
  5322. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5323. for (var i = 0; i < 6; i++) {
  5324. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5325. return false;
  5326. }
  5327. return true;
  5328. };
  5329. BoundingSphere.prototype.intersectsPoint = function (point) {
  5330. var x = this.centerWorld.x - point.x;
  5331. var y = this.centerWorld.y - point.y;
  5332. var z = this.centerWorld.z - point.z;
  5333. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5334. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5335. return false;
  5336. return true;
  5337. };
  5338. // Statics
  5339. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5340. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5341. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5342. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5343. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5344. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5345. return false;
  5346. return true;
  5347. };
  5348. return BoundingSphere;
  5349. })();
  5350. BABYLON.BoundingSphere = BoundingSphere;
  5351. })(BABYLON || (BABYLON = {}));
  5352. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5353. (function (BABYLON) {
  5354. var BoundingBox = (function () {
  5355. function BoundingBox(minimum, maximum) {
  5356. this.minimum = minimum;
  5357. this.maximum = maximum;
  5358. this.vectors = new Array();
  5359. this.vectorsWorld = new Array();
  5360. // Bounding vectors
  5361. this.vectors.push(this.minimum.clone());
  5362. this.vectors.push(this.maximum.clone());
  5363. this.vectors.push(this.minimum.clone());
  5364. this.vectors[2].x = this.maximum.x;
  5365. this.vectors.push(this.minimum.clone());
  5366. this.vectors[3].y = this.maximum.y;
  5367. this.vectors.push(this.minimum.clone());
  5368. this.vectors[4].z = this.maximum.z;
  5369. this.vectors.push(this.maximum.clone());
  5370. this.vectors[5].z = this.minimum.z;
  5371. this.vectors.push(this.maximum.clone());
  5372. this.vectors[6].x = this.minimum.x;
  5373. this.vectors.push(this.maximum.clone());
  5374. this.vectors[7].y = this.minimum.y;
  5375. // OBB
  5376. this.center = this.maximum.add(this.minimum).scale(0.5);
  5377. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5378. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5379. for (var index = 0; index < this.vectors.length; index++) {
  5380. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5381. }
  5382. this.minimumWorld = BABYLON.Vector3.Zero();
  5383. this.maximumWorld = BABYLON.Vector3.Zero();
  5384. this._update(BABYLON.Matrix.Identity());
  5385. }
  5386. // Methods
  5387. BoundingBox.prototype.getWorldMatrix = function () {
  5388. return this._worldMatrix;
  5389. };
  5390. BoundingBox.prototype._update = function (world) {
  5391. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5392. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5393. for (var index = 0; index < this.vectors.length; index++) {
  5394. var v = this.vectorsWorld[index];
  5395. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5396. if (v.x < this.minimumWorld.x)
  5397. this.minimumWorld.x = v.x;
  5398. if (v.y < this.minimumWorld.y)
  5399. this.minimumWorld.y = v.y;
  5400. if (v.z < this.minimumWorld.z)
  5401. this.minimumWorld.z = v.z;
  5402. if (v.x > this.maximumWorld.x)
  5403. this.maximumWorld.x = v.x;
  5404. if (v.y > this.maximumWorld.y)
  5405. this.maximumWorld.y = v.y;
  5406. if (v.z > this.maximumWorld.z)
  5407. this.maximumWorld.z = v.z;
  5408. }
  5409. // OBB
  5410. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5411. this.center.scaleInPlace(0.5);
  5412. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5413. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5414. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5415. this._worldMatrix = world;
  5416. };
  5417. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5418. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5419. };
  5420. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5421. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5422. };
  5423. BoundingBox.prototype.intersectsPoint = function (point) {
  5424. var delta = BABYLON.Engine.Epsilon;
  5425. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5426. return false;
  5427. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5428. return false;
  5429. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5430. return false;
  5431. return true;
  5432. };
  5433. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5434. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5435. };
  5436. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5437. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5438. return false;
  5439. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5440. return false;
  5441. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5442. return false;
  5443. return true;
  5444. };
  5445. // Statics
  5446. BoundingBox.Intersects = function (box0, box1) {
  5447. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5448. return false;
  5449. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5450. return false;
  5451. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5452. return false;
  5453. return true;
  5454. };
  5455. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5456. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5457. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5458. return (num <= (sphereRadius * sphereRadius));
  5459. };
  5460. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5461. for (var p = 0; p < 6; p++) {
  5462. for (var i = 0; i < 8; i++) {
  5463. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5464. return false;
  5465. }
  5466. }
  5467. }
  5468. return true;
  5469. };
  5470. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5471. for (var p = 0; p < 6; p++) {
  5472. var inCount = 8;
  5473. for (var i = 0; i < 8; i++) {
  5474. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5475. --inCount;
  5476. }
  5477. else {
  5478. break;
  5479. }
  5480. }
  5481. if (inCount === 0)
  5482. return false;
  5483. }
  5484. return true;
  5485. };
  5486. return BoundingBox;
  5487. })();
  5488. BABYLON.BoundingBox = BoundingBox;
  5489. })(BABYLON || (BABYLON = {}));
  5490. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5491. (function (BABYLON) {
  5492. var computeBoxExtents = function (axis, box) {
  5493. var p = BABYLON.Vector3.Dot(box.center, axis);
  5494. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5495. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5496. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5497. var r = r0 + r1 + r2;
  5498. return {
  5499. min: p - r,
  5500. max: p + r
  5501. };
  5502. };
  5503. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5504. var axisOverlap = function (axis, box0, box1) {
  5505. var result0 = computeBoxExtents(axis, box0);
  5506. var result1 = computeBoxExtents(axis, box1);
  5507. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5508. };
  5509. var BoundingInfo = (function () {
  5510. function BoundingInfo(minimum, maximum) {
  5511. this.minimum = minimum;
  5512. this.maximum = maximum;
  5513. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5514. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5515. }
  5516. // Methods
  5517. BoundingInfo.prototype._update = function (world) {
  5518. this.boundingBox._update(world);
  5519. this.boundingSphere._update(world);
  5520. };
  5521. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5522. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5523. return false;
  5524. return this.boundingBox.isInFrustum(frustumPlanes);
  5525. };
  5526. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5527. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5528. };
  5529. BoundingInfo.prototype._checkCollision = function (collider) {
  5530. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5531. };
  5532. BoundingInfo.prototype.intersectsPoint = function (point) {
  5533. if (!this.boundingSphere.centerWorld) {
  5534. return false;
  5535. }
  5536. if (!this.boundingSphere.intersectsPoint(point)) {
  5537. return false;
  5538. }
  5539. if (!this.boundingBox.intersectsPoint(point)) {
  5540. return false;
  5541. }
  5542. return true;
  5543. };
  5544. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5545. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5546. return false;
  5547. }
  5548. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5549. return false;
  5550. }
  5551. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5552. return false;
  5553. }
  5554. if (!precise) {
  5555. return true;
  5556. }
  5557. var box0 = this.boundingBox;
  5558. var box1 = boundingInfo.boundingBox;
  5559. if (!axisOverlap(box0.directions[0], box0, box1))
  5560. return false;
  5561. if (!axisOverlap(box0.directions[1], box0, box1))
  5562. return false;
  5563. if (!axisOverlap(box0.directions[2], box0, box1))
  5564. return false;
  5565. if (!axisOverlap(box1.directions[0], box0, box1))
  5566. return false;
  5567. if (!axisOverlap(box1.directions[1], box0, box1))
  5568. return false;
  5569. if (!axisOverlap(box1.directions[2], box0, box1))
  5570. return false;
  5571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5572. return false;
  5573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5574. return false;
  5575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5576. return false;
  5577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5578. return false;
  5579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5580. return false;
  5581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5582. return false;
  5583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5584. return false;
  5585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5586. return false;
  5587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5588. return false;
  5589. return true;
  5590. };
  5591. return BoundingInfo;
  5592. })();
  5593. BABYLON.BoundingInfo = BoundingInfo;
  5594. })(BABYLON || (BABYLON = {}));
  5595. //# sourceMappingURL=babylon.boundingInfo.js.map
  5596. var BABYLON;
  5597. (function (BABYLON) {
  5598. var Light = (function (_super) {
  5599. __extends(Light, _super);
  5600. function Light(name, scene) {
  5601. _super.call(this, name, scene);
  5602. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5603. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5604. this.intensity = 1.0;
  5605. this.range = Number.MAX_VALUE;
  5606. this.includedOnlyMeshes = new Array();
  5607. this.excludedMeshes = new Array();
  5608. this._excludedMeshesIds = new Array();
  5609. this._includedOnlyMeshesIds = new Array();
  5610. scene.lights.push(this);
  5611. }
  5612. Light.prototype.getShadowGenerator = function () {
  5613. return this._shadowGenerator;
  5614. };
  5615. Light.prototype.getAbsolutePosition = function () {
  5616. return BABYLON.Vector3.Zero();
  5617. };
  5618. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5619. };
  5620. Light.prototype._getWorldMatrix = function () {
  5621. return BABYLON.Matrix.Identity();
  5622. };
  5623. Light.prototype.canAffectMesh = function (mesh) {
  5624. if (!mesh) {
  5625. return true;
  5626. }
  5627. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5628. return false;
  5629. }
  5630. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5631. return false;
  5632. }
  5633. return true;
  5634. };
  5635. Light.prototype.getWorldMatrix = function () {
  5636. this._currentRenderId = this.getScene().getRenderId();
  5637. var worldMatrix = this._getWorldMatrix();
  5638. if (this.parent && this.parent.getWorldMatrix) {
  5639. if (!this._parentedWorldMatrix) {
  5640. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5641. }
  5642. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5643. return this._parentedWorldMatrix;
  5644. }
  5645. return worldMatrix;
  5646. };
  5647. Light.prototype.dispose = function () {
  5648. if (this._shadowGenerator) {
  5649. this._shadowGenerator.dispose();
  5650. this._shadowGenerator = null;
  5651. }
  5652. // Remove from scene
  5653. var index = this.getScene().lights.indexOf(this);
  5654. this.getScene().lights.splice(index, 1);
  5655. };
  5656. return Light;
  5657. })(BABYLON.Node);
  5658. BABYLON.Light = Light;
  5659. })(BABYLON || (BABYLON = {}));
  5660. //# sourceMappingURL=babylon.light.js.map
  5661. var BABYLON;
  5662. (function (BABYLON) {
  5663. var PointLight = (function (_super) {
  5664. __extends(PointLight, _super);
  5665. function PointLight(name, position, scene) {
  5666. _super.call(this, name, scene);
  5667. this.position = position;
  5668. }
  5669. PointLight.prototype.getAbsolutePosition = function () {
  5670. return this._transformedPosition ? this._transformedPosition : this.position;
  5671. };
  5672. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5673. if (this.parent && this.parent.getWorldMatrix) {
  5674. if (!this._transformedPosition) {
  5675. this._transformedPosition = BABYLON.Vector3.Zero();
  5676. }
  5677. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5678. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5679. return;
  5680. }
  5681. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5682. };
  5683. PointLight.prototype.getShadowGenerator = function () {
  5684. return null;
  5685. };
  5686. PointLight.prototype._getWorldMatrix = function () {
  5687. if (!this._worldMatrix) {
  5688. this._worldMatrix = BABYLON.Matrix.Identity();
  5689. }
  5690. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5691. return this._worldMatrix;
  5692. };
  5693. return PointLight;
  5694. })(BABYLON.Light);
  5695. BABYLON.PointLight = PointLight;
  5696. })(BABYLON || (BABYLON = {}));
  5697. //# sourceMappingURL=babylon.pointLight.js.map
  5698. var BABYLON;
  5699. (function (BABYLON) {
  5700. var SpotLight = (function (_super) {
  5701. __extends(SpotLight, _super);
  5702. function SpotLight(name, position, direction, angle, exponent, scene) {
  5703. _super.call(this, name, scene);
  5704. this.position = position;
  5705. this.direction = direction;
  5706. this.angle = angle;
  5707. this.exponent = exponent;
  5708. }
  5709. SpotLight.prototype.getAbsolutePosition = function () {
  5710. return this.transformedPosition ? this.transformedPosition : this.position;
  5711. };
  5712. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5713. var activeCamera = this.getScene().activeCamera;
  5714. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  5715. };
  5716. SpotLight.prototype.supportsVSM = function () {
  5717. return true;
  5718. };
  5719. SpotLight.prototype.needRefreshPerFrame = function () {
  5720. return false;
  5721. };
  5722. SpotLight.prototype.setDirectionToTarget = function (target) {
  5723. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5724. return this.direction;
  5725. };
  5726. SpotLight.prototype.computeTransformedPosition = function () {
  5727. if (this.parent && this.parent.getWorldMatrix) {
  5728. if (!this.transformedPosition) {
  5729. this.transformedPosition = BABYLON.Vector3.Zero();
  5730. }
  5731. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5732. return true;
  5733. }
  5734. return false;
  5735. };
  5736. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5737. var normalizeDirection;
  5738. if (this.parent && this.parent.getWorldMatrix) {
  5739. if (!this._transformedDirection) {
  5740. this._transformedDirection = BABYLON.Vector3.Zero();
  5741. }
  5742. this.computeTransformedPosition();
  5743. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5744. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5745. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5746. }
  5747. else {
  5748. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5749. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5750. }
  5751. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5752. };
  5753. SpotLight.prototype._getWorldMatrix = function () {
  5754. if (!this._worldMatrix) {
  5755. this._worldMatrix = BABYLON.Matrix.Identity();
  5756. }
  5757. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5758. return this._worldMatrix;
  5759. };
  5760. return SpotLight;
  5761. })(BABYLON.Light);
  5762. BABYLON.SpotLight = SpotLight;
  5763. })(BABYLON || (BABYLON = {}));
  5764. //# sourceMappingURL=babylon.spotLight.js.map
  5765. var BABYLON;
  5766. (function (BABYLON) {
  5767. var DirectionalLight = (function (_super) {
  5768. __extends(DirectionalLight, _super);
  5769. function DirectionalLight(name, direction, scene) {
  5770. _super.call(this, name, scene);
  5771. this.direction = direction;
  5772. this.shadowOrthoScale = 0.1;
  5773. this.position = direction.scale(-1);
  5774. }
  5775. DirectionalLight.prototype.getAbsolutePosition = function () {
  5776. return this.transformedPosition ? this.transformedPosition : this.position;
  5777. };
  5778. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5779. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5780. return this.direction;
  5781. };
  5782. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5783. var orthoLeft = Number.MAX_VALUE;
  5784. var orthoRight = Number.MIN_VALUE;
  5785. var orthoTop = Number.MIN_VALUE;
  5786. var orthoBottom = Number.MAX_VALUE;
  5787. var tempVector3 = BABYLON.Vector3.Zero();
  5788. var activeCamera = this.getScene().activeCamera;
  5789. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  5790. var mesh = renderList[meshIndex];
  5791. if (!mesh) {
  5792. continue;
  5793. }
  5794. var boundingInfo = mesh.getBoundingInfo();
  5795. if (!boundingInfo) {
  5796. continue;
  5797. }
  5798. var boundingBox = boundingInfo.boundingBox;
  5799. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  5800. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  5801. if (tempVector3.x < orthoLeft)
  5802. orthoLeft = tempVector3.x;
  5803. if (tempVector3.y < orthoBottom)
  5804. orthoBottom = tempVector3.y;
  5805. if (tempVector3.x > orthoRight)
  5806. orthoRight = tempVector3.x;
  5807. if (tempVector3.y > orthoTop)
  5808. orthoTop = tempVector3.y;
  5809. }
  5810. }
  5811. var xOffset = orthoRight - orthoLeft;
  5812. var yOffset = orthoTop - orthoBottom;
  5813. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  5814. };
  5815. DirectionalLight.prototype.supportsVSM = function () {
  5816. return true;
  5817. };
  5818. DirectionalLight.prototype.needRefreshPerFrame = function () {
  5819. return true;
  5820. };
  5821. DirectionalLight.prototype.computeTransformedPosition = function () {
  5822. if (this.parent && this.parent.getWorldMatrix) {
  5823. if (!this.transformedPosition) {
  5824. this.transformedPosition = BABYLON.Vector3.Zero();
  5825. }
  5826. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5827. return true;
  5828. }
  5829. return false;
  5830. };
  5831. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5832. if (this.parent && this.parent.getWorldMatrix) {
  5833. if (!this._transformedDirection) {
  5834. this._transformedDirection = BABYLON.Vector3.Zero();
  5835. }
  5836. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5837. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5838. return;
  5839. }
  5840. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5841. };
  5842. DirectionalLight.prototype._getWorldMatrix = function () {
  5843. if (!this._worldMatrix) {
  5844. this._worldMatrix = BABYLON.Matrix.Identity();
  5845. }
  5846. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5847. return this._worldMatrix;
  5848. };
  5849. return DirectionalLight;
  5850. })(BABYLON.Light);
  5851. BABYLON.DirectionalLight = DirectionalLight;
  5852. })(BABYLON || (BABYLON = {}));
  5853. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5854. (function (BABYLON) {
  5855. var ShadowGenerator = (function () {
  5856. function ShadowGenerator(mapSize, light) {
  5857. var _this = this;
  5858. // Members
  5859. this.filter = ShadowGenerator.FILTER_NONE;
  5860. this.blurScale = 2;
  5861. this._blurBoxOffset = 0;
  5862. this._darkness = 0;
  5863. this._bias = 0.00005;
  5864. this._transparencyShadow = false;
  5865. this._viewMatrix = BABYLON.Matrix.Zero();
  5866. this._projectionMatrix = BABYLON.Matrix.Zero();
  5867. this._transformMatrix = BABYLON.Matrix.Zero();
  5868. this._worldViewProjection = BABYLON.Matrix.Zero();
  5869. this._light = light;
  5870. this._scene = light.getScene();
  5871. this._mapSize = mapSize;
  5872. light._shadowGenerator = this;
  5873. // Render target
  5874. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5875. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5876. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5877. this._shadowMap.renderParticles = false;
  5878. this._shadowMap.onAfterUnbind = function () {
  5879. if (!_this.useBlurVarianceShadowMap) {
  5880. return;
  5881. }
  5882. if (!_this._shadowMap2) {
  5883. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  5884. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5885. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5886. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, _this._scene.getEngine());
  5887. _this._downSamplePostprocess.onApply = function (effect) {
  5888. effect.setTexture("textureSampler", _this._shadowMap);
  5889. };
  5890. _this.blurBoxOffset = 1;
  5891. }
  5892. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  5893. };
  5894. // Custom render function
  5895. var renderSubMesh = function (subMesh) {
  5896. var mesh = subMesh.getRenderingMesh();
  5897. var scene = _this._scene;
  5898. var engine = scene.getEngine();
  5899. // Culling
  5900. engine.setState(subMesh.getMaterial().backFaceCulling);
  5901. // Managing instances
  5902. var batch = mesh._getInstancesRenderList(subMesh._id);
  5903. if (batch.mustReturn) {
  5904. return;
  5905. }
  5906. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5907. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5908. engine.enableEffect(_this._effect);
  5909. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5910. var material = subMesh.getMaterial();
  5911. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5912. // Alpha test
  5913. if (material && material.needAlphaTesting()) {
  5914. var alphaTexture = material.getAlphaTestTexture();
  5915. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5916. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5917. }
  5918. // Bones
  5919. if (mesh.useBones) {
  5920. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5921. }
  5922. // Draw
  5923. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5924. }
  5925. else {
  5926. // Need to reset refresh rate of the shadowMap
  5927. _this._shadowMap.resetRefreshCounter();
  5928. }
  5929. };
  5930. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5931. var index;
  5932. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5933. renderSubMesh(opaqueSubMeshes.data[index]);
  5934. }
  5935. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5936. renderSubMesh(alphaTestSubMeshes.data[index]);
  5937. }
  5938. if (_this._transparencyShadow) {
  5939. for (index = 0; index < transparentSubMeshes.length; index++) {
  5940. renderSubMesh(transparentSubMeshes.data[index]);
  5941. }
  5942. }
  5943. };
  5944. this._shadowMap.onClear = function (engine) {
  5945. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  5946. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  5947. }
  5948. else {
  5949. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  5950. }
  5951. };
  5952. }
  5953. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5954. // Static
  5955. get: function () {
  5956. return ShadowGenerator._FILTER_NONE;
  5957. },
  5958. enumerable: true,
  5959. configurable: true
  5960. });
  5961. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5962. get: function () {
  5963. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5964. },
  5965. enumerable: true,
  5966. configurable: true
  5967. });
  5968. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5969. get: function () {
  5970. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5971. },
  5972. enumerable: true,
  5973. configurable: true
  5974. });
  5975. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  5976. get: function () {
  5977. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  5978. },
  5979. enumerable: true,
  5980. configurable: true
  5981. });
  5982. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  5983. get: function () {
  5984. return this._blurBoxOffset;
  5985. },
  5986. set: function (value) {
  5987. var _this = this;
  5988. if (this._blurBoxOffset === value) {
  5989. return;
  5990. }
  5991. this._blurBoxOffset = value;
  5992. if (this._boxBlurPostprocess) {
  5993. this._boxBlurPostprocess.dispose();
  5994. }
  5995. 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);
  5996. this._boxBlurPostprocess.onApply = function (effect) {
  5997. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  5998. };
  5999. },
  6000. enumerable: true,
  6001. configurable: true
  6002. });
  6003. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6004. get: function () {
  6005. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6006. },
  6007. set: function (value) {
  6008. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6009. },
  6010. enumerable: true,
  6011. configurable: true
  6012. });
  6013. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6014. get: function () {
  6015. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6016. },
  6017. set: function (value) {
  6018. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6019. },
  6020. enumerable: true,
  6021. configurable: true
  6022. });
  6023. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6024. get: function () {
  6025. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6026. },
  6027. set: function (value) {
  6028. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6029. },
  6030. enumerable: true,
  6031. configurable: true
  6032. });
  6033. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6034. var defines = [];
  6035. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6036. defines.push("#define VSM");
  6037. }
  6038. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6039. var mesh = subMesh.getMesh();
  6040. var material = subMesh.getMaterial();
  6041. // Alpha test
  6042. if (material && material.needAlphaTesting()) {
  6043. defines.push("#define ALPHATEST");
  6044. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6045. attribs.push(BABYLON.VertexBuffer.UVKind);
  6046. defines.push("#define UV1");
  6047. }
  6048. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6049. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6050. defines.push("#define UV2");
  6051. }
  6052. }
  6053. // Bones
  6054. if (mesh.useBones) {
  6055. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6056. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6057. defines.push("#define BONES");
  6058. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6059. }
  6060. // Instances
  6061. if (useInstances) {
  6062. defines.push("#define INSTANCES");
  6063. attribs.push("world0");
  6064. attribs.push("world1");
  6065. attribs.push("world2");
  6066. attribs.push("world3");
  6067. }
  6068. // Get correct effect
  6069. var join = defines.join("\n");
  6070. if (this._cachedDefines !== join) {
  6071. this._cachedDefines = join;
  6072. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6073. }
  6074. return this._effect.isReady();
  6075. };
  6076. ShadowGenerator.prototype.getShadowMap = function () {
  6077. return this._shadowMap;
  6078. };
  6079. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6080. if (this._shadowMap2) {
  6081. return this._shadowMap2;
  6082. }
  6083. return this._shadowMap;
  6084. };
  6085. ShadowGenerator.prototype.getLight = function () {
  6086. return this._light;
  6087. };
  6088. // Methods
  6089. ShadowGenerator.prototype.getTransformMatrix = function () {
  6090. var scene = this._scene;
  6091. if (this._currentRenderID === scene.getRenderId()) {
  6092. return this._transformMatrix;
  6093. }
  6094. this._currentRenderID = scene.getRenderId();
  6095. var lightPosition = this._light.position;
  6096. var lightDirection = this._light.direction;
  6097. if (this._light.computeTransformedPosition()) {
  6098. lightPosition = this._light.transformedPosition;
  6099. }
  6100. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6101. this._cachedPosition = lightPosition.clone();
  6102. this._cachedDirection = lightDirection.clone();
  6103. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6104. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6105. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6106. }
  6107. return this._transformMatrix;
  6108. };
  6109. ShadowGenerator.prototype.getDarkness = function () {
  6110. return this._darkness;
  6111. };
  6112. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6113. if (darkness >= 1.0)
  6114. this._darkness = 1.0;
  6115. else if (darkness <= 0.0)
  6116. this._darkness = 0.0;
  6117. else
  6118. this._darkness = darkness;
  6119. };
  6120. ShadowGenerator.prototype.getBias = function () {
  6121. return this._bias;
  6122. };
  6123. ShadowGenerator.prototype.setBias = function (bias) {
  6124. this._bias = bias;
  6125. };
  6126. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6127. this._transparencyShadow = hasShadow;
  6128. };
  6129. ShadowGenerator.prototype._packHalf = function (depth) {
  6130. var scale = depth * 255.0;
  6131. var fract = scale - Math.floor(scale);
  6132. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6133. };
  6134. ShadowGenerator.prototype.dispose = function () {
  6135. this._shadowMap.dispose();
  6136. if (this._shadowMap2) {
  6137. this._shadowMap2.dispose();
  6138. }
  6139. if (this._downSamplePostprocess) {
  6140. this._downSamplePostprocess.dispose();
  6141. }
  6142. if (this._boxBlurPostprocess) {
  6143. this._boxBlurPostprocess.dispose();
  6144. }
  6145. };
  6146. ShadowGenerator._FILTER_NONE = 0;
  6147. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6148. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6149. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6150. return ShadowGenerator;
  6151. })();
  6152. BABYLON.ShadowGenerator = ShadowGenerator;
  6153. })(BABYLON || (BABYLON = {}));
  6154. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6155. var BABYLON;
  6156. (function (BABYLON) {
  6157. var HemisphericLight = (function (_super) {
  6158. __extends(HemisphericLight, _super);
  6159. function HemisphericLight(name, direction, scene) {
  6160. _super.call(this, name, scene);
  6161. this.direction = direction;
  6162. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6163. }
  6164. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6165. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6166. return this.direction;
  6167. };
  6168. HemisphericLight.prototype.getShadowGenerator = function () {
  6169. return null;
  6170. };
  6171. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6172. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6173. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6174. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6175. };
  6176. HemisphericLight.prototype._getWorldMatrix = function () {
  6177. if (!this._worldMatrix) {
  6178. this._worldMatrix = BABYLON.Matrix.Identity();
  6179. }
  6180. return this._worldMatrix;
  6181. };
  6182. return HemisphericLight;
  6183. })(BABYLON.Light);
  6184. BABYLON.HemisphericLight = HemisphericLight;
  6185. })(BABYLON || (BABYLON = {}));
  6186. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6187. (function (BABYLON) {
  6188. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6189. if (boxMin.x > sphereCenter.x + sphereRadius)
  6190. return false;
  6191. if (sphereCenter.x - sphereRadius > boxMax.x)
  6192. return false;
  6193. if (boxMin.y > sphereCenter.y + sphereRadius)
  6194. return false;
  6195. if (sphereCenter.y - sphereRadius > boxMax.y)
  6196. return false;
  6197. if (boxMin.z > sphereCenter.z + sphereRadius)
  6198. return false;
  6199. if (sphereCenter.z - sphereRadius > boxMax.z)
  6200. return false;
  6201. return true;
  6202. };
  6203. var getLowestRoot = function (a, b, c, maxR) {
  6204. var determinant = b * b - 4.0 * a * c;
  6205. var result = { root: 0, found: false };
  6206. if (determinant < 0)
  6207. return result;
  6208. var sqrtD = Math.sqrt(determinant);
  6209. var r1 = (-b - sqrtD) / (2.0 * a);
  6210. var r2 = (-b + sqrtD) / (2.0 * a);
  6211. if (r1 > r2) {
  6212. var temp = r2;
  6213. r2 = r1;
  6214. r1 = temp;
  6215. }
  6216. if (r1 > 0 && r1 < maxR) {
  6217. result.root = r1;
  6218. result.found = true;
  6219. return result;
  6220. }
  6221. if (r2 > 0 && r2 < maxR) {
  6222. result.root = r2;
  6223. result.found = true;
  6224. return result;
  6225. }
  6226. return result;
  6227. };
  6228. var Collider = (function () {
  6229. function Collider() {
  6230. this.radius = new BABYLON.Vector3(1, 1, 1);
  6231. this.retry = 0;
  6232. this.basePointWorld = BABYLON.Vector3.Zero();
  6233. this.velocityWorld = BABYLON.Vector3.Zero();
  6234. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6235. this._collisionPoint = BABYLON.Vector3.Zero();
  6236. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6237. this._tempVector = BABYLON.Vector3.Zero();
  6238. this._tempVector2 = BABYLON.Vector3.Zero();
  6239. this._tempVector3 = BABYLON.Vector3.Zero();
  6240. this._tempVector4 = BABYLON.Vector3.Zero();
  6241. this._edge = BABYLON.Vector3.Zero();
  6242. this._baseToVertex = BABYLON.Vector3.Zero();
  6243. this._destinationPoint = BABYLON.Vector3.Zero();
  6244. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6245. this._displacementVector = BABYLON.Vector3.Zero();
  6246. }
  6247. // Methods
  6248. Collider.prototype._initialize = function (source, dir, e) {
  6249. this.velocity = dir;
  6250. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6251. this.basePoint = source;
  6252. source.multiplyToRef(this.radius, this.basePointWorld);
  6253. dir.multiplyToRef(this.radius, this.velocityWorld);
  6254. this.velocityWorldLength = this.velocityWorld.length();
  6255. this.epsilon = e;
  6256. this.collisionFound = false;
  6257. };
  6258. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6259. pa.subtractToRef(point, this._tempVector);
  6260. pb.subtractToRef(point, this._tempVector2);
  6261. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6262. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6263. if (d < 0)
  6264. return false;
  6265. pc.subtractToRef(point, this._tempVector3);
  6266. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6267. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6268. if (d < 0)
  6269. return false;
  6270. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6271. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6272. return d >= 0;
  6273. };
  6274. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6275. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6276. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6277. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6278. return false;
  6279. }
  6280. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6281. return false;
  6282. return true;
  6283. };
  6284. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6285. var t0;
  6286. var embeddedInPlane = false;
  6287. if (!subMesh._trianglePlanes) {
  6288. subMesh._trianglePlanes = [];
  6289. }
  6290. if (!subMesh._trianglePlanes[faceIndex]) {
  6291. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6292. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6293. }
  6294. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6295. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6296. return;
  6297. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6298. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6299. if (normalDotVelocity == 0) {
  6300. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6301. return;
  6302. embeddedInPlane = true;
  6303. t0 = 0;
  6304. }
  6305. else {
  6306. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6307. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6308. if (t0 > t1) {
  6309. var temp = t1;
  6310. t1 = t0;
  6311. t0 = temp;
  6312. }
  6313. if (t0 > 1.0 || t1 < 0.0)
  6314. return;
  6315. if (t0 < 0)
  6316. t0 = 0;
  6317. if (t0 > 1.0)
  6318. t0 = 1.0;
  6319. }
  6320. this._collisionPoint.copyFromFloats(0, 0, 0);
  6321. var found = false;
  6322. var t = 1.0;
  6323. if (!embeddedInPlane) {
  6324. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6325. this.velocity.scaleToRef(t0, this._tempVector);
  6326. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6327. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6328. found = true;
  6329. t = t0;
  6330. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6331. }
  6332. }
  6333. if (!found) {
  6334. var velocitySquaredLength = this.velocity.lengthSquared();
  6335. var a = velocitySquaredLength;
  6336. this.basePoint.subtractToRef(p1, this._tempVector);
  6337. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6338. var c = this._tempVector.lengthSquared() - 1.0;
  6339. var lowestRoot = getLowestRoot(a, b, c, t);
  6340. if (lowestRoot.found) {
  6341. t = lowestRoot.root;
  6342. found = true;
  6343. this._collisionPoint.copyFrom(p1);
  6344. }
  6345. this.basePoint.subtractToRef(p2, this._tempVector);
  6346. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6347. c = this._tempVector.lengthSquared() - 1.0;
  6348. lowestRoot = getLowestRoot(a, b, c, t);
  6349. if (lowestRoot.found) {
  6350. t = lowestRoot.root;
  6351. found = true;
  6352. this._collisionPoint.copyFrom(p2);
  6353. }
  6354. this.basePoint.subtractToRef(p3, this._tempVector);
  6355. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6356. c = this._tempVector.lengthSquared() - 1.0;
  6357. lowestRoot = getLowestRoot(a, b, c, t);
  6358. if (lowestRoot.found) {
  6359. t = lowestRoot.root;
  6360. found = true;
  6361. this._collisionPoint.copyFrom(p3);
  6362. }
  6363. p2.subtractToRef(p1, this._edge);
  6364. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6365. var edgeSquaredLength = this._edge.lengthSquared();
  6366. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6367. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6368. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6369. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6370. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6371. lowestRoot = getLowestRoot(a, b, c, t);
  6372. if (lowestRoot.found) {
  6373. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6374. if (f >= 0.0 && f <= 1.0) {
  6375. t = lowestRoot.root;
  6376. found = true;
  6377. this._edge.scaleInPlace(f);
  6378. p1.addToRef(this._edge, this._collisionPoint);
  6379. }
  6380. }
  6381. p3.subtractToRef(p2, this._edge);
  6382. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6383. edgeSquaredLength = this._edge.lengthSquared();
  6384. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6385. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6386. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6387. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6388. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6389. lowestRoot = getLowestRoot(a, b, c, t);
  6390. if (lowestRoot.found) {
  6391. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6392. if (f >= 0.0 && f <= 1.0) {
  6393. t = lowestRoot.root;
  6394. found = true;
  6395. this._edge.scaleInPlace(f);
  6396. p2.addToRef(this._edge, this._collisionPoint);
  6397. }
  6398. }
  6399. p1.subtractToRef(p3, this._edge);
  6400. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6401. edgeSquaredLength = this._edge.lengthSquared();
  6402. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6403. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6404. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6405. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6406. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6407. lowestRoot = getLowestRoot(a, b, c, t);
  6408. if (lowestRoot.found) {
  6409. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6410. if (f >= 0.0 && f <= 1.0) {
  6411. t = lowestRoot.root;
  6412. found = true;
  6413. this._edge.scaleInPlace(f);
  6414. p3.addToRef(this._edge, this._collisionPoint);
  6415. }
  6416. }
  6417. }
  6418. if (found) {
  6419. var distToCollision = t * this.velocity.length();
  6420. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6421. if (!this.intersectionPoint) {
  6422. this.intersectionPoint = this._collisionPoint.clone();
  6423. }
  6424. else {
  6425. this.intersectionPoint.copyFrom(this._collisionPoint);
  6426. }
  6427. this.nearestDistance = distToCollision;
  6428. this.collisionFound = true;
  6429. this.collidedMesh = subMesh.getMesh();
  6430. }
  6431. }
  6432. };
  6433. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6434. for (var i = indexStart; i < indexEnd; i += 3) {
  6435. var p1 = pts[indices[i] - decal];
  6436. var p2 = pts[indices[i + 1] - decal];
  6437. var p3 = pts[indices[i + 2] - decal];
  6438. this._testTriangle(i, subMesh, p3, p2, p1);
  6439. }
  6440. };
  6441. Collider.prototype._getResponse = function (pos, vel) {
  6442. pos.addToRef(vel, this._destinationPoint);
  6443. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6444. this.basePoint.addToRef(vel, pos);
  6445. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6446. this._slidePlaneNormal.normalize();
  6447. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6448. pos.addInPlace(this._displacementVector);
  6449. this.intersectionPoint.addInPlace(this._displacementVector);
  6450. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6451. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6452. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6453. };
  6454. return Collider;
  6455. })();
  6456. BABYLON.Collider = Collider;
  6457. })(BABYLON || (BABYLON = {}));
  6458. //# sourceMappingURL=babylon.collider.js.map
  6459. var BABYLON;
  6460. (function (BABYLON) {
  6461. var Camera = (function (_super) {
  6462. __extends(Camera, _super);
  6463. function Camera(name, position, scene) {
  6464. _super.call(this, name, scene);
  6465. this.position = position;
  6466. // Members
  6467. this.upVector = BABYLON.Vector3.Up();
  6468. this.orthoLeft = null;
  6469. this.orthoRight = null;
  6470. this.orthoBottom = null;
  6471. this.orthoTop = null;
  6472. this.fov = 0.8;
  6473. this.minZ = 1.0;
  6474. this.maxZ = 10000.0;
  6475. this.inertia = 0.9;
  6476. this.mode = Camera.PERSPECTIVE_CAMERA;
  6477. this.isIntermediate = false;
  6478. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6479. this.subCameras = [];
  6480. this.layerMask = 0xFFFFFFFF;
  6481. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6482. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6483. this._projectionMatrix = new BABYLON.Matrix();
  6484. this._postProcesses = new Array();
  6485. this._postProcessesTakenIndices = [];
  6486. this._activeMeshes = new BABYLON.SmartArray(256);
  6487. scene.cameras.push(this);
  6488. if (!scene.activeCamera) {
  6489. scene.activeCamera = this;
  6490. }
  6491. }
  6492. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6493. get: function () {
  6494. return Camera._PERSPECTIVE_CAMERA;
  6495. },
  6496. enumerable: true,
  6497. configurable: true
  6498. });
  6499. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6500. get: function () {
  6501. return Camera._ORTHOGRAPHIC_CAMERA;
  6502. },
  6503. enumerable: true,
  6504. configurable: true
  6505. });
  6506. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6507. get: function () {
  6508. return Camera._FOVMODE_VERTICAL_FIXED;
  6509. },
  6510. enumerable: true,
  6511. configurable: true
  6512. });
  6513. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6514. get: function () {
  6515. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6516. },
  6517. enumerable: true,
  6518. configurable: true
  6519. });
  6520. Camera.prototype.getActiveMeshes = function () {
  6521. return this._activeMeshes;
  6522. };
  6523. Camera.prototype.isActiveMesh = function (mesh) {
  6524. return (this._activeMeshes.indexOf(mesh) !== -1);
  6525. };
  6526. //Cache
  6527. Camera.prototype._initCache = function () {
  6528. _super.prototype._initCache.call(this);
  6529. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6530. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6531. this._cache.mode = undefined;
  6532. this._cache.minZ = undefined;
  6533. this._cache.maxZ = undefined;
  6534. this._cache.fov = undefined;
  6535. this._cache.aspectRatio = undefined;
  6536. this._cache.orthoLeft = undefined;
  6537. this._cache.orthoRight = undefined;
  6538. this._cache.orthoBottom = undefined;
  6539. this._cache.orthoTop = undefined;
  6540. this._cache.renderWidth = undefined;
  6541. this._cache.renderHeight = undefined;
  6542. };
  6543. Camera.prototype._updateCache = function (ignoreParentClass) {
  6544. if (!ignoreParentClass) {
  6545. _super.prototype._updateCache.call(this);
  6546. }
  6547. var engine = this.getEngine();
  6548. this._cache.position.copyFrom(this.position);
  6549. this._cache.upVector.copyFrom(this.upVector);
  6550. this._cache.mode = this.mode;
  6551. this._cache.minZ = this.minZ;
  6552. this._cache.maxZ = this.maxZ;
  6553. this._cache.fov = this.fov;
  6554. this._cache.aspectRatio = engine.getAspectRatio(this);
  6555. this._cache.orthoLeft = this.orthoLeft;
  6556. this._cache.orthoRight = this.orthoRight;
  6557. this._cache.orthoBottom = this.orthoBottom;
  6558. this._cache.orthoTop = this.orthoTop;
  6559. this._cache.renderWidth = engine.getRenderWidth();
  6560. this._cache.renderHeight = engine.getRenderHeight();
  6561. };
  6562. Camera.prototype._updateFromScene = function () {
  6563. this.updateCache();
  6564. this._update();
  6565. };
  6566. // Synchronized
  6567. Camera.prototype._isSynchronized = function () {
  6568. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6569. };
  6570. Camera.prototype._isSynchronizedViewMatrix = function () {
  6571. if (!_super.prototype._isSynchronized.call(this))
  6572. return false;
  6573. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6574. };
  6575. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6576. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6577. if (!check) {
  6578. return false;
  6579. }
  6580. var engine = this.getEngine();
  6581. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6582. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6583. }
  6584. else {
  6585. 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();
  6586. }
  6587. return check;
  6588. };
  6589. // Controls
  6590. Camera.prototype.attachControl = function (element) {
  6591. };
  6592. Camera.prototype.detachControl = function (element) {
  6593. };
  6594. Camera.prototype._update = function () {
  6595. };
  6596. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6597. if (insertAt === void 0) { insertAt = null; }
  6598. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6599. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6600. return 0;
  6601. }
  6602. if (insertAt == null || insertAt < 0) {
  6603. this._postProcesses.push(postProcess);
  6604. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6605. return this._postProcesses.length - 1;
  6606. }
  6607. var add = 0;
  6608. if (this._postProcesses[insertAt]) {
  6609. var start = this._postProcesses.length - 1;
  6610. for (var i = start; i >= insertAt + 1; --i) {
  6611. this._postProcesses[i + 1] = this._postProcesses[i];
  6612. }
  6613. add = 1;
  6614. }
  6615. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6616. if (this._postProcessesTakenIndices[i] < insertAt) {
  6617. continue;
  6618. }
  6619. start = this._postProcessesTakenIndices.length - 1;
  6620. for (var j = start; j >= i; --j) {
  6621. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6622. }
  6623. this._postProcessesTakenIndices[i] = insertAt;
  6624. break;
  6625. }
  6626. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6627. this._postProcessesTakenIndices.push(insertAt);
  6628. }
  6629. var result = insertAt + add;
  6630. this._postProcesses[result] = postProcess;
  6631. return result;
  6632. };
  6633. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6634. if (atIndices === void 0) { atIndices = null; }
  6635. var result = [];
  6636. if (!atIndices) {
  6637. var length = this._postProcesses.length;
  6638. for (var i = 0; i < length; i++) {
  6639. if (this._postProcesses[i] !== postProcess) {
  6640. continue;
  6641. }
  6642. delete this._postProcesses[i];
  6643. var index = this._postProcessesTakenIndices.indexOf(i);
  6644. this._postProcessesTakenIndices.splice(index, 1);
  6645. }
  6646. }
  6647. else {
  6648. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6649. for (i = 0; i < atIndices.length; i++) {
  6650. var foundPostProcess = this._postProcesses[atIndices[i]];
  6651. if (foundPostProcess !== postProcess) {
  6652. result.push(i);
  6653. continue;
  6654. }
  6655. delete this._postProcesses[atIndices[i]];
  6656. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6657. this._postProcessesTakenIndices.splice(index, 1);
  6658. }
  6659. }
  6660. return result;
  6661. };
  6662. Camera.prototype.getWorldMatrix = function () {
  6663. if (!this._worldMatrix) {
  6664. this._worldMatrix = BABYLON.Matrix.Identity();
  6665. }
  6666. var viewMatrix = this.getViewMatrix();
  6667. viewMatrix.invertToRef(this._worldMatrix);
  6668. return this._worldMatrix;
  6669. };
  6670. Camera.prototype._getViewMatrix = function () {
  6671. return BABYLON.Matrix.Identity();
  6672. };
  6673. Camera.prototype.getViewMatrix = function () {
  6674. this._computedViewMatrix = this._computeViewMatrix();
  6675. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6676. return this._computedViewMatrix;
  6677. }
  6678. if (!this._worldMatrix) {
  6679. this._worldMatrix = BABYLON.Matrix.Identity();
  6680. }
  6681. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6682. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6683. this._computedViewMatrix.invert();
  6684. this._currentRenderId = this.getScene().getRenderId();
  6685. return this._computedViewMatrix;
  6686. };
  6687. Camera.prototype._computeViewMatrix = function (force) {
  6688. if (!force && this._isSynchronizedViewMatrix()) {
  6689. return this._computedViewMatrix;
  6690. }
  6691. this._computedViewMatrix = this._getViewMatrix();
  6692. if (!this.parent || !this.parent.getWorldMatrix) {
  6693. this._currentRenderId = this.getScene().getRenderId();
  6694. }
  6695. return this._computedViewMatrix;
  6696. };
  6697. Camera.prototype.getProjectionMatrix = function (force) {
  6698. if (!force && this._isSynchronizedProjectionMatrix()) {
  6699. return this._projectionMatrix;
  6700. }
  6701. var engine = this.getEngine();
  6702. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6703. if (this.minZ <= 0) {
  6704. this.minZ = 0.1;
  6705. }
  6706. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6707. return this._projectionMatrix;
  6708. }
  6709. var halfWidth = engine.getRenderWidth() / 2.0;
  6710. var halfHeight = engine.getRenderHeight() / 2.0;
  6711. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6712. return this._projectionMatrix;
  6713. };
  6714. Camera.prototype.dispose = function () {
  6715. // Remove from scene
  6716. var index = this.getScene().cameras.indexOf(this);
  6717. this.getScene().cameras.splice(index, 1);
  6718. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6719. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6720. }
  6721. };
  6722. // Statics
  6723. Camera._PERSPECTIVE_CAMERA = 0;
  6724. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6725. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6726. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6727. return Camera;
  6728. })(BABYLON.Node);
  6729. BABYLON.Camera = Camera;
  6730. })(BABYLON || (BABYLON = {}));
  6731. //# sourceMappingURL=babylon.camera.js.map
  6732. var BABYLON;
  6733. (function (BABYLON) {
  6734. var TargetCamera = (function (_super) {
  6735. __extends(TargetCamera, _super);
  6736. function TargetCamera(name, position, scene) {
  6737. _super.call(this, name, position, scene);
  6738. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6739. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6740. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6741. this.speed = 2.0;
  6742. this.noRotationConstraint = false;
  6743. this.lockedTarget = null;
  6744. this._currentTarget = BABYLON.Vector3.Zero();
  6745. this._viewMatrix = BABYLON.Matrix.Zero();
  6746. this._camMatrix = BABYLON.Matrix.Zero();
  6747. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6748. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6749. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6750. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6751. this._lookAtTemp = BABYLON.Matrix.Zero();
  6752. this._tempMatrix = BABYLON.Matrix.Zero();
  6753. }
  6754. TargetCamera.prototype._getLockedTargetPosition = function () {
  6755. if (!this.lockedTarget) {
  6756. return null;
  6757. }
  6758. return this.lockedTarget.position || this.lockedTarget;
  6759. };
  6760. // Cache
  6761. TargetCamera.prototype._initCache = function () {
  6762. _super.prototype._initCache.call(this);
  6763. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6764. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6765. };
  6766. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6767. if (!ignoreParentClass) {
  6768. _super.prototype._updateCache.call(this);
  6769. }
  6770. var lockedTargetPosition = this._getLockedTargetPosition();
  6771. if (!lockedTargetPosition) {
  6772. this._cache.lockedTarget = null;
  6773. }
  6774. else {
  6775. if (!this._cache.lockedTarget) {
  6776. this._cache.lockedTarget = lockedTargetPosition.clone();
  6777. }
  6778. else {
  6779. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6780. }
  6781. }
  6782. this._cache.rotation.copyFrom(this.rotation);
  6783. };
  6784. // Synchronized
  6785. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6786. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6787. return false;
  6788. }
  6789. var lockedTargetPosition = this._getLockedTargetPosition();
  6790. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6791. };
  6792. // Methods
  6793. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6794. var engine = this.getEngine();
  6795. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6796. };
  6797. // Target
  6798. TargetCamera.prototype.setTarget = function (target) {
  6799. this.upVector.normalize();
  6800. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6801. this._camMatrix.invert();
  6802. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6803. var vDir = target.subtract(this.position);
  6804. if (vDir.x >= 0.0) {
  6805. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6806. }
  6807. else {
  6808. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6809. }
  6810. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6811. if (isNaN(this.rotation.x)) {
  6812. this.rotation.x = 0;
  6813. }
  6814. if (isNaN(this.rotation.y)) {
  6815. this.rotation.y = 0;
  6816. }
  6817. if (isNaN(this.rotation.z)) {
  6818. this.rotation.z = 0;
  6819. }
  6820. };
  6821. TargetCamera.prototype.getTarget = function () {
  6822. return this._currentTarget;
  6823. };
  6824. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6825. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6826. };
  6827. TargetCamera.prototype._updatePosition = function () {
  6828. this.position.addInPlace(this.cameraDirection);
  6829. };
  6830. TargetCamera.prototype._update = function () {
  6831. var needToMove = this._decideIfNeedsToMove();
  6832. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6833. // Move
  6834. if (needToMove) {
  6835. this._updatePosition();
  6836. }
  6837. // Rotate
  6838. if (needToRotate) {
  6839. this.rotation.x += this.cameraRotation.x;
  6840. this.rotation.y += this.cameraRotation.y;
  6841. if (!this.noRotationConstraint) {
  6842. var limit = (Math.PI / 2) * 0.95;
  6843. if (this.rotation.x > limit)
  6844. this.rotation.x = limit;
  6845. if (this.rotation.x < -limit)
  6846. this.rotation.x = -limit;
  6847. }
  6848. }
  6849. // Inertia
  6850. if (needToMove) {
  6851. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6852. this.cameraDirection.x = 0;
  6853. }
  6854. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6855. this.cameraDirection.y = 0;
  6856. }
  6857. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6858. this.cameraDirection.z = 0;
  6859. }
  6860. this.cameraDirection.scaleInPlace(this.inertia);
  6861. }
  6862. if (needToRotate) {
  6863. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6864. this.cameraRotation.x = 0;
  6865. }
  6866. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6867. this.cameraRotation.y = 0;
  6868. }
  6869. this.cameraRotation.scaleInPlace(this.inertia);
  6870. }
  6871. };
  6872. TargetCamera.prototype._getViewMatrix = function () {
  6873. if (!this.lockedTarget) {
  6874. // Compute
  6875. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6876. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6877. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6878. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6879. this._lookAtTemp.invert();
  6880. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6881. }
  6882. else {
  6883. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6884. }
  6885. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6886. // Computing target and final matrix
  6887. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6888. }
  6889. else {
  6890. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6891. }
  6892. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6893. return this._viewMatrix;
  6894. };
  6895. return TargetCamera;
  6896. })(BABYLON.Camera);
  6897. BABYLON.TargetCamera = TargetCamera;
  6898. })(BABYLON || (BABYLON = {}));
  6899. //# sourceMappingURL=babylon.targetCamera.js.map
  6900. var BABYLON;
  6901. (function (BABYLON) {
  6902. var FollowCamera = (function (_super) {
  6903. __extends(FollowCamera, _super);
  6904. function FollowCamera(name, position, scene) {
  6905. _super.call(this, name, position, scene);
  6906. this.radius = 12;
  6907. this.rotationOffset = 0;
  6908. this.heightOffset = 4;
  6909. this.cameraAcceleration = 0.05;
  6910. this.maxCameraSpeed = 20;
  6911. }
  6912. FollowCamera.prototype.getRadians = function (degrees) {
  6913. return degrees * Math.PI / 180;
  6914. };
  6915. FollowCamera.prototype.follow = function (cameraTarget) {
  6916. if (!cameraTarget)
  6917. return;
  6918. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6919. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6920. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6921. var dx = targetX - this.position.x;
  6922. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6923. var dz = (targetZ) - this.position.z;
  6924. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6925. var vy = dy * this.cameraAcceleration;
  6926. var vz = dz * this.cameraAcceleration * 2;
  6927. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6928. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6929. }
  6930. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6931. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6932. }
  6933. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6934. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6935. }
  6936. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6937. this.setTarget(cameraTarget.position);
  6938. };
  6939. FollowCamera.prototype._update = function () {
  6940. _super.prototype._update.call(this);
  6941. this.follow(this.target);
  6942. };
  6943. return FollowCamera;
  6944. })(BABYLON.TargetCamera);
  6945. BABYLON.FollowCamera = FollowCamera;
  6946. })(BABYLON || (BABYLON = {}));
  6947. //# sourceMappingURL=babylon.followCamera.js.map
  6948. var BABYLON;
  6949. (function (BABYLON) {
  6950. var FreeCamera = (function (_super) {
  6951. __extends(FreeCamera, _super);
  6952. function FreeCamera(name, position, scene) {
  6953. _super.call(this, name, position, scene);
  6954. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6955. this.keysUp = [38];
  6956. this.keysDown = [40];
  6957. this.keysLeft = [37];
  6958. this.keysRight = [39];
  6959. this.checkCollisions = false;
  6960. this.applyGravity = false;
  6961. this.angularSensibility = 2000.0;
  6962. this._keys = [];
  6963. this._collider = new BABYLON.Collider();
  6964. this._needMoveForGravity = true;
  6965. this._oldPosition = BABYLON.Vector3.Zero();
  6966. this._diffPosition = BABYLON.Vector3.Zero();
  6967. this._newPosition = BABYLON.Vector3.Zero();
  6968. }
  6969. // Controls
  6970. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6971. var _this = this;
  6972. var previousPosition;
  6973. var engine = this.getEngine();
  6974. if (this._attachedElement) {
  6975. return;
  6976. }
  6977. this._attachedElement = element;
  6978. if (this._onMouseDown === undefined) {
  6979. this._onMouseDown = function (evt) {
  6980. previousPosition = {
  6981. x: evt.clientX,
  6982. y: evt.clientY
  6983. };
  6984. if (!noPreventDefault) {
  6985. evt.preventDefault();
  6986. }
  6987. };
  6988. this._onMouseUp = function (evt) {
  6989. previousPosition = null;
  6990. if (!noPreventDefault) {
  6991. evt.preventDefault();
  6992. }
  6993. };
  6994. this._onMouseOut = function (evt) {
  6995. previousPosition = null;
  6996. _this._keys = [];
  6997. if (!noPreventDefault) {
  6998. evt.preventDefault();
  6999. }
  7000. };
  7001. this._onMouseMove = function (evt) {
  7002. if (!previousPosition && !engine.isPointerLock) {
  7003. return;
  7004. }
  7005. var offsetX;
  7006. var offsetY;
  7007. if (!engine.isPointerLock) {
  7008. offsetX = evt.clientX - previousPosition.x;
  7009. offsetY = evt.clientY - previousPosition.y;
  7010. }
  7011. else {
  7012. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7013. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7014. }
  7015. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7016. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7017. previousPosition = {
  7018. x: evt.clientX,
  7019. y: evt.clientY
  7020. };
  7021. if (!noPreventDefault) {
  7022. evt.preventDefault();
  7023. }
  7024. };
  7025. this._onKeyDown = function (evt) {
  7026. 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) {
  7027. var index = _this._keys.indexOf(evt.keyCode);
  7028. if (index === -1) {
  7029. _this._keys.push(evt.keyCode);
  7030. }
  7031. if (!noPreventDefault) {
  7032. evt.preventDefault();
  7033. }
  7034. }
  7035. };
  7036. this._onKeyUp = function (evt) {
  7037. 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) {
  7038. var index = _this._keys.indexOf(evt.keyCode);
  7039. if (index >= 0) {
  7040. _this._keys.splice(index, 1);
  7041. }
  7042. if (!noPreventDefault) {
  7043. evt.preventDefault();
  7044. }
  7045. }
  7046. };
  7047. this._onLostFocus = function () {
  7048. _this._keys = [];
  7049. };
  7050. this._reset = function () {
  7051. _this._keys = [];
  7052. previousPosition = null;
  7053. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7054. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7055. };
  7056. }
  7057. element.addEventListener("mousedown", this._onMouseDown, false);
  7058. element.addEventListener("mouseup", this._onMouseUp, false);
  7059. element.addEventListener("mouseout", this._onMouseOut, false);
  7060. element.addEventListener("mousemove", this._onMouseMove, false);
  7061. BABYLON.Tools.RegisterTopRootEvents([
  7062. { name: "keydown", handler: this._onKeyDown },
  7063. { name: "keyup", handler: this._onKeyUp },
  7064. { name: "blur", handler: this._onLostFocus }
  7065. ]);
  7066. };
  7067. FreeCamera.prototype.detachControl = function (element) {
  7068. if (this._attachedElement != element) {
  7069. return;
  7070. }
  7071. element.removeEventListener("mousedown", this._onMouseDown);
  7072. element.removeEventListener("mouseup", this._onMouseUp);
  7073. element.removeEventListener("mouseout", this._onMouseOut);
  7074. element.removeEventListener("mousemove", this._onMouseMove);
  7075. BABYLON.Tools.UnregisterTopRootEvents([
  7076. { name: "keydown", handler: this._onKeyDown },
  7077. { name: "keyup", handler: this._onKeyUp },
  7078. { name: "blur", handler: this._onLostFocus }
  7079. ]);
  7080. this._attachedElement = null;
  7081. if (this._reset) {
  7082. this._reset();
  7083. }
  7084. };
  7085. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7086. var globalPosition;
  7087. if (this.parent) {
  7088. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7089. }
  7090. else {
  7091. globalPosition = this.position;
  7092. }
  7093. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7094. this._collider.radius = this.ellipsoid;
  7095. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7096. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7097. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7098. this.position.addInPlace(this._diffPosition);
  7099. if (this.onCollide) {
  7100. this.onCollide(this._collider.collidedMesh);
  7101. }
  7102. }
  7103. };
  7104. FreeCamera.prototype._checkInputs = function () {
  7105. if (!this._localDirection) {
  7106. this._localDirection = BABYLON.Vector3.Zero();
  7107. this._transformedDirection = BABYLON.Vector3.Zero();
  7108. }
  7109. for (var index = 0; index < this._keys.length; index++) {
  7110. var keyCode = this._keys[index];
  7111. var speed = this._computeLocalCameraSpeed();
  7112. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7113. this._localDirection.copyFromFloats(-speed, 0, 0);
  7114. }
  7115. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7116. this._localDirection.copyFromFloats(0, 0, speed);
  7117. }
  7118. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7119. this._localDirection.copyFromFloats(speed, 0, 0);
  7120. }
  7121. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7122. this._localDirection.copyFromFloats(0, 0, -speed);
  7123. }
  7124. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7125. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7126. this.cameraDirection.addInPlace(this._transformedDirection);
  7127. }
  7128. };
  7129. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7130. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7131. };
  7132. FreeCamera.prototype._updatePosition = function () {
  7133. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7134. this._collideWithWorld(this.cameraDirection);
  7135. if (this.applyGravity) {
  7136. var oldPosition = this.position;
  7137. this._collideWithWorld(this.getScene().gravity);
  7138. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7139. }
  7140. }
  7141. else {
  7142. this.position.addInPlace(this.cameraDirection);
  7143. }
  7144. };
  7145. FreeCamera.prototype._update = function () {
  7146. this._checkInputs();
  7147. _super.prototype._update.call(this);
  7148. };
  7149. return FreeCamera;
  7150. })(BABYLON.TargetCamera);
  7151. BABYLON.FreeCamera = FreeCamera;
  7152. })(BABYLON || (BABYLON = {}));
  7153. //# sourceMappingURL=babylon.freeCamera.js.map
  7154. var BABYLON;
  7155. (function (BABYLON) {
  7156. // We're mainly based on the logic defined into the FreeCamera code
  7157. var TouchCamera = (function (_super) {
  7158. __extends(TouchCamera, _super);
  7159. function TouchCamera(name, position, scene) {
  7160. _super.call(this, name, position, scene);
  7161. this._offsetX = null;
  7162. this._offsetY = null;
  7163. this._pointerCount = 0;
  7164. this._pointerPressed = [];
  7165. this.angularSensibility = 200000.0;
  7166. this.moveSensibility = 500.0;
  7167. }
  7168. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7169. var _this = this;
  7170. var previousPosition;
  7171. if (this._attachedCanvas) {
  7172. return;
  7173. }
  7174. this._attachedCanvas = canvas;
  7175. if (this._onPointerDown === undefined) {
  7176. this._onPointerDown = function (evt) {
  7177. if (!noPreventDefault) {
  7178. evt.preventDefault();
  7179. }
  7180. _this._pointerPressed.push(evt.pointerId);
  7181. if (_this._pointerPressed.length !== 1) {
  7182. return;
  7183. }
  7184. previousPosition = {
  7185. x: evt.clientX,
  7186. y: evt.clientY
  7187. };
  7188. };
  7189. this._onPointerUp = function (evt) {
  7190. if (!noPreventDefault) {
  7191. evt.preventDefault();
  7192. }
  7193. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7194. if (index === -1) {
  7195. return;
  7196. }
  7197. _this._pointerPressed.splice(index, 1);
  7198. if (index != 0) {
  7199. return;
  7200. }
  7201. previousPosition = null;
  7202. _this._offsetX = null;
  7203. _this._offsetY = null;
  7204. };
  7205. this._onPointerMove = function (evt) {
  7206. if (!noPreventDefault) {
  7207. evt.preventDefault();
  7208. }
  7209. if (!previousPosition) {
  7210. return;
  7211. }
  7212. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7213. if (index != 0) {
  7214. return;
  7215. }
  7216. _this._offsetX = evt.clientX - previousPosition.x;
  7217. _this._offsetY = -(evt.clientY - previousPosition.y);
  7218. };
  7219. this._onLostFocus = function () {
  7220. _this._offsetX = null;
  7221. _this._offsetY = null;
  7222. };
  7223. }
  7224. canvas.addEventListener("pointerdown", this._onPointerDown);
  7225. canvas.addEventListener("pointerup", this._onPointerUp);
  7226. canvas.addEventListener("pointerout", this._onPointerUp);
  7227. canvas.addEventListener("pointermove", this._onPointerMove);
  7228. BABYLON.Tools.RegisterTopRootEvents([
  7229. { name: "blur", handler: this._onLostFocus }
  7230. ]);
  7231. };
  7232. TouchCamera.prototype.detachControl = function (canvas) {
  7233. if (this._attachedCanvas != canvas) {
  7234. return;
  7235. }
  7236. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7237. canvas.removeEventListener("pointerup", this._onPointerUp);
  7238. canvas.removeEventListener("pointerout", this._onPointerUp);
  7239. canvas.removeEventListener("pointermove", this._onPointerMove);
  7240. BABYLON.Tools.UnregisterTopRootEvents([
  7241. { name: "blur", handler: this._onLostFocus }
  7242. ]);
  7243. this._attachedCanvas = null;
  7244. };
  7245. TouchCamera.prototype._checkInputs = function () {
  7246. if (!this._offsetX) {
  7247. return;
  7248. }
  7249. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7250. if (this._pointerPressed.length > 1) {
  7251. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7252. }
  7253. else {
  7254. var speed = this._computeLocalCameraSpeed();
  7255. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7256. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7257. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7258. }
  7259. };
  7260. return TouchCamera;
  7261. })(BABYLON.FreeCamera);
  7262. BABYLON.TouchCamera = TouchCamera;
  7263. })(BABYLON || (BABYLON = {}));
  7264. //# sourceMappingURL=babylon.touchCamera.js.map
  7265. var BABYLON;
  7266. (function (BABYLON) {
  7267. // We're mainly based on the logic defined into the FreeCamera code
  7268. var DeviceOrientationCamera = (function (_super) {
  7269. __extends(DeviceOrientationCamera, _super);
  7270. function DeviceOrientationCamera(name, position, scene) {
  7271. var _this = this;
  7272. _super.call(this, name, position, scene);
  7273. this._offsetX = null;
  7274. this._offsetY = null;
  7275. this._orientationGamma = 0;
  7276. this._orientationBeta = 0;
  7277. this._initialOrientationGamma = 0;
  7278. this._initialOrientationBeta = 0;
  7279. this.angularSensibility = 10000.0;
  7280. this.moveSensibility = 50.0;
  7281. window.addEventListener("resize", function () {
  7282. _this._initialOrientationGamma = null;
  7283. }, false);
  7284. }
  7285. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7286. var _this = this;
  7287. if (this._attachedCanvas) {
  7288. return;
  7289. }
  7290. this._attachedCanvas = canvas;
  7291. if (!this._orientationChanged) {
  7292. this._orientationChanged = function (evt) {
  7293. if (!_this._initialOrientationGamma) {
  7294. _this._initialOrientationGamma = evt.gamma;
  7295. _this._initialOrientationBeta = evt.beta;
  7296. }
  7297. _this._orientationGamma = evt.gamma;
  7298. _this._orientationBeta = evt.beta;
  7299. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7300. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7301. };
  7302. }
  7303. window.addEventListener("deviceorientation", this._orientationChanged);
  7304. };
  7305. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7306. if (this._attachedCanvas != canvas) {
  7307. return;
  7308. }
  7309. window.removeEventListener("deviceorientation", this._orientationChanged);
  7310. this._attachedCanvas = null;
  7311. this._orientationGamma = 0;
  7312. this._orientationBeta = 0;
  7313. this._initialOrientationGamma = 0;
  7314. this._initialOrientationBeta = 0;
  7315. };
  7316. DeviceOrientationCamera.prototype._checkInputs = function () {
  7317. if (!this._offsetX) {
  7318. return;
  7319. }
  7320. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7321. var speed = this._computeLocalCameraSpeed();
  7322. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7323. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7324. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7325. };
  7326. return DeviceOrientationCamera;
  7327. })(BABYLON.FreeCamera);
  7328. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7329. })(BABYLON || (BABYLON = {}));
  7330. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7331. var BABYLON;
  7332. (function (BABYLON) {
  7333. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7334. var ArcRotateCamera = (function (_super) {
  7335. __extends(ArcRotateCamera, _super);
  7336. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7337. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7338. this.alpha = alpha;
  7339. this.beta = beta;
  7340. this.radius = radius;
  7341. this.target = target;
  7342. this.inertialAlphaOffset = 0;
  7343. this.inertialBetaOffset = 0;
  7344. this.inertialRadiusOffset = 0;
  7345. this.lowerAlphaLimit = null;
  7346. this.upperAlphaLimit = null;
  7347. this.lowerBetaLimit = 0.01;
  7348. this.upperBetaLimit = Math.PI;
  7349. this.lowerRadiusLimit = null;
  7350. this.upperRadiusLimit = null;
  7351. this.angularSensibility = 1000.0;
  7352. this.wheelPrecision = 3.0;
  7353. this.keysUp = [38];
  7354. this.keysDown = [40];
  7355. this.keysLeft = [37];
  7356. this.keysRight = [39];
  7357. this.zoomOnFactor = 1;
  7358. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7359. this._keys = [];
  7360. this._viewMatrix = new BABYLON.Matrix();
  7361. this.checkCollisions = false;
  7362. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7363. this._collider = new BABYLON.Collider();
  7364. this._previousPosition = BABYLON.Vector3.Zero();
  7365. this._collisionVelocity = BABYLON.Vector3.Zero();
  7366. this._newPosition = BABYLON.Vector3.Zero();
  7367. // Pinch
  7368. // value for pinch step scaling
  7369. // set to 20 by default
  7370. this.pinchPrecision = 20;
  7371. this.getViewMatrix();
  7372. }
  7373. ArcRotateCamera.prototype._getTargetPosition = function () {
  7374. return this.target.position || this.target;
  7375. };
  7376. // Cache
  7377. ArcRotateCamera.prototype._initCache = function () {
  7378. _super.prototype._initCache.call(this);
  7379. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7380. this._cache.alpha = undefined;
  7381. this._cache.beta = undefined;
  7382. this._cache.radius = undefined;
  7383. this._cache.targetScreenOffset = undefined;
  7384. };
  7385. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7386. if (!ignoreParentClass) {
  7387. _super.prototype._updateCache.call(this);
  7388. }
  7389. this._cache.target.copyFrom(this._getTargetPosition());
  7390. this._cache.alpha = this.alpha;
  7391. this._cache.beta = this.beta;
  7392. this._cache.radius = this.radius;
  7393. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7394. };
  7395. // Synchronized
  7396. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7397. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7398. return false;
  7399. 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);
  7400. };
  7401. // Methods
  7402. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7403. var _this = this;
  7404. var previousPosition;
  7405. var pointerId;
  7406. // to know if pinch started
  7407. var pinchStarted = false;
  7408. // two pinch point on X
  7409. // that will use for find if user action is pinch open or pinch close
  7410. var pinchPointX1, pinchPointX2;
  7411. if (this._attachedElement) {
  7412. return;
  7413. }
  7414. this._attachedElement = element;
  7415. var engine = this.getEngine();
  7416. if (this._onPointerDown === undefined) {
  7417. this._onPointerDown = function (evt) {
  7418. if (pointerId) {
  7419. return;
  7420. }
  7421. pointerId = evt.pointerId;
  7422. previousPosition = {
  7423. x: evt.clientX,
  7424. y: evt.clientY
  7425. };
  7426. if (!noPreventDefault) {
  7427. evt.preventDefault();
  7428. }
  7429. };
  7430. this._onPointerUp = function (evt) {
  7431. previousPosition = null;
  7432. pointerId = null;
  7433. if (!noPreventDefault) {
  7434. evt.preventDefault();
  7435. }
  7436. };
  7437. this._onPointerMove = function (evt) {
  7438. if (!previousPosition) {
  7439. return;
  7440. }
  7441. if (pointerId !== evt.pointerId) {
  7442. return;
  7443. }
  7444. // return pinch is started
  7445. if (pinchStarted) {
  7446. return;
  7447. }
  7448. var offsetX = evt.clientX - previousPosition.x;
  7449. var offsetY = evt.clientY - previousPosition.y;
  7450. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7451. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7452. previousPosition = {
  7453. x: evt.clientX,
  7454. y: evt.clientY
  7455. };
  7456. if (!noPreventDefault) {
  7457. evt.preventDefault();
  7458. }
  7459. };
  7460. this._onMouseMove = function (evt) {
  7461. if (!engine.isPointerLock) {
  7462. return;
  7463. }
  7464. // return pinch is started
  7465. if (pinchStarted) {
  7466. return;
  7467. }
  7468. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7469. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7470. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7471. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7472. if (!noPreventDefault) {
  7473. evt.preventDefault();
  7474. }
  7475. };
  7476. this._wheel = function (event) {
  7477. var delta = 0;
  7478. if (event.wheelDelta) {
  7479. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7480. }
  7481. else if (event.detail) {
  7482. delta = -event.detail / _this.wheelPrecision;
  7483. }
  7484. if (delta)
  7485. _this.inertialRadiusOffset += delta;
  7486. if (event.preventDefault) {
  7487. if (!noPreventDefault) {
  7488. event.preventDefault();
  7489. }
  7490. }
  7491. };
  7492. this._onKeyDown = function (evt) {
  7493. 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) {
  7494. var index = _this._keys.indexOf(evt.keyCode);
  7495. if (index === -1) {
  7496. _this._keys.push(evt.keyCode);
  7497. }
  7498. if (evt.preventDefault) {
  7499. if (!noPreventDefault) {
  7500. evt.preventDefault();
  7501. }
  7502. }
  7503. }
  7504. };
  7505. this._onKeyUp = function (evt) {
  7506. 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) {
  7507. var index = _this._keys.indexOf(evt.keyCode);
  7508. if (index >= 0) {
  7509. _this._keys.splice(index, 1);
  7510. }
  7511. if (evt.preventDefault) {
  7512. if (!noPreventDefault) {
  7513. evt.preventDefault();
  7514. }
  7515. }
  7516. }
  7517. };
  7518. this._onLostFocus = function () {
  7519. _this._keys = [];
  7520. pointerId = null;
  7521. };
  7522. this._onGestureStart = function (e) {
  7523. if (window.MSGesture === undefined) {
  7524. return;
  7525. }
  7526. if (!_this._MSGestureHandler) {
  7527. _this._MSGestureHandler = new MSGesture();
  7528. _this._MSGestureHandler.target = element;
  7529. }
  7530. _this._MSGestureHandler.addPointer(e.pointerId);
  7531. };
  7532. this._onGesture = function (e) {
  7533. _this.radius *= e.scale;
  7534. if (e.preventDefault) {
  7535. if (!noPreventDefault) {
  7536. e.stopPropagation();
  7537. e.preventDefault();
  7538. }
  7539. }
  7540. };
  7541. this._reset = function () {
  7542. _this._keys = [];
  7543. _this.inertialAlphaOffset = 0;
  7544. _this.inertialBetaOffset = 0;
  7545. _this.inertialRadiusOffset = 0;
  7546. previousPosition = null;
  7547. pointerId = null;
  7548. };
  7549. this._touchStart = function (event) {
  7550. if (event.touches.length === 2) {
  7551. //-- start pinch if two fingers on the screen
  7552. pinchStarted = true;
  7553. _this._pinchStart(event);
  7554. }
  7555. };
  7556. this._touchMove = function (event) {
  7557. if (pinchStarted) {
  7558. //-- make scaling
  7559. _this._pinchMove(event);
  7560. }
  7561. };
  7562. this._touchEnd = function (event) {
  7563. if (pinchStarted) {
  7564. //-- end of pinch
  7565. _this._pinchEnd(event);
  7566. }
  7567. };
  7568. this._pinchStart = function (event) {
  7569. // save origin touch point
  7570. pinchPointX1 = event.touches[0].clientX;
  7571. pinchPointX2 = event.touches[1].clientX;
  7572. // block the camera
  7573. // if not it rotate around target during pinch
  7574. pinchStarted = true;
  7575. };
  7576. this._pinchMove = function (event) {
  7577. // variable for new camera's radius
  7578. var delta = 0;
  7579. // variables to know if pinch open or pinch close
  7580. var direction = 1;
  7581. var distanceXOrigine, distanceXNow;
  7582. if (event.touches.length !== 2)
  7583. return;
  7584. // calculate absolute distances of the two fingers
  7585. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7586. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7587. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7588. if (distanceXNow < distanceXOrigine) {
  7589. direction = -1;
  7590. }
  7591. // calculate new radius
  7592. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7593. // set new radius
  7594. _this.inertialRadiusOffset -= delta;
  7595. // save origin touch point
  7596. pinchPointX1 = event.touches[0].clientX;
  7597. pinchPointX2 = event.touches[1].clientX;
  7598. };
  7599. this._pinchEnd = function (event) {
  7600. // cancel pinch and deblock camera rotation
  7601. pinchStarted = false;
  7602. };
  7603. }
  7604. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7605. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7606. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7607. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7608. element.addEventListener("mousemove", this._onMouseMove, false);
  7609. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7610. element.addEventListener("MSGestureChange", this._onGesture, false);
  7611. element.addEventListener('mousewheel', this._wheel, false);
  7612. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7613. // pinch
  7614. element.addEventListener('touchstart', this._touchStart, false);
  7615. element.addEventListener('touchmove', this._touchMove, false);
  7616. element.addEventListener('touchend', this._touchEnd, false);
  7617. BABYLON.Tools.RegisterTopRootEvents([
  7618. { name: "keydown", handler: this._onKeyDown },
  7619. { name: "keyup", handler: this._onKeyUp },
  7620. { name: "blur", handler: this._onLostFocus }
  7621. ]);
  7622. };
  7623. ArcRotateCamera.prototype.detachControl = function (element) {
  7624. if (this._attachedElement != element) {
  7625. return;
  7626. }
  7627. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7628. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7629. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7630. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7631. element.removeEventListener("mousemove", this._onMouseMove);
  7632. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7633. element.removeEventListener("MSGestureChange", this._onGesture);
  7634. element.removeEventListener('mousewheel', this._wheel);
  7635. element.removeEventListener('DOMMouseScroll', this._wheel);
  7636. // pinch
  7637. element.removeEventListener('touchstart', this._touchStart);
  7638. element.removeEventListener('touchmove', this._touchMove);
  7639. element.removeEventListener('touchend', this._touchEnd);
  7640. BABYLON.Tools.UnregisterTopRootEvents([
  7641. { name: "keydown", handler: this._onKeyDown },
  7642. { name: "keyup", handler: this._onKeyUp },
  7643. { name: "blur", handler: this._onLostFocus }
  7644. ]);
  7645. this._MSGestureHandler = null;
  7646. this._attachedElement = null;
  7647. if (this._reset) {
  7648. this._reset();
  7649. }
  7650. };
  7651. ArcRotateCamera.prototype._update = function () {
  7652. for (var index = 0; index < this._keys.length; index++) {
  7653. var keyCode = this._keys[index];
  7654. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7655. this.inertialAlphaOffset -= 0.01;
  7656. }
  7657. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7658. this.inertialBetaOffset -= 0.01;
  7659. }
  7660. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7661. this.inertialAlphaOffset += 0.01;
  7662. }
  7663. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7664. this.inertialBetaOffset += 0.01;
  7665. }
  7666. }
  7667. // Inertia
  7668. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7669. this.alpha += this.inertialAlphaOffset;
  7670. this.beta += this.inertialBetaOffset;
  7671. this.radius -= this.inertialRadiusOffset;
  7672. this.inertialAlphaOffset *= this.inertia;
  7673. this.inertialBetaOffset *= this.inertia;
  7674. this.inertialRadiusOffset *= this.inertia;
  7675. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7676. this.inertialAlphaOffset = 0;
  7677. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7678. this.inertialBetaOffset = 0;
  7679. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7680. this.inertialRadiusOffset = 0;
  7681. }
  7682. // Limits
  7683. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7684. this.alpha = this.lowerAlphaLimit;
  7685. }
  7686. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7687. this.alpha = this.upperAlphaLimit;
  7688. }
  7689. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7690. this.beta = this.lowerBetaLimit;
  7691. }
  7692. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7693. this.beta = this.upperBetaLimit;
  7694. }
  7695. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7696. this.radius = this.lowerRadiusLimit;
  7697. }
  7698. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7699. this.radius = this.upperRadiusLimit;
  7700. }
  7701. };
  7702. ArcRotateCamera.prototype.setPosition = function (position) {
  7703. var radiusv3 = position.subtract(this._getTargetPosition());
  7704. this.radius = radiusv3.length();
  7705. // Alpha
  7706. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7707. if (radiusv3.z < 0) {
  7708. this.alpha = 2 * Math.PI - this.alpha;
  7709. }
  7710. // Beta
  7711. this.beta = Math.acos(radiusv3.y / this.radius);
  7712. };
  7713. ArcRotateCamera.prototype._getViewMatrix = function () {
  7714. // Compute
  7715. var cosa = Math.cos(this.alpha);
  7716. var sina = Math.sin(this.alpha);
  7717. var cosb = Math.cos(this.beta);
  7718. var sinb = Math.sin(this.beta);
  7719. var target = this._getTargetPosition();
  7720. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7721. if (this.checkCollisions) {
  7722. this._collider.radius = this.collisionRadius;
  7723. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7724. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7725. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7726. this.position.copyFrom(this._previousPosition);
  7727. this.alpha = this._previousAlpha;
  7728. this.beta = this._previousBeta;
  7729. this.radius = this._previousRadius;
  7730. if (this.onCollide) {
  7731. this.onCollide(this._collider.collidedMesh);
  7732. }
  7733. }
  7734. }
  7735. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7736. this._previousAlpha = this.alpha;
  7737. this._previousBeta = this.beta;
  7738. this._previousRadius = this.radius;
  7739. this._previousPosition.copyFrom(this.position);
  7740. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7741. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7742. return this._viewMatrix;
  7743. };
  7744. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7745. meshes = meshes || this.getScene().meshes;
  7746. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7747. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7748. this.radius = distance * this.zoomOnFactor;
  7749. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7750. };
  7751. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7752. var meshesOrMinMaxVector;
  7753. var distance;
  7754. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7755. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7756. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7757. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7758. }
  7759. else {
  7760. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7761. distance = meshesOrMinMaxVectorAndDistance.distance;
  7762. }
  7763. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7764. this.maxZ = distance * 2;
  7765. };
  7766. return ArcRotateCamera;
  7767. })(BABYLON.Camera);
  7768. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7769. })(BABYLON || (BABYLON = {}));
  7770. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7771. (function (BABYLON) {
  7772. /**
  7773. * Represents a scene to be rendered by the engine.
  7774. * @see http://doc.babylonjs.com/page.php?p=21911
  7775. */
  7776. var Scene = (function () {
  7777. /**
  7778. * @constructor
  7779. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7780. */
  7781. function Scene(engine) {
  7782. // Members
  7783. this.autoClear = true;
  7784. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7785. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7786. this.forceWireframe = false;
  7787. this.forcePointsCloud = false;
  7788. this.forceShowBoundingBoxes = false;
  7789. this.animationsEnabled = true;
  7790. 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
  7791. // Fog
  7792. /**
  7793. * is fog enabled on this scene.
  7794. * @type {boolean}
  7795. */
  7796. this.fogEnabled = true;
  7797. this.fogMode = Scene.FOGMODE_NONE;
  7798. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7799. this.fogDensity = 0.1;
  7800. this.fogStart = 0;
  7801. this.fogEnd = 1000.0;
  7802. // Lights
  7803. /**
  7804. * is shadow enabled on this scene.
  7805. * @type {boolean}
  7806. */
  7807. this.shadowsEnabled = true;
  7808. /**
  7809. * is light enabled on this scene.
  7810. * @type {boolean}
  7811. */
  7812. this.lightsEnabled = true;
  7813. /**
  7814. * All of the lights added to this scene.
  7815. * @see BABYLON.Light
  7816. * @type {BABYLON.Light[]}
  7817. */
  7818. this.lights = new Array();
  7819. // Cameras
  7820. /**
  7821. * All of the cameras added to this scene.
  7822. * @see BABYLON.Camera
  7823. * @type {BABYLON.Camera[]}
  7824. */
  7825. this.cameras = new Array();
  7826. this.activeCameras = new Array();
  7827. // Meshes
  7828. /**
  7829. * All of the (abstract) meshes added to this scene.
  7830. * @see BABYLON.AbstractMesh
  7831. * @type {BABYLON.AbstractMesh[]}
  7832. */
  7833. this.meshes = new Array();
  7834. // Geometries
  7835. this._geometries = new Array();
  7836. this.materials = new Array();
  7837. this.multiMaterials = new Array();
  7838. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7839. // Textures
  7840. this.texturesEnabled = true;
  7841. this.textures = new Array();
  7842. // Particles
  7843. this.particlesEnabled = true;
  7844. this.particleSystems = new Array();
  7845. // Sprites
  7846. this.spritesEnabled = true;
  7847. this.spriteManagers = new Array();
  7848. // Layers
  7849. this.layers = new Array();
  7850. // Skeletons
  7851. this.skeletonsEnabled = true;
  7852. this.skeletons = new Array();
  7853. // Lens flares
  7854. this.lensFlaresEnabled = true;
  7855. this.lensFlareSystems = new Array();
  7856. // Collisions
  7857. this.collisionsEnabled = true;
  7858. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7859. // Postprocesses
  7860. this.postProcessesEnabled = true;
  7861. // Customs render targets
  7862. this.renderTargetsEnabled = true;
  7863. this.dumpNextRenderTargets = false;
  7864. this.customRenderTargets = new Array();
  7865. // Imported meshes
  7866. this.importedMeshesFiles = new Array();
  7867. this._actionManagers = new Array();
  7868. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7869. // Procedural textures
  7870. this.proceduralTexturesEnabled = true;
  7871. this._proceduralTextures = new Array();
  7872. this.soundTracks = new Array();
  7873. this._audioEnabled = true;
  7874. this._totalVertices = 0;
  7875. this._activeVertices = 0;
  7876. this._activeParticles = 0;
  7877. this._lastFrameDuration = 0;
  7878. this._evaluateActiveMeshesDuration = 0;
  7879. this._renderTargetsDuration = 0;
  7880. this._particlesDuration = 0;
  7881. this._renderDuration = 0;
  7882. this._spritesDuration = 0;
  7883. this._animationRatio = 0;
  7884. this._renderId = 0;
  7885. this._executeWhenReadyTimeoutId = -1;
  7886. this._toBeDisposed = new BABYLON.SmartArray(256);
  7887. this._onReadyCallbacks = new Array();
  7888. this._pendingData = []; //ANY
  7889. this._onBeforeRenderCallbacks = new Array();
  7890. this._onAfterRenderCallbacks = new Array();
  7891. this._activeMeshes = new BABYLON.SmartArray(256);
  7892. this._processedMaterials = new BABYLON.SmartArray(256);
  7893. this._renderTargets = new BABYLON.SmartArray(256);
  7894. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7895. this._activeSkeletons = new BABYLON.SmartArray(32);
  7896. this._activeBones = 0;
  7897. this._activeAnimatables = new Array();
  7898. this._transformMatrix = BABYLON.Matrix.Zero();
  7899. this._scaledPosition = BABYLON.Vector3.Zero();
  7900. this._scaledVelocity = BABYLON.Vector3.Zero();
  7901. this._engine = engine;
  7902. engine.scenes.push(this);
  7903. this._renderingManager = new BABYLON.RenderingManager(this);
  7904. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7905. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7906. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7907. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7908. this.attachControl();
  7909. this._debugLayer = new BABYLON.DebugLayer(this);
  7910. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7911. //simplification queue
  7912. this.simplificationQueue = new BABYLON.SimplificationQueue();
  7913. }
  7914. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7915. get: function () {
  7916. return Scene._FOGMODE_NONE;
  7917. },
  7918. enumerable: true,
  7919. configurable: true
  7920. });
  7921. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7922. get: function () {
  7923. return Scene._FOGMODE_EXP;
  7924. },
  7925. enumerable: true,
  7926. configurable: true
  7927. });
  7928. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7929. get: function () {
  7930. return Scene._FOGMODE_EXP2;
  7931. },
  7932. enumerable: true,
  7933. configurable: true
  7934. });
  7935. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7936. get: function () {
  7937. return Scene._FOGMODE_LINEAR;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. Object.defineProperty(Scene.prototype, "debugLayer", {
  7943. // Properties
  7944. get: function () {
  7945. return this._debugLayer;
  7946. },
  7947. enumerable: true,
  7948. configurable: true
  7949. });
  7950. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7951. /**
  7952. * The mesh that is currently under the pointer.
  7953. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7954. */
  7955. get: function () {
  7956. return this._meshUnderPointer;
  7957. },
  7958. enumerable: true,
  7959. configurable: true
  7960. });
  7961. Object.defineProperty(Scene.prototype, "pointerX", {
  7962. /**
  7963. * Current on-screen X position of the pointer
  7964. * @return {number} X position of the pointer
  7965. */
  7966. get: function () {
  7967. return this._pointerX;
  7968. },
  7969. enumerable: true,
  7970. configurable: true
  7971. });
  7972. Object.defineProperty(Scene.prototype, "pointerY", {
  7973. /**
  7974. * Current on-screen Y position of the pointer
  7975. * @return {number} Y position of the pointer
  7976. */
  7977. get: function () {
  7978. return this._pointerY;
  7979. },
  7980. enumerable: true,
  7981. configurable: true
  7982. });
  7983. Scene.prototype.getCachedMaterial = function () {
  7984. return this._cachedMaterial;
  7985. };
  7986. Scene.prototype.getBoundingBoxRenderer = function () {
  7987. return this._boundingBoxRenderer;
  7988. };
  7989. Scene.prototype.getOutlineRenderer = function () {
  7990. return this._outlineRenderer;
  7991. };
  7992. Scene.prototype.getEngine = function () {
  7993. return this._engine;
  7994. };
  7995. Scene.prototype.getTotalVertices = function () {
  7996. return this._totalVertices;
  7997. };
  7998. Scene.prototype.getActiveVertices = function () {
  7999. return this._activeVertices;
  8000. };
  8001. Scene.prototype.getActiveParticles = function () {
  8002. return this._activeParticles;
  8003. };
  8004. Scene.prototype.getActiveBones = function () {
  8005. return this._activeBones;
  8006. };
  8007. // Stats
  8008. Scene.prototype.getLastFrameDuration = function () {
  8009. return this._lastFrameDuration;
  8010. };
  8011. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8012. return this._evaluateActiveMeshesDuration;
  8013. };
  8014. Scene.prototype.getActiveMeshes = function () {
  8015. return this._activeMeshes;
  8016. };
  8017. Scene.prototype.getRenderTargetsDuration = function () {
  8018. return this._renderTargetsDuration;
  8019. };
  8020. Scene.prototype.getRenderDuration = function () {
  8021. return this._renderDuration;
  8022. };
  8023. Scene.prototype.getParticlesDuration = function () {
  8024. return this._particlesDuration;
  8025. };
  8026. Scene.prototype.getSpritesDuration = function () {
  8027. return this._spritesDuration;
  8028. };
  8029. Scene.prototype.getAnimationRatio = function () {
  8030. return this._animationRatio;
  8031. };
  8032. Scene.prototype.getRenderId = function () {
  8033. return this._renderId;
  8034. };
  8035. Scene.prototype.incrementRenderId = function () {
  8036. this._renderId++;
  8037. };
  8038. Scene.prototype._updatePointerPosition = function (evt) {
  8039. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8040. this._pointerX = evt.clientX - canvasRect.left;
  8041. this._pointerY = evt.clientY - canvasRect.top;
  8042. if (this.cameraToUseForPointers) {
  8043. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8044. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8045. }
  8046. };
  8047. // Pointers handling
  8048. Scene.prototype.attachControl = function () {
  8049. var _this = this;
  8050. this._onPointerMove = function (evt) {
  8051. var canvas = _this._engine.getRenderingCanvas();
  8052. _this._updatePointerPosition(evt);
  8053. 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);
  8054. if (pickResult.hit) {
  8055. _this._meshUnderPointer = pickResult.pickedMesh;
  8056. _this.setPointerOverMesh(pickResult.pickedMesh);
  8057. canvas.style.cursor = "pointer";
  8058. }
  8059. else {
  8060. _this.setPointerOverMesh(null);
  8061. canvas.style.cursor = "";
  8062. _this._meshUnderPointer = null;
  8063. }
  8064. };
  8065. this._onPointerDown = function (evt) {
  8066. var predicate = null;
  8067. if (!_this.onPointerDown) {
  8068. predicate = function (mesh) {
  8069. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8070. };
  8071. }
  8072. _this._updatePointerPosition(evt);
  8073. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8074. if (pickResult.hit) {
  8075. if (pickResult.pickedMesh.actionManager) {
  8076. switch (evt.button) {
  8077. case 0:
  8078. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8079. break;
  8080. case 1:
  8081. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8082. break;
  8083. case 2:
  8084. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8085. break;
  8086. }
  8087. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8088. }
  8089. }
  8090. if (_this.onPointerDown) {
  8091. _this.onPointerDown(evt, pickResult);
  8092. }
  8093. };
  8094. this._onKeyDown = function (evt) {
  8095. if (_this.actionManager) {
  8096. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8097. }
  8098. };
  8099. this._onKeyUp = function (evt) {
  8100. if (_this.actionManager) {
  8101. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8102. }
  8103. };
  8104. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8105. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8106. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8107. BABYLON.Tools.RegisterTopRootEvents([
  8108. { name: "keydown", handler: this._onKeyDown },
  8109. { name: "keyup", handler: this._onKeyUp }
  8110. ]);
  8111. };
  8112. Scene.prototype.detachControl = function () {
  8113. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8114. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8115. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8116. BABYLON.Tools.UnregisterTopRootEvents([
  8117. { name: "keydown", handler: this._onKeyDown },
  8118. { name: "keyup", handler: this._onKeyUp }
  8119. ]);
  8120. };
  8121. // Ready
  8122. Scene.prototype.isReady = function () {
  8123. if (this._pendingData.length > 0) {
  8124. return false;
  8125. }
  8126. for (var index = 0; index < this._geometries.length; index++) {
  8127. var geometry = this._geometries[index];
  8128. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8129. return false;
  8130. }
  8131. }
  8132. for (index = 0; index < this.meshes.length; index++) {
  8133. var mesh = this.meshes[index];
  8134. if (!mesh.isReady()) {
  8135. return false;
  8136. }
  8137. var mat = mesh.material;
  8138. if (mat) {
  8139. if (!mat.isReady(mesh)) {
  8140. return false;
  8141. }
  8142. }
  8143. }
  8144. return true;
  8145. };
  8146. Scene.prototype.resetCachedMaterial = function () {
  8147. this._cachedMaterial = null;
  8148. };
  8149. Scene.prototype.registerBeforeRender = function (func) {
  8150. this._onBeforeRenderCallbacks.push(func);
  8151. };
  8152. Scene.prototype.unregisterBeforeRender = function (func) {
  8153. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8154. if (index > -1) {
  8155. this._onBeforeRenderCallbacks.splice(index, 1);
  8156. }
  8157. };
  8158. Scene.prototype.registerAfterRender = function (func) {
  8159. this._onAfterRenderCallbacks.push(func);
  8160. };
  8161. Scene.prototype.unregisterAfterRender = function (func) {
  8162. var index = this._onAfterRenderCallbacks.indexOf(func);
  8163. if (index > -1) {
  8164. this._onAfterRenderCallbacks.splice(index, 1);
  8165. }
  8166. };
  8167. Scene.prototype._addPendingData = function (data) {
  8168. this._pendingData.push(data);
  8169. };
  8170. Scene.prototype._removePendingData = function (data) {
  8171. var index = this._pendingData.indexOf(data);
  8172. if (index !== -1) {
  8173. this._pendingData.splice(index, 1);
  8174. }
  8175. };
  8176. Scene.prototype.getWaitingItemsCount = function () {
  8177. return this._pendingData.length;
  8178. };
  8179. /**
  8180. * Registers a function to be executed when the scene is ready.
  8181. * @param {Function} func - the function to be executed.
  8182. */
  8183. Scene.prototype.executeWhenReady = function (func) {
  8184. var _this = this;
  8185. this._onReadyCallbacks.push(func);
  8186. if (this._executeWhenReadyTimeoutId !== -1) {
  8187. return;
  8188. }
  8189. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8190. _this._checkIsReady();
  8191. }, 150);
  8192. };
  8193. Scene.prototype._checkIsReady = function () {
  8194. var _this = this;
  8195. if (this.isReady()) {
  8196. this._onReadyCallbacks.forEach(function (func) {
  8197. func();
  8198. });
  8199. this._onReadyCallbacks = [];
  8200. this._executeWhenReadyTimeoutId = -1;
  8201. return;
  8202. }
  8203. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8204. _this._checkIsReady();
  8205. }, 150);
  8206. };
  8207. // Animations
  8208. /**
  8209. * Will start the animation sequence of a given target
  8210. * @param target - the target
  8211. * @param {number} from - from which frame should animation start
  8212. * @param {number} to - till which frame should animation run.
  8213. * @param {boolean} [loop] - should the animation loop
  8214. * @param {number} [speedRatio] - the speed in which to run the animation
  8215. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8216. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8217. * @return {BABYLON.Animatable} the animatable object created for this animation
  8218. * @see BABYLON.Animatable
  8219. * @see http://doc.babylonjs.com/page.php?p=22081
  8220. */
  8221. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8222. if (speedRatio === undefined) {
  8223. speedRatio = 1.0;
  8224. }
  8225. this.stopAnimation(target);
  8226. if (!animatable) {
  8227. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8228. }
  8229. // Local animations
  8230. if (target.animations) {
  8231. animatable.appendAnimations(target, target.animations);
  8232. }
  8233. // Children animations
  8234. if (target.getAnimatables) {
  8235. var animatables = target.getAnimatables();
  8236. for (var index = 0; index < animatables.length; index++) {
  8237. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8238. }
  8239. }
  8240. return animatable;
  8241. };
  8242. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8243. if (speedRatio === undefined) {
  8244. speedRatio = 1.0;
  8245. }
  8246. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8247. return animatable;
  8248. };
  8249. Scene.prototype.getAnimatableByTarget = function (target) {
  8250. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8251. if (this._activeAnimatables[index].target === target) {
  8252. return this._activeAnimatables[index];
  8253. }
  8254. }
  8255. return null;
  8256. };
  8257. /**
  8258. * Will stop the animation of the given target
  8259. * @param target - the target
  8260. * @see beginAnimation
  8261. */
  8262. Scene.prototype.stopAnimation = function (target) {
  8263. var animatable = this.getAnimatableByTarget(target);
  8264. if (animatable) {
  8265. animatable.stop();
  8266. }
  8267. };
  8268. Scene.prototype._animate = function () {
  8269. if (!this.animationsEnabled) {
  8270. return;
  8271. }
  8272. if (!this._animationStartDate) {
  8273. this._animationStartDate = BABYLON.Tools.Now;
  8274. }
  8275. // Getting time
  8276. var now = BABYLON.Tools.Now;
  8277. var delay = now - this._animationStartDate;
  8278. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8279. if (!this._activeAnimatables[index]._animate(delay)) {
  8280. this._activeAnimatables.splice(index, 1);
  8281. index--;
  8282. }
  8283. }
  8284. };
  8285. // Matrix
  8286. Scene.prototype.getViewMatrix = function () {
  8287. return this._viewMatrix;
  8288. };
  8289. Scene.prototype.getProjectionMatrix = function () {
  8290. return this._projectionMatrix;
  8291. };
  8292. Scene.prototype.getTransformMatrix = function () {
  8293. return this._transformMatrix;
  8294. };
  8295. Scene.prototype.setTransformMatrix = function (view, projection) {
  8296. this._viewMatrix = view;
  8297. this._projectionMatrix = projection;
  8298. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8299. };
  8300. // Methods
  8301. /**
  8302. * sets the active camera of the scene using its ID
  8303. * @param {string} id - the camera's ID
  8304. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8305. * @see activeCamera
  8306. */
  8307. Scene.prototype.setActiveCameraByID = function (id) {
  8308. var camera = this.getCameraByID(id);
  8309. if (camera) {
  8310. this.activeCamera = camera;
  8311. return camera;
  8312. }
  8313. return null;
  8314. };
  8315. /**
  8316. * sets the active camera of the scene using its name
  8317. * @param {string} name - the camera's name
  8318. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8319. * @see activeCamera
  8320. */
  8321. Scene.prototype.setActiveCameraByName = function (name) {
  8322. var camera = this.getCameraByName(name);
  8323. if (camera) {
  8324. this.activeCamera = camera;
  8325. return camera;
  8326. }
  8327. return null;
  8328. };
  8329. /**
  8330. * get a material using its id
  8331. * @param {string} the material's ID
  8332. * @return {BABYLON.Material|null} the material or null if none found.
  8333. */
  8334. Scene.prototype.getMaterialByID = function (id) {
  8335. for (var index = 0; index < this.materials.length; index++) {
  8336. if (this.materials[index].id === id) {
  8337. return this.materials[index];
  8338. }
  8339. }
  8340. return null;
  8341. };
  8342. /**
  8343. * get a material using its name
  8344. * @param {string} the material's name
  8345. * @return {BABYLON.Material|null} the material or null if none found.
  8346. */
  8347. Scene.prototype.getMaterialByName = function (name) {
  8348. for (var index = 0; index < this.materials.length; index++) {
  8349. if (this.materials[index].name === name) {
  8350. return this.materials[index];
  8351. }
  8352. }
  8353. return null;
  8354. };
  8355. Scene.prototype.getCameraByID = function (id) {
  8356. for (var index = 0; index < this.cameras.length; index++) {
  8357. if (this.cameras[index].id === id) {
  8358. return this.cameras[index];
  8359. }
  8360. }
  8361. return null;
  8362. };
  8363. /**
  8364. * get a camera using its name
  8365. * @param {string} the camera's name
  8366. * @return {BABYLON.Camera|null} the camera or null if none found.
  8367. */
  8368. Scene.prototype.getCameraByName = function (name) {
  8369. for (var index = 0; index < this.cameras.length; index++) {
  8370. if (this.cameras[index].name === name) {
  8371. return this.cameras[index];
  8372. }
  8373. }
  8374. return null;
  8375. };
  8376. /**
  8377. * get a light node using its name
  8378. * @param {string} the light's name
  8379. * @return {BABYLON.Light|null} the light or null if none found.
  8380. */
  8381. Scene.prototype.getLightByName = function (name) {
  8382. for (var index = 0; index < this.lights.length; index++) {
  8383. if (this.lights[index].name === name) {
  8384. return this.lights[index];
  8385. }
  8386. }
  8387. return null;
  8388. };
  8389. /**
  8390. * get a light node using its ID
  8391. * @param {string} the light's id
  8392. * @return {BABYLON.Light|null} the light or null if none found.
  8393. */
  8394. Scene.prototype.getLightByID = function (id) {
  8395. for (var index = 0; index < this.lights.length; index++) {
  8396. if (this.lights[index].id === id) {
  8397. return this.lights[index];
  8398. }
  8399. }
  8400. return null;
  8401. };
  8402. /**
  8403. * get a geometry using its ID
  8404. * @param {string} the geometry's id
  8405. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8406. */
  8407. Scene.prototype.getGeometryByID = function (id) {
  8408. for (var index = 0; index < this._geometries.length; index++) {
  8409. if (this._geometries[index].id === id) {
  8410. return this._geometries[index];
  8411. }
  8412. }
  8413. return null;
  8414. };
  8415. /**
  8416. * add a new geometry to this scene.
  8417. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8418. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8419. * @return {boolean} was the geometry added or not
  8420. */
  8421. Scene.prototype.pushGeometry = function (geometry, force) {
  8422. if (!force && this.getGeometryByID(geometry.id)) {
  8423. return false;
  8424. }
  8425. this._geometries.push(geometry);
  8426. return true;
  8427. };
  8428. Scene.prototype.getGeometries = function () {
  8429. return this._geometries;
  8430. };
  8431. /**
  8432. * Get a the first added mesh found of a given ID
  8433. * @param {string} id - the id to search for
  8434. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8435. */
  8436. Scene.prototype.getMeshByID = function (id) {
  8437. for (var index = 0; index < this.meshes.length; index++) {
  8438. if (this.meshes[index].id === id) {
  8439. return this.meshes[index];
  8440. }
  8441. }
  8442. return null;
  8443. };
  8444. /**
  8445. * Get a the last added mesh found of a given ID
  8446. * @param {string} id - the id to search for
  8447. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8448. */
  8449. Scene.prototype.getLastMeshByID = function (id) {
  8450. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8451. if (this.meshes[index].id === id) {
  8452. return this.meshes[index];
  8453. }
  8454. }
  8455. return null;
  8456. };
  8457. /**
  8458. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8459. * @param {string} id - the id to search for
  8460. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8461. */
  8462. Scene.prototype.getLastEntryByID = function (id) {
  8463. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8464. if (this.meshes[index].id === id) {
  8465. return this.meshes[index];
  8466. }
  8467. }
  8468. for (index = this.cameras.length - 1; index >= 0; index--) {
  8469. if (this.cameras[index].id === id) {
  8470. return this.cameras[index];
  8471. }
  8472. }
  8473. for (index = this.lights.length - 1; index >= 0; index--) {
  8474. if (this.lights[index].id === id) {
  8475. return this.lights[index];
  8476. }
  8477. }
  8478. return null;
  8479. };
  8480. Scene.prototype.getNodeByName = function (name) {
  8481. var mesh = this.getMeshByName(name);
  8482. if (mesh) {
  8483. return mesh;
  8484. }
  8485. var light = this.getLightByName(name);
  8486. if (light) {
  8487. return light;
  8488. }
  8489. return this.getCameraByName(name);
  8490. };
  8491. Scene.prototype.getMeshByName = function (name) {
  8492. for (var index = 0; index < this.meshes.length; index++) {
  8493. if (this.meshes[index].name === name) {
  8494. return this.meshes[index];
  8495. }
  8496. }
  8497. return null;
  8498. };
  8499. Scene.prototype.getSoundByName = function (name) {
  8500. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8501. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8502. return this.mainSoundTrack.soundCollection[index];
  8503. }
  8504. }
  8505. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8506. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8507. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8508. return this.soundTracks[sdIndex].soundCollection[index];
  8509. }
  8510. }
  8511. }
  8512. return null;
  8513. };
  8514. Scene.prototype.getLastSkeletonByID = function (id) {
  8515. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8516. if (this.skeletons[index].id === id) {
  8517. return this.skeletons[index];
  8518. }
  8519. }
  8520. return null;
  8521. };
  8522. Scene.prototype.getSkeletonById = function (id) {
  8523. for (var index = 0; index < this.skeletons.length; index++) {
  8524. if (this.skeletons[index].id === id) {
  8525. return this.skeletons[index];
  8526. }
  8527. }
  8528. return null;
  8529. };
  8530. Scene.prototype.getSkeletonByName = function (name) {
  8531. for (var index = 0; index < this.skeletons.length; index++) {
  8532. if (this.skeletons[index].name === name) {
  8533. return this.skeletons[index];
  8534. }
  8535. }
  8536. return null;
  8537. };
  8538. Scene.prototype.isActiveMesh = function (mesh) {
  8539. return (this._activeMeshes.indexOf(mesh) !== -1);
  8540. };
  8541. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8542. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8543. var material = subMesh.getMaterial();
  8544. if (mesh.showSubMeshesBoundingBox) {
  8545. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8546. }
  8547. if (material) {
  8548. // Render targets
  8549. if (material.getRenderTargetTextures) {
  8550. if (this._processedMaterials.indexOf(material) === -1) {
  8551. this._processedMaterials.push(material);
  8552. this._renderTargets.concat(material.getRenderTargetTextures());
  8553. }
  8554. }
  8555. // Dispatch
  8556. this._activeVertices += subMesh.indexCount;
  8557. this._renderingManager.dispatch(subMesh);
  8558. }
  8559. }
  8560. };
  8561. Scene.prototype._evaluateActiveMeshes = function () {
  8562. this.activeCamera._activeMeshes.reset();
  8563. this._activeMeshes.reset();
  8564. this._renderingManager.reset();
  8565. this._processedMaterials.reset();
  8566. this._activeParticleSystems.reset();
  8567. this._activeSkeletons.reset();
  8568. this._boundingBoxRenderer.reset();
  8569. if (!this._frustumPlanes) {
  8570. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8571. }
  8572. else {
  8573. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8574. }
  8575. // Meshes
  8576. var meshes;
  8577. var len;
  8578. if (this._selectionOctree) {
  8579. var selection = this._selectionOctree.select(this._frustumPlanes);
  8580. meshes = selection.data;
  8581. len = selection.length;
  8582. }
  8583. else {
  8584. len = this.meshes.length;
  8585. meshes = this.meshes;
  8586. }
  8587. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8588. var mesh = meshes[meshIndex];
  8589. if (mesh.isBlocked) {
  8590. continue;
  8591. }
  8592. this._totalVertices += mesh.getTotalVertices();
  8593. if (!mesh.isReady()) {
  8594. continue;
  8595. }
  8596. mesh.computeWorldMatrix();
  8597. // Intersections
  8598. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8599. this._meshesForIntersections.pushNoDuplicate(mesh);
  8600. }
  8601. // Switch to current LOD
  8602. var meshLOD = mesh.getLOD(this.activeCamera);
  8603. if (!meshLOD) {
  8604. continue;
  8605. }
  8606. mesh._preActivate();
  8607. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8608. this._activeMeshes.push(mesh);
  8609. this.activeCamera._activeMeshes.push(mesh);
  8610. mesh._activate(this._renderId);
  8611. this._activeMesh(meshLOD);
  8612. }
  8613. }
  8614. // Particle systems
  8615. var beforeParticlesDate = BABYLON.Tools.Now;
  8616. if (this.particlesEnabled) {
  8617. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8618. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8619. var particleSystem = this.particleSystems[particleIndex];
  8620. if (!particleSystem.isStarted()) {
  8621. continue;
  8622. }
  8623. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8624. this._activeParticleSystems.push(particleSystem);
  8625. particleSystem.animate();
  8626. }
  8627. }
  8628. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8629. }
  8630. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8631. };
  8632. Scene.prototype._activeMesh = function (mesh) {
  8633. if (mesh.skeleton && this.skeletonsEnabled) {
  8634. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8635. }
  8636. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8637. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8638. }
  8639. if (mesh && mesh.subMeshes) {
  8640. // Submeshes Octrees
  8641. var len;
  8642. var subMeshes;
  8643. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8644. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8645. len = intersections.length;
  8646. subMeshes = intersections.data;
  8647. }
  8648. else {
  8649. subMeshes = mesh.subMeshes;
  8650. len = subMeshes.length;
  8651. }
  8652. for (var subIndex = 0; subIndex < len; subIndex++) {
  8653. var subMesh = subMeshes[subIndex];
  8654. this._evaluateSubMesh(subMesh, mesh);
  8655. }
  8656. }
  8657. };
  8658. Scene.prototype.updateTransformMatrix = function (force) {
  8659. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8660. };
  8661. Scene.prototype._renderForCamera = function (camera) {
  8662. var engine = this._engine;
  8663. this.activeCamera = camera;
  8664. if (!this.activeCamera)
  8665. throw new Error("Active camera not set");
  8666. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8667. // Viewport
  8668. engine.setViewport(this.activeCamera.viewport);
  8669. // Camera
  8670. this._renderId++;
  8671. this.updateTransformMatrix();
  8672. if (this.beforeCameraRender) {
  8673. this.beforeCameraRender(this.activeCamera);
  8674. }
  8675. // Meshes
  8676. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8677. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8678. this._evaluateActiveMeshes();
  8679. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8680. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8681. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8682. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8683. skeleton.prepare();
  8684. }
  8685. // Render targets
  8686. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8687. if (this.renderTargetsEnabled) {
  8688. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8689. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8690. var renderTarget = this._renderTargets.data[renderIndex];
  8691. if (renderTarget._shouldRender()) {
  8692. this._renderId++;
  8693. renderTarget.render(false, this.dumpNextRenderTargets);
  8694. }
  8695. }
  8696. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8697. this._renderId++;
  8698. }
  8699. if (this._renderTargets.length > 0) {
  8700. engine.restoreDefaultFramebuffer();
  8701. }
  8702. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8703. // Prepare Frame
  8704. this.postProcessManager._prepareFrame();
  8705. var beforeRenderDate = BABYLON.Tools.Now;
  8706. // Backgrounds
  8707. if (this.layers.length) {
  8708. engine.setDepthBuffer(false);
  8709. var layerIndex;
  8710. var layer;
  8711. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8712. layer = this.layers[layerIndex];
  8713. if (layer.isBackground) {
  8714. layer.render();
  8715. }
  8716. }
  8717. engine.setDepthBuffer(true);
  8718. }
  8719. // Render
  8720. BABYLON.Tools.StartPerformanceCounter("Main render");
  8721. this._renderingManager.render(null, null, true, true);
  8722. BABYLON.Tools.EndPerformanceCounter("Main render");
  8723. // Bounding boxes
  8724. this._boundingBoxRenderer.render();
  8725. // Lens flares
  8726. if (this.lensFlaresEnabled) {
  8727. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8728. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8729. this.lensFlareSystems[lensFlareSystemIndex].render();
  8730. }
  8731. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8732. }
  8733. // Foregrounds
  8734. if (this.layers.length) {
  8735. engine.setDepthBuffer(false);
  8736. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8737. layer = this.layers[layerIndex];
  8738. if (!layer.isBackground) {
  8739. layer.render();
  8740. }
  8741. }
  8742. engine.setDepthBuffer(true);
  8743. }
  8744. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8745. // Finalize frame
  8746. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8747. // Update camera
  8748. this.activeCamera._updateFromScene();
  8749. // Reset some special arrays
  8750. this._renderTargets.reset();
  8751. if (this.afterCameraRender) {
  8752. this.afterCameraRender(this.activeCamera);
  8753. }
  8754. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8755. };
  8756. Scene.prototype._processSubCameras = function (camera) {
  8757. if (camera.subCameras.length === 0) {
  8758. this._renderForCamera(camera);
  8759. return;
  8760. }
  8761. for (var index = 0; index < camera.subCameras.length; index++) {
  8762. this._renderForCamera(camera.subCameras[index]);
  8763. }
  8764. this.activeCamera = camera;
  8765. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8766. // Update camera
  8767. this.activeCamera._updateFromScene();
  8768. };
  8769. Scene.prototype._checkIntersections = function () {
  8770. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8771. var sourceMesh = this._meshesForIntersections.data[index];
  8772. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8773. var action = sourceMesh.actionManager.actions[actionIndex];
  8774. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8775. var parameters = action.getTriggerParameter();
  8776. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8777. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8778. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8779. if (areIntersecting && currentIntersectionInProgress === -1) {
  8780. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8781. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8782. sourceMesh._intersectionsInProgress.push(otherMesh);
  8783. }
  8784. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8785. sourceMesh._intersectionsInProgress.push(otherMesh);
  8786. }
  8787. }
  8788. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8789. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8790. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8791. if (indexOfOther > -1) {
  8792. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8793. }
  8794. }
  8795. }
  8796. }
  8797. }
  8798. };
  8799. Scene.prototype.render = function () {
  8800. var startDate = BABYLON.Tools.Now;
  8801. this._particlesDuration = 0;
  8802. this._spritesDuration = 0;
  8803. this._activeParticles = 0;
  8804. this._renderDuration = 0;
  8805. this._renderTargetsDuration = 0;
  8806. this._evaluateActiveMeshesDuration = 0;
  8807. this._totalVertices = 0;
  8808. this._activeVertices = 0;
  8809. this._activeBones = 0;
  8810. this.getEngine().resetDrawCalls();
  8811. this._meshesForIntersections.reset();
  8812. this.resetCachedMaterial();
  8813. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8814. // Actions
  8815. if (this.actionManager) {
  8816. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8817. }
  8818. //Simplification Queue
  8819. if (!this.simplificationQueue.running) {
  8820. this.simplificationQueue.executeNext();
  8821. }
  8822. // Before render
  8823. if (this.beforeRender) {
  8824. this.beforeRender();
  8825. }
  8826. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8827. this._onBeforeRenderCallbacks[callbackIndex]();
  8828. }
  8829. // Animations
  8830. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8831. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8832. this._animate();
  8833. // Physics
  8834. if (this._physicsEngine) {
  8835. BABYLON.Tools.StartPerformanceCounter("Physics");
  8836. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8837. BABYLON.Tools.EndPerformanceCounter("Physics");
  8838. }
  8839. // Customs render targets
  8840. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8841. var engine = this.getEngine();
  8842. var currentActiveCamera = this.activeCamera;
  8843. if (this.renderTargetsEnabled) {
  8844. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8845. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8846. var renderTarget = this.customRenderTargets[customIndex];
  8847. if (renderTarget._shouldRender()) {
  8848. this._renderId++;
  8849. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8850. if (!this.activeCamera)
  8851. throw new Error("Active camera not set");
  8852. // Viewport
  8853. engine.setViewport(this.activeCamera.viewport);
  8854. // Camera
  8855. this.updateTransformMatrix();
  8856. renderTarget.render(false, this.dumpNextRenderTargets);
  8857. }
  8858. }
  8859. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8860. this._renderId++;
  8861. }
  8862. if (this.customRenderTargets.length > 0) {
  8863. engine.restoreDefaultFramebuffer();
  8864. }
  8865. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8866. this.activeCamera = currentActiveCamera;
  8867. // Procedural textures
  8868. if (this.proceduralTexturesEnabled) {
  8869. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8870. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8871. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8872. if (proceduralTexture._shouldRender()) {
  8873. proceduralTexture.render();
  8874. }
  8875. }
  8876. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8877. }
  8878. // Clear
  8879. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8880. // Shadows
  8881. if (this.shadowsEnabled) {
  8882. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8883. var light = this.lights[lightIndex];
  8884. var shadowGenerator = light.getShadowGenerator();
  8885. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8886. this._renderTargets.push(shadowGenerator.getShadowMap());
  8887. }
  8888. }
  8889. }
  8890. // Depth renderer
  8891. if (this._depthRenderer) {
  8892. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8893. }
  8894. // RenderPipeline
  8895. this.postProcessRenderPipelineManager.update();
  8896. // Multi-cameras?
  8897. if (this.activeCameras.length > 0) {
  8898. var currentRenderId = this._renderId;
  8899. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8900. this._renderId = currentRenderId;
  8901. this._processSubCameras(this.activeCameras[cameraIndex]);
  8902. }
  8903. }
  8904. else {
  8905. if (!this.activeCamera) {
  8906. throw new Error("No camera defined");
  8907. }
  8908. this._processSubCameras(this.activeCamera);
  8909. }
  8910. // Intersection checks
  8911. this._checkIntersections();
  8912. // Update the audio listener attached to the camera
  8913. this._updateAudioParameters();
  8914. // After render
  8915. if (this.afterRender) {
  8916. this.afterRender();
  8917. }
  8918. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8919. this._onAfterRenderCallbacks[callbackIndex]();
  8920. }
  8921. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8922. this._toBeDisposed.data[index].dispose();
  8923. this._toBeDisposed[index] = null;
  8924. }
  8925. this._toBeDisposed.reset();
  8926. if (this.dumpNextRenderTargets) {
  8927. this.dumpNextRenderTargets = false;
  8928. }
  8929. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8930. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8931. };
  8932. Scene.prototype._updateAudioParameters = function () {
  8933. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  8934. return;
  8935. }
  8936. var listeningCamera;
  8937. var audioEngine = BABYLON.Engine.audioEngine;
  8938. if (this.activeCameras.length > 0) {
  8939. listeningCamera = this.activeCameras[0];
  8940. }
  8941. else {
  8942. listeningCamera = this.activeCamera;
  8943. }
  8944. if (listeningCamera && audioEngine.canUseWebAudio) {
  8945. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8946. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8947. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8948. cameraDirection.normalize();
  8949. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8950. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8951. var sound = this.mainSoundTrack.soundCollection[i];
  8952. if (sound.useCustomAttenuation) {
  8953. sound.updateDistanceFromListener();
  8954. }
  8955. }
  8956. for (i = 0; i < this.soundTracks.length; i++) {
  8957. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8958. sound = this.soundTracks[i].soundCollection[j];
  8959. if (sound.useCustomAttenuation) {
  8960. sound.updateDistanceFromListener();
  8961. }
  8962. }
  8963. }
  8964. }
  8965. };
  8966. Object.defineProperty(Scene.prototype, "audioEnabled", {
  8967. get: function () {
  8968. return this._audioEnabled;
  8969. },
  8970. set: function (value) {
  8971. this._audioEnabled = value;
  8972. if (this._audioEnabled) {
  8973. this._enableAudio();
  8974. }
  8975. else {
  8976. this._disableAudio();
  8977. }
  8978. },
  8979. enumerable: true,
  8980. configurable: true
  8981. });
  8982. Scene.prototype._disableAudio = function () {
  8983. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8984. this.mainSoundTrack.soundCollection[i].pause();
  8985. }
  8986. for (i = 0; i < this.soundTracks.length; i++) {
  8987. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8988. this.soundTracks[i].soundCollection[j].pause();
  8989. }
  8990. }
  8991. };
  8992. Scene.prototype._enableAudio = function () {
  8993. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8994. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  8995. this.mainSoundTrack.soundCollection[i].play();
  8996. }
  8997. }
  8998. for (i = 0; i < this.soundTracks.length; i++) {
  8999. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9000. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9001. this.soundTracks[i].soundCollection[j].play();
  9002. }
  9003. }
  9004. }
  9005. };
  9006. Scene.prototype.enableDepthRenderer = function () {
  9007. if (this._depthRenderer) {
  9008. return this._depthRenderer;
  9009. }
  9010. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9011. return this._depthRenderer;
  9012. };
  9013. Scene.prototype.disableDepthRenderer = function () {
  9014. if (!this._depthRenderer) {
  9015. return;
  9016. }
  9017. this._depthRenderer.dispose();
  9018. this._depthRenderer = null;
  9019. };
  9020. Scene.prototype.dispose = function () {
  9021. this.beforeRender = null;
  9022. this.afterRender = null;
  9023. this.skeletons = [];
  9024. this._boundingBoxRenderer.dispose();
  9025. if (this._depthRenderer) {
  9026. this._depthRenderer.dispose();
  9027. }
  9028. // Debug layer
  9029. this.debugLayer.hide();
  9030. // Events
  9031. if (this.onDispose) {
  9032. this.onDispose();
  9033. }
  9034. this._onBeforeRenderCallbacks = [];
  9035. this._onAfterRenderCallbacks = [];
  9036. this.detachControl();
  9037. // Release sounds & sounds tracks
  9038. this.disposeSounds();
  9039. // Detach cameras
  9040. var canvas = this._engine.getRenderingCanvas();
  9041. var index;
  9042. for (index = 0; index < this.cameras.length; index++) {
  9043. this.cameras[index].detachControl(canvas);
  9044. }
  9045. while (this.lights.length) {
  9046. this.lights[0].dispose();
  9047. }
  9048. while (this.meshes.length) {
  9049. this.meshes[0].dispose(true);
  9050. }
  9051. while (this.cameras.length) {
  9052. this.cameras[0].dispose();
  9053. }
  9054. while (this.materials.length) {
  9055. this.materials[0].dispose();
  9056. }
  9057. while (this.particleSystems.length) {
  9058. this.particleSystems[0].dispose();
  9059. }
  9060. while (this.spriteManagers.length) {
  9061. this.spriteManagers[0].dispose();
  9062. }
  9063. while (this.layers.length) {
  9064. this.layers[0].dispose();
  9065. }
  9066. while (this.textures.length) {
  9067. this.textures[0].dispose();
  9068. }
  9069. // Post-processes
  9070. this.postProcessManager.dispose();
  9071. // Physics
  9072. if (this._physicsEngine) {
  9073. this.disablePhysicsEngine();
  9074. }
  9075. // Remove from engine
  9076. index = this._engine.scenes.indexOf(this);
  9077. if (index > -1) {
  9078. this._engine.scenes.splice(index, 1);
  9079. }
  9080. this._engine.wipeCaches();
  9081. };
  9082. // Release sounds & sounds tracks
  9083. Scene.prototype.disposeSounds = function () {
  9084. this.mainSoundTrack.dispose();
  9085. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9086. this.soundTracks[scIndex].dispose();
  9087. }
  9088. };
  9089. // Collisions
  9090. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9091. if (excludedMesh === void 0) { excludedMesh = null; }
  9092. position.divideToRef(collider.radius, this._scaledPosition);
  9093. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9094. collider.retry = 0;
  9095. collider.initialVelocity = this._scaledVelocity;
  9096. collider.initialPosition = this._scaledPosition;
  9097. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9098. finalPosition.multiplyInPlace(collider.radius);
  9099. };
  9100. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9101. if (excludedMesh === void 0) { excludedMesh = null; }
  9102. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9103. if (collider.retry >= maximumRetry) {
  9104. finalPosition.copyFrom(position);
  9105. return;
  9106. }
  9107. collider._initialize(position, velocity, closeDistance);
  9108. for (var index = 0; index < this.meshes.length; index++) {
  9109. var mesh = this.meshes[index];
  9110. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9111. mesh._checkCollision(collider);
  9112. }
  9113. }
  9114. if (!collider.collisionFound) {
  9115. position.addToRef(velocity, finalPosition);
  9116. return;
  9117. }
  9118. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9119. collider._getResponse(position, velocity);
  9120. }
  9121. if (velocity.length() <= closeDistance) {
  9122. finalPosition.copyFrom(position);
  9123. return;
  9124. }
  9125. collider.retry++;
  9126. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9127. };
  9128. // Octrees
  9129. Scene.prototype.getWorldExtends = function () {
  9130. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9131. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9132. for (var index = 0; index < this.meshes.length; index++) {
  9133. var mesh = this.meshes[index];
  9134. mesh.computeWorldMatrix(true);
  9135. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9136. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9137. BABYLON.Tools.CheckExtends(minBox, min, max);
  9138. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9139. }
  9140. return {
  9141. min: min,
  9142. max: max
  9143. };
  9144. };
  9145. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9146. if (maxCapacity === void 0) { maxCapacity = 64; }
  9147. if (maxDepth === void 0) { maxDepth = 2; }
  9148. if (!this._selectionOctree) {
  9149. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9150. }
  9151. var worldExtends = this.getWorldExtends();
  9152. // Update octree
  9153. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9154. return this._selectionOctree;
  9155. };
  9156. // Picking
  9157. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9158. var engine = this._engine;
  9159. if (!camera) {
  9160. if (!this.activeCamera)
  9161. throw new Error("Active camera not set");
  9162. camera = this.activeCamera;
  9163. }
  9164. var cameraViewport = camera.viewport;
  9165. var viewport = cameraViewport.toGlobal(engine);
  9166. // Moving coordinates to local viewport world
  9167. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9168. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9169. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9170. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9171. };
  9172. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9173. var pickingInfo = null;
  9174. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9175. var mesh = this.meshes[meshIndex];
  9176. if (predicate) {
  9177. if (!predicate(mesh)) {
  9178. continue;
  9179. }
  9180. }
  9181. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9182. continue;
  9183. }
  9184. var world = mesh.getWorldMatrix();
  9185. var ray = rayFunction(world);
  9186. var result = mesh.intersects(ray, fastCheck);
  9187. if (!result || !result.hit)
  9188. continue;
  9189. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9190. continue;
  9191. pickingInfo = result;
  9192. if (fastCheck) {
  9193. break;
  9194. }
  9195. }
  9196. return pickingInfo || new BABYLON.PickingInfo();
  9197. };
  9198. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9199. var _this = this;
  9200. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9201. /// <param name="x">X position on screen</param>
  9202. /// <param name="y">Y position on screen</param>
  9203. /// <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>
  9204. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9205. /// <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>
  9206. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9207. };
  9208. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9209. var _this = this;
  9210. return this._internalPick(function (world) {
  9211. if (!_this._pickWithRayInverseMatrix) {
  9212. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9213. }
  9214. world.invertToRef(_this._pickWithRayInverseMatrix);
  9215. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9216. }, predicate, fastCheck);
  9217. };
  9218. Scene.prototype.setPointerOverMesh = function (mesh) {
  9219. if (this._pointerOverMesh === mesh) {
  9220. return;
  9221. }
  9222. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9223. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9224. }
  9225. this._pointerOverMesh = mesh;
  9226. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9227. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9228. }
  9229. };
  9230. Scene.prototype.getPointerOverMesh = function () {
  9231. return this._pointerOverMesh;
  9232. };
  9233. // Physics
  9234. Scene.prototype.getPhysicsEngine = function () {
  9235. return this._physicsEngine;
  9236. };
  9237. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9238. if (this._physicsEngine) {
  9239. return true;
  9240. }
  9241. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9242. if (!this._physicsEngine.isSupported()) {
  9243. this._physicsEngine = null;
  9244. return false;
  9245. }
  9246. this._physicsEngine._initialize(gravity);
  9247. return true;
  9248. };
  9249. Scene.prototype.disablePhysicsEngine = function () {
  9250. if (!this._physicsEngine) {
  9251. return;
  9252. }
  9253. this._physicsEngine.dispose();
  9254. this._physicsEngine = undefined;
  9255. };
  9256. Scene.prototype.isPhysicsEnabled = function () {
  9257. return this._physicsEngine !== undefined;
  9258. };
  9259. Scene.prototype.setGravity = function (gravity) {
  9260. if (!this._physicsEngine) {
  9261. return;
  9262. }
  9263. this._physicsEngine._setGravity(gravity);
  9264. };
  9265. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9266. if (parts.parts) {
  9267. options = parts;
  9268. parts = parts.parts;
  9269. }
  9270. if (!this._physicsEngine) {
  9271. return null;
  9272. }
  9273. for (var index = 0; index < parts.length; index++) {
  9274. var mesh = parts[index].mesh;
  9275. mesh._physicImpostor = parts[index].impostor;
  9276. mesh._physicsMass = options.mass / parts.length;
  9277. mesh._physicsFriction = options.friction;
  9278. mesh._physicRestitution = options.restitution;
  9279. }
  9280. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9281. };
  9282. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9283. for (var index = 0; index < compound.parts.length; index++) {
  9284. var mesh = compound.parts[index].mesh;
  9285. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9286. this._physicsEngine._unregisterMesh(mesh);
  9287. }
  9288. };
  9289. // Misc.
  9290. Scene.prototype.createDefaultCameraOrLight = function () {
  9291. // Light
  9292. if (this.lights.length === 0) {
  9293. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9294. }
  9295. // Camera
  9296. if (!this.activeCamera) {
  9297. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9298. // Compute position
  9299. var worldExtends = this.getWorldExtends();
  9300. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9301. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9302. camera.setTarget(worldCenter);
  9303. this.activeCamera = camera;
  9304. }
  9305. };
  9306. // Tags
  9307. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9308. if (tagsQuery === undefined) {
  9309. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9310. return list;
  9311. }
  9312. var listByTags = [];
  9313. forEach = forEach || (function (item) {
  9314. return;
  9315. });
  9316. for (var i in list) {
  9317. var item = list[i];
  9318. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9319. listByTags.push(item);
  9320. forEach(item);
  9321. }
  9322. }
  9323. return listByTags;
  9324. };
  9325. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9326. return this._getByTags(this.meshes, tagsQuery, forEach);
  9327. };
  9328. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9329. return this._getByTags(this.cameras, tagsQuery, forEach);
  9330. };
  9331. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9332. return this._getByTags(this.lights, tagsQuery, forEach);
  9333. };
  9334. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9335. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9336. };
  9337. // Audio
  9338. Scene.prototype.switchAudioModeForHeadphones = function () {
  9339. this.mainSoundTrack.switchPanningModelToHRTF();
  9340. for (var i = 0; i < this.soundTracks.length; i++) {
  9341. this.soundTracks[i].switchPanningModelToHRTF();
  9342. }
  9343. };
  9344. Scene.prototype.switchAudioModeForNormalSpeakers = function () {
  9345. this.mainSoundTrack.switchPanningModelToEqualPower();
  9346. for (var i = 0; i < this.soundTracks.length; i++) {
  9347. this.soundTracks[i].switchPanningModelToEqualPower();
  9348. }
  9349. };
  9350. // Statics
  9351. Scene._FOGMODE_NONE = 0;
  9352. Scene._FOGMODE_EXP = 1;
  9353. Scene._FOGMODE_EXP2 = 2;
  9354. Scene._FOGMODE_LINEAR = 3;
  9355. Scene.MinDeltaTime = 1.0;
  9356. Scene.MaxDeltaTime = 1000.0;
  9357. return Scene;
  9358. })();
  9359. BABYLON.Scene = Scene;
  9360. })(BABYLON || (BABYLON = {}));
  9361. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9362. (function (BABYLON) {
  9363. var VertexBuffer = (function () {
  9364. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9365. if (engine instanceof BABYLON.Mesh) {
  9366. this._engine = engine.getScene().getEngine();
  9367. }
  9368. else {
  9369. this._engine = engine;
  9370. }
  9371. this._updatable = updatable;
  9372. this._data = data;
  9373. if (!postponeInternalCreation) {
  9374. this.create();
  9375. }
  9376. this._kind = kind;
  9377. if (stride) {
  9378. this._strideSize = stride;
  9379. return;
  9380. }
  9381. switch (kind) {
  9382. case VertexBuffer.PositionKind:
  9383. this._strideSize = 3;
  9384. break;
  9385. case VertexBuffer.NormalKind:
  9386. this._strideSize = 3;
  9387. break;
  9388. case VertexBuffer.UVKind:
  9389. this._strideSize = 2;
  9390. break;
  9391. case VertexBuffer.UV2Kind:
  9392. this._strideSize = 2;
  9393. break;
  9394. case VertexBuffer.ColorKind:
  9395. this._strideSize = 4;
  9396. break;
  9397. case VertexBuffer.MatricesIndicesKind:
  9398. this._strideSize = 4;
  9399. break;
  9400. case VertexBuffer.MatricesWeightsKind:
  9401. this._strideSize = 4;
  9402. break;
  9403. }
  9404. }
  9405. // Properties
  9406. VertexBuffer.prototype.isUpdatable = function () {
  9407. return this._updatable;
  9408. };
  9409. VertexBuffer.prototype.getData = function () {
  9410. return this._data;
  9411. };
  9412. VertexBuffer.prototype.getBuffer = function () {
  9413. return this._buffer;
  9414. };
  9415. VertexBuffer.prototype.getStrideSize = function () {
  9416. return this._strideSize;
  9417. };
  9418. // Methods
  9419. VertexBuffer.prototype.create = function (data) {
  9420. if (!data && this._buffer) {
  9421. return; // nothing to do
  9422. }
  9423. data = data || this._data;
  9424. if (!this._buffer) {
  9425. if (this._updatable) {
  9426. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9427. }
  9428. else {
  9429. this._buffer = this._engine.createVertexBuffer(data);
  9430. }
  9431. }
  9432. if (this._updatable) {
  9433. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9434. this._data = data;
  9435. }
  9436. };
  9437. VertexBuffer.prototype.update = function (data) {
  9438. this.create(data);
  9439. };
  9440. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9441. if (!this._buffer) {
  9442. return;
  9443. }
  9444. if (this._updatable) {
  9445. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9446. this._data = null;
  9447. }
  9448. };
  9449. VertexBuffer.prototype.dispose = function () {
  9450. if (!this._buffer) {
  9451. return;
  9452. }
  9453. if (this._engine._releaseBuffer(this._buffer)) {
  9454. this._buffer = null;
  9455. }
  9456. };
  9457. Object.defineProperty(VertexBuffer, "PositionKind", {
  9458. get: function () {
  9459. return VertexBuffer._PositionKind;
  9460. },
  9461. enumerable: true,
  9462. configurable: true
  9463. });
  9464. Object.defineProperty(VertexBuffer, "NormalKind", {
  9465. get: function () {
  9466. return VertexBuffer._NormalKind;
  9467. },
  9468. enumerable: true,
  9469. configurable: true
  9470. });
  9471. Object.defineProperty(VertexBuffer, "UVKind", {
  9472. get: function () {
  9473. return VertexBuffer._UVKind;
  9474. },
  9475. enumerable: true,
  9476. configurable: true
  9477. });
  9478. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9479. get: function () {
  9480. return VertexBuffer._UV2Kind;
  9481. },
  9482. enumerable: true,
  9483. configurable: true
  9484. });
  9485. Object.defineProperty(VertexBuffer, "ColorKind", {
  9486. get: function () {
  9487. return VertexBuffer._ColorKind;
  9488. },
  9489. enumerable: true,
  9490. configurable: true
  9491. });
  9492. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9493. get: function () {
  9494. return VertexBuffer._MatricesIndicesKind;
  9495. },
  9496. enumerable: true,
  9497. configurable: true
  9498. });
  9499. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9500. get: function () {
  9501. return VertexBuffer._MatricesWeightsKind;
  9502. },
  9503. enumerable: true,
  9504. configurable: true
  9505. });
  9506. // Enums
  9507. VertexBuffer._PositionKind = "position";
  9508. VertexBuffer._NormalKind = "normal";
  9509. VertexBuffer._UVKind = "uv";
  9510. VertexBuffer._UV2Kind = "uv2";
  9511. VertexBuffer._ColorKind = "color";
  9512. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9513. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9514. return VertexBuffer;
  9515. })();
  9516. BABYLON.VertexBuffer = VertexBuffer;
  9517. })(BABYLON || (BABYLON = {}));
  9518. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9519. var BABYLON;
  9520. (function (BABYLON) {
  9521. var AbstractMesh = (function (_super) {
  9522. __extends(AbstractMesh, _super);
  9523. function AbstractMesh(name, scene) {
  9524. _super.call(this, name, scene);
  9525. // Properties
  9526. this.definedFacingForward = true; // orientation for POV movement & rotation
  9527. this.position = new BABYLON.Vector3(0, 0, 0);
  9528. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9529. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9530. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9531. this.visibility = 1.0;
  9532. this.alphaIndex = Number.MAX_VALUE;
  9533. this.infiniteDistance = false;
  9534. this.isVisible = true;
  9535. this.isPickable = true;
  9536. this.showBoundingBox = false;
  9537. this.showSubMeshesBoundingBox = false;
  9538. this.onDispose = null;
  9539. this.checkCollisions = false;
  9540. this.isBlocker = false;
  9541. this.renderingGroupId = 0;
  9542. this.receiveShadows = false;
  9543. this.renderOutline = false;
  9544. this.outlineColor = BABYLON.Color3.Red();
  9545. this.outlineWidth = 0.02;
  9546. this.renderOverlay = false;
  9547. this.overlayColor = BABYLON.Color3.Red();
  9548. this.overlayAlpha = 0.5;
  9549. this.hasVertexAlpha = false;
  9550. this.useVertexColors = true;
  9551. this.applyFog = true;
  9552. this.useOctreeForRenderingSelection = true;
  9553. this.useOctreeForPicking = true;
  9554. this.useOctreeForCollisions = true;
  9555. this.layerMask = 0xFFFFFFFF;
  9556. // Physics
  9557. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9558. // Collisions
  9559. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9560. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9561. this._collider = new BABYLON.Collider();
  9562. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9563. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9564. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9565. // Cache
  9566. this._localScaling = BABYLON.Matrix.Zero();
  9567. this._localRotation = BABYLON.Matrix.Zero();
  9568. this._localTranslation = BABYLON.Matrix.Zero();
  9569. this._localBillboard = BABYLON.Matrix.Zero();
  9570. this._localPivotScaling = BABYLON.Matrix.Zero();
  9571. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9572. this._localWorld = BABYLON.Matrix.Zero();
  9573. this._worldMatrix = BABYLON.Matrix.Zero();
  9574. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9575. this._absolutePosition = BABYLON.Vector3.Zero();
  9576. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9577. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9578. this._isDirty = false;
  9579. this._pivotMatrix = BABYLON.Matrix.Identity();
  9580. this._isDisposed = false;
  9581. this._renderId = 0;
  9582. this._intersectionsInProgress = new Array();
  9583. this._onAfterWorldMatrixUpdate = new Array();
  9584. scene.meshes.push(this);
  9585. }
  9586. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9587. get: function () {
  9588. return AbstractMesh._BILLBOARDMODE_NONE;
  9589. },
  9590. enumerable: true,
  9591. configurable: true
  9592. });
  9593. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9594. get: function () {
  9595. return AbstractMesh._BILLBOARDMODE_X;
  9596. },
  9597. enumerable: true,
  9598. configurable: true
  9599. });
  9600. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9601. get: function () {
  9602. return AbstractMesh._BILLBOARDMODE_Y;
  9603. },
  9604. enumerable: true,
  9605. configurable: true
  9606. });
  9607. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9608. get: function () {
  9609. return AbstractMesh._BILLBOARDMODE_Z;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9615. get: function () {
  9616. return AbstractMesh._BILLBOARDMODE_ALL;
  9617. },
  9618. enumerable: true,
  9619. configurable: true
  9620. });
  9621. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9622. // Methods
  9623. get: function () {
  9624. return false;
  9625. },
  9626. enumerable: true,
  9627. configurable: true
  9628. });
  9629. AbstractMesh.prototype.getLOD = function (camera) {
  9630. return this;
  9631. };
  9632. AbstractMesh.prototype.getTotalVertices = function () {
  9633. return 0;
  9634. };
  9635. AbstractMesh.prototype.getIndices = function () {
  9636. return null;
  9637. };
  9638. AbstractMesh.prototype.getVerticesData = function (kind) {
  9639. return null;
  9640. };
  9641. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9642. return false;
  9643. };
  9644. AbstractMesh.prototype.getBoundingInfo = function () {
  9645. if (this._masterMesh) {
  9646. return this._masterMesh.getBoundingInfo();
  9647. }
  9648. if (!this._boundingInfo) {
  9649. this._updateBoundingInfo();
  9650. }
  9651. return this._boundingInfo;
  9652. };
  9653. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9654. get: function () {
  9655. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9656. },
  9657. enumerable: true,
  9658. configurable: true
  9659. });
  9660. AbstractMesh.prototype._preActivate = function () {
  9661. };
  9662. AbstractMesh.prototype._activate = function (renderId) {
  9663. this._renderId = renderId;
  9664. };
  9665. AbstractMesh.prototype.getWorldMatrix = function () {
  9666. if (this._masterMesh) {
  9667. return this._masterMesh.getWorldMatrix();
  9668. }
  9669. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9670. this.computeWorldMatrix();
  9671. }
  9672. return this._worldMatrix;
  9673. };
  9674. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9675. get: function () {
  9676. return this._worldMatrix;
  9677. },
  9678. enumerable: true,
  9679. configurable: true
  9680. });
  9681. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9682. get: function () {
  9683. return this._absolutePosition;
  9684. },
  9685. enumerable: true,
  9686. configurable: true
  9687. });
  9688. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9689. if (!this.rotationQuaternion) {
  9690. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9691. this.rotation = BABYLON.Vector3.Zero();
  9692. }
  9693. if (!space || space == 0 /* LOCAL */) {
  9694. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9695. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9696. }
  9697. else {
  9698. if (this.parent) {
  9699. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9700. invertParentWorldMatrix.invert();
  9701. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9702. }
  9703. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9704. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9705. }
  9706. };
  9707. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9708. var displacementVector = axis.scale(distance);
  9709. if (!space || space == 0 /* LOCAL */) {
  9710. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9711. this.setPositionWithLocalVector(tempV3);
  9712. }
  9713. else {
  9714. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9715. }
  9716. };
  9717. AbstractMesh.prototype.getAbsolutePosition = function () {
  9718. this.computeWorldMatrix();
  9719. return this._absolutePosition;
  9720. };
  9721. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9722. if (!absolutePosition) {
  9723. return;
  9724. }
  9725. var absolutePositionX;
  9726. var absolutePositionY;
  9727. var absolutePositionZ;
  9728. if (absolutePosition.x === undefined) {
  9729. if (arguments.length < 3) {
  9730. return;
  9731. }
  9732. absolutePositionX = arguments[0];
  9733. absolutePositionY = arguments[1];
  9734. absolutePositionZ = arguments[2];
  9735. }
  9736. else {
  9737. absolutePositionX = absolutePosition.x;
  9738. absolutePositionY = absolutePosition.y;
  9739. absolutePositionZ = absolutePosition.z;
  9740. }
  9741. if (this.parent) {
  9742. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9743. invertParentWorldMatrix.invert();
  9744. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9745. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9746. }
  9747. else {
  9748. this.position.x = absolutePositionX;
  9749. this.position.y = absolutePositionY;
  9750. this.position.z = absolutePositionZ;
  9751. }
  9752. };
  9753. // ================================== Point of View Movement =================================
  9754. /**
  9755. * Perform relative position change from the point of view of behind the front of the mesh.
  9756. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9757. * Supports definition of mesh facing forward or backward.
  9758. * @param {number} amountRight
  9759. * @param {number} amountUp
  9760. * @param {number} amountForward
  9761. */
  9762. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9763. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9764. };
  9765. /**
  9766. * Calculate relative position change from the point of view of behind the front of the mesh.
  9767. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9768. * Supports definition of mesh facing forward or backward.
  9769. * @param {number} amountRight
  9770. * @param {number} amountUp
  9771. * @param {number} amountForward
  9772. */
  9773. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9774. var rotMatrix = new BABYLON.Matrix();
  9775. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9776. rotQuaternion.toRotationMatrix(rotMatrix);
  9777. var translationDelta = BABYLON.Vector3.Zero();
  9778. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9779. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9780. return translationDelta;
  9781. };
  9782. // ================================== Point of View Rotation =================================
  9783. /**
  9784. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9785. * Supports definition of mesh facing forward or backward.
  9786. * @param {number} flipBack
  9787. * @param {number} twirlClockwise
  9788. * @param {number} tiltRight
  9789. */
  9790. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9791. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9792. };
  9793. /**
  9794. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9795. * Supports definition of mesh facing forward or backward.
  9796. * @param {number} flipBack
  9797. * @param {number} twirlClockwise
  9798. * @param {number} tiltRight
  9799. */
  9800. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9801. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9802. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9803. };
  9804. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9805. this._pivotMatrix = matrix;
  9806. this._cache.pivotMatrixUpdated = true;
  9807. };
  9808. AbstractMesh.prototype.getPivotMatrix = function () {
  9809. return this._pivotMatrix;
  9810. };
  9811. AbstractMesh.prototype._isSynchronized = function () {
  9812. if (this._isDirty) {
  9813. return false;
  9814. }
  9815. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9816. return false;
  9817. if (this._cache.pivotMatrixUpdated) {
  9818. return false;
  9819. }
  9820. if (this.infiniteDistance) {
  9821. return false;
  9822. }
  9823. if (!this._cache.position.equals(this.position))
  9824. return false;
  9825. if (this.rotationQuaternion) {
  9826. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9827. return false;
  9828. }
  9829. else {
  9830. if (!this._cache.rotation.equals(this.rotation))
  9831. return false;
  9832. }
  9833. if (!this._cache.scaling.equals(this.scaling))
  9834. return false;
  9835. return true;
  9836. };
  9837. AbstractMesh.prototype._initCache = function () {
  9838. _super.prototype._initCache.call(this);
  9839. this._cache.localMatrixUpdated = false;
  9840. this._cache.position = BABYLON.Vector3.Zero();
  9841. this._cache.scaling = BABYLON.Vector3.Zero();
  9842. this._cache.rotation = BABYLON.Vector3.Zero();
  9843. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9844. };
  9845. AbstractMesh.prototype.markAsDirty = function (property) {
  9846. if (property === "rotation") {
  9847. this.rotationQuaternion = null;
  9848. }
  9849. this._currentRenderId = Number.MAX_VALUE;
  9850. this._isDirty = true;
  9851. };
  9852. AbstractMesh.prototype._updateBoundingInfo = function () {
  9853. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9854. this._boundingInfo._update(this.worldMatrixFromCache);
  9855. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9856. };
  9857. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9858. if (!this.subMeshes) {
  9859. return;
  9860. }
  9861. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9862. var subMesh = this.subMeshes[subIndex];
  9863. subMesh.updateBoundingInfo(matrix);
  9864. }
  9865. };
  9866. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9867. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9868. return this._worldMatrix;
  9869. }
  9870. this._cache.position.copyFrom(this.position);
  9871. this._cache.scaling.copyFrom(this.scaling);
  9872. this._cache.pivotMatrixUpdated = false;
  9873. this._currentRenderId = this.getScene().getRenderId();
  9874. this._isDirty = false;
  9875. // Scaling
  9876. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9877. // Rotation
  9878. if (this.rotationQuaternion) {
  9879. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9880. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9881. }
  9882. else {
  9883. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9884. this._cache.rotation.copyFrom(this.rotation);
  9885. }
  9886. // Translation
  9887. if (this.infiniteDistance && !this.parent) {
  9888. var camera = this.getScene().activeCamera;
  9889. var cameraWorldMatrix = camera.getWorldMatrix();
  9890. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9891. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9892. }
  9893. else {
  9894. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9895. }
  9896. // Composing transformations
  9897. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9898. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9899. // Billboarding
  9900. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9901. var localPosition = this.position.clone();
  9902. var zero = this.getScene().activeCamera.position.clone();
  9903. if (this.parent && this.parent.position) {
  9904. localPosition.addInPlace(this.parent.position);
  9905. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9906. }
  9907. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9908. zero = this.getScene().activeCamera.position;
  9909. }
  9910. else {
  9911. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9912. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9913. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9914. zero.y = localPosition.y + 0.001;
  9915. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9916. zero.z = localPosition.z + 0.001;
  9917. }
  9918. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9919. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9920. this._localBillboard.invert();
  9921. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9922. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9923. }
  9924. // Local world
  9925. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9926. // Parent
  9927. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9928. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9929. }
  9930. else {
  9931. this._worldMatrix.copyFrom(this._localWorld);
  9932. }
  9933. // Bounding info
  9934. this._updateBoundingInfo();
  9935. // Absolute position
  9936. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9937. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9938. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9939. }
  9940. return this._worldMatrix;
  9941. };
  9942. /**
  9943. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9944. * @param func: callback function to add
  9945. */
  9946. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9947. this._onAfterWorldMatrixUpdate.push(func);
  9948. };
  9949. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9950. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9951. if (index > -1) {
  9952. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9953. }
  9954. };
  9955. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9956. this.computeWorldMatrix();
  9957. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9958. };
  9959. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9960. this.computeWorldMatrix();
  9961. var invLocalWorldMatrix = this._localWorld.clone();
  9962. invLocalWorldMatrix.invert();
  9963. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9964. };
  9965. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9966. this.computeWorldMatrix();
  9967. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9968. };
  9969. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9970. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9971. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9972. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9973. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9974. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9975. /// <returns>Mesh oriented towards targetMesh</returns>
  9976. yawCor = yawCor || 0; // default to zero if undefined
  9977. pitchCor = pitchCor || 0;
  9978. rollCor = rollCor || 0;
  9979. var dv = targetPoint.subtract(this.position);
  9980. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9981. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9982. var pitch = Math.atan2(dv.y, len);
  9983. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9984. };
  9985. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9986. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9987. return false;
  9988. }
  9989. return true;
  9990. };
  9991. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9992. if (!camera) {
  9993. camera = this.getScene().activeCamera;
  9994. }
  9995. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9996. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9997. return false;
  9998. }
  9999. return true;
  10000. };
  10001. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10002. if (!this._boundingInfo || !mesh._boundingInfo) {
  10003. return false;
  10004. }
  10005. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10006. };
  10007. AbstractMesh.prototype.intersectsPoint = function (point) {
  10008. if (!this._boundingInfo) {
  10009. return false;
  10010. }
  10011. return this._boundingInfo.intersectsPoint(point);
  10012. };
  10013. // Physics
  10014. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10015. var physicsEngine = this.getScene().getPhysicsEngine();
  10016. if (!physicsEngine) {
  10017. return;
  10018. }
  10019. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10020. if (impostor.impostor) {
  10021. // Old API
  10022. options = impostor;
  10023. impostor = impostor.impostor;
  10024. }
  10025. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10026. physicsEngine._unregisterMesh(this);
  10027. return;
  10028. }
  10029. if (!options) {
  10030. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10031. }
  10032. else {
  10033. if (!options.mass && options.mass !== 0)
  10034. options.mass = 0;
  10035. if (!options.friction && options.friction !== 0)
  10036. options.friction = 0.2;
  10037. if (!options.restitution && options.restitution !== 0)
  10038. options.restitution = 0.2;
  10039. }
  10040. this._physicImpostor = impostor;
  10041. this._physicsMass = options.mass;
  10042. this._physicsFriction = options.friction;
  10043. this._physicRestitution = options.restitution;
  10044. return physicsEngine._registerMesh(this, impostor, options);
  10045. };
  10046. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10047. if (!this._physicImpostor) {
  10048. return BABYLON.PhysicsEngine.NoImpostor;
  10049. }
  10050. return this._physicImpostor;
  10051. };
  10052. AbstractMesh.prototype.getPhysicsMass = function () {
  10053. if (!this._physicsMass) {
  10054. return 0;
  10055. }
  10056. return this._physicsMass;
  10057. };
  10058. AbstractMesh.prototype.getPhysicsFriction = function () {
  10059. if (!this._physicsFriction) {
  10060. return 0;
  10061. }
  10062. return this._physicsFriction;
  10063. };
  10064. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10065. if (!this._physicRestitution) {
  10066. return 0;
  10067. }
  10068. return this._physicRestitution;
  10069. };
  10070. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10071. if (!camera) {
  10072. camera = this.getScene().activeCamera;
  10073. }
  10074. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10075. };
  10076. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10077. if (!camera) {
  10078. camera = this.getScene().activeCamera;
  10079. }
  10080. return this.absolutePosition.subtract(camera.position).length();
  10081. };
  10082. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10083. if (!this._physicImpostor) {
  10084. return;
  10085. }
  10086. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10087. };
  10088. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10089. if (!this._physicImpostor) {
  10090. return;
  10091. }
  10092. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10093. };
  10094. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10095. if (!this._physicImpostor) {
  10096. return;
  10097. }
  10098. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10099. };
  10100. // Collisions
  10101. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10102. var globalPosition = this.getAbsolutePosition();
  10103. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10104. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10105. this._collider.radius = this.ellipsoid;
  10106. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10107. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10108. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10109. this.position.addInPlace(this._diffPositionForCollisions);
  10110. }
  10111. };
  10112. // Submeshes octree
  10113. /**
  10114. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10115. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10116. */
  10117. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10118. if (maxCapacity === void 0) { maxCapacity = 64; }
  10119. if (maxDepth === void 0) { maxDepth = 2; }
  10120. if (!this._submeshesOctree) {
  10121. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10122. }
  10123. this.computeWorldMatrix(true);
  10124. // Update octree
  10125. var bbox = this.getBoundingInfo().boundingBox;
  10126. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10127. return this._submeshesOctree;
  10128. };
  10129. // Collisions
  10130. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10131. this._generatePointsArray();
  10132. // Transformation
  10133. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10134. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10135. subMesh._lastColliderWorldVertices = [];
  10136. subMesh._trianglePlanes = [];
  10137. var start = subMesh.verticesStart;
  10138. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10139. for (var i = start; i < end; i++) {
  10140. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10141. }
  10142. }
  10143. // Collide
  10144. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10145. };
  10146. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10147. var subMeshes;
  10148. var len;
  10149. // Octrees
  10150. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10151. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10152. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10153. len = intersections.length;
  10154. subMeshes = intersections.data;
  10155. }
  10156. else {
  10157. subMeshes = this.subMeshes;
  10158. len = subMeshes.length;
  10159. }
  10160. for (var index = 0; index < len; index++) {
  10161. var subMesh = subMeshes[index];
  10162. // Bounding test
  10163. if (len > 1 && !subMesh._checkCollision(collider))
  10164. continue;
  10165. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10166. }
  10167. };
  10168. AbstractMesh.prototype._checkCollision = function (collider) {
  10169. // Bounding box test
  10170. if (!this._boundingInfo._checkCollision(collider))
  10171. return;
  10172. // Transformation matrix
  10173. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10174. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10175. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10176. };
  10177. // Picking
  10178. AbstractMesh.prototype._generatePointsArray = function () {
  10179. return false;
  10180. };
  10181. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10182. var pickingInfo = new BABYLON.PickingInfo();
  10183. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10184. return pickingInfo;
  10185. }
  10186. if (!this._generatePointsArray()) {
  10187. return pickingInfo;
  10188. }
  10189. var intersectInfo = null;
  10190. // Octrees
  10191. var subMeshes;
  10192. var len;
  10193. if (this._submeshesOctree && this.useOctreeForPicking) {
  10194. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10195. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10196. len = intersections.length;
  10197. subMeshes = intersections.data;
  10198. }
  10199. else {
  10200. subMeshes = this.subMeshes;
  10201. len = subMeshes.length;
  10202. }
  10203. for (var index = 0; index < len; index++) {
  10204. var subMesh = subMeshes[index];
  10205. // Bounding test
  10206. if (len > 1 && !subMesh.canIntersects(ray))
  10207. continue;
  10208. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10209. if (currentIntersectInfo) {
  10210. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10211. intersectInfo = currentIntersectInfo;
  10212. intersectInfo.subMeshId = index;
  10213. if (fastCheck) {
  10214. break;
  10215. }
  10216. }
  10217. }
  10218. }
  10219. if (intersectInfo) {
  10220. // Get picked point
  10221. var world = this.getWorldMatrix();
  10222. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10223. var direction = ray.direction.clone();
  10224. direction = direction.scale(intersectInfo.distance);
  10225. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10226. var pickedPoint = worldOrigin.add(worldDirection);
  10227. // Return result
  10228. pickingInfo.hit = true;
  10229. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10230. pickingInfo.pickedPoint = pickedPoint;
  10231. pickingInfo.pickedMesh = this;
  10232. pickingInfo.bu = intersectInfo.bu;
  10233. pickingInfo.bv = intersectInfo.bv;
  10234. pickingInfo.faceId = intersectInfo.faceId;
  10235. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10236. return pickingInfo;
  10237. }
  10238. return pickingInfo;
  10239. };
  10240. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10241. return null;
  10242. };
  10243. AbstractMesh.prototype.releaseSubMeshes = function () {
  10244. if (this.subMeshes) {
  10245. while (this.subMeshes.length) {
  10246. this.subMeshes[0].dispose();
  10247. }
  10248. }
  10249. else {
  10250. this.subMeshes = new Array();
  10251. }
  10252. };
  10253. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10254. // Physics
  10255. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  10256. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10257. }
  10258. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10259. var other = this._intersectionsInProgress[index];
  10260. var pos = other._intersectionsInProgress.indexOf(this);
  10261. other._intersectionsInProgress.splice(pos, 1);
  10262. }
  10263. this._intersectionsInProgress = [];
  10264. // SubMeshes
  10265. this.releaseSubMeshes();
  10266. // Remove from scene
  10267. var index = this.getScene().meshes.indexOf(this);
  10268. if (index != -1) {
  10269. // Remove from the scene if mesh found
  10270. this.getScene().meshes.splice(index, 1);
  10271. }
  10272. if (!doNotRecurse) {
  10273. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10274. if (this.getScene().particleSystems[index].emitter == this) {
  10275. this.getScene().particleSystems[index].dispose();
  10276. index--;
  10277. }
  10278. }
  10279. // Children
  10280. var objects = this.getScene().meshes.slice(0);
  10281. for (index = 0; index < objects.length; index++) {
  10282. if (objects[index].parent == this) {
  10283. objects[index].dispose();
  10284. }
  10285. }
  10286. }
  10287. else {
  10288. for (index = 0; index < this.getScene().meshes.length; index++) {
  10289. var obj = this.getScene().meshes[index];
  10290. if (obj.parent === this) {
  10291. obj.parent = null;
  10292. obj.computeWorldMatrix(true);
  10293. }
  10294. }
  10295. }
  10296. this._onAfterWorldMatrixUpdate = [];
  10297. this._isDisposed = true;
  10298. // Callback
  10299. if (this.onDispose) {
  10300. this.onDispose();
  10301. }
  10302. };
  10303. // Statics
  10304. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10305. AbstractMesh._BILLBOARDMODE_X = 1;
  10306. AbstractMesh._BILLBOARDMODE_Y = 2;
  10307. AbstractMesh._BILLBOARDMODE_Z = 4;
  10308. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10309. return AbstractMesh;
  10310. })(BABYLON.Node);
  10311. BABYLON.AbstractMesh = AbstractMesh;
  10312. })(BABYLON || (BABYLON = {}));
  10313. //# sourceMappingURL=babylon.abstractMesh.js.map
  10314. var BABYLON;
  10315. (function (BABYLON) {
  10316. var _InstancesBatch = (function () {
  10317. function _InstancesBatch() {
  10318. this.mustReturn = false;
  10319. this.visibleInstances = new Array();
  10320. this.renderSelf = new Array();
  10321. }
  10322. return _InstancesBatch;
  10323. })();
  10324. BABYLON._InstancesBatch = _InstancesBatch;
  10325. var Mesh = (function (_super) {
  10326. __extends(Mesh, _super);
  10327. /**
  10328. * @constructor
  10329. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10330. * @param {Scene} scene - The scene to add this mesh to.
  10331. * @param {Node} parent - The parent of this mesh, if it has one
  10332. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10333. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10334. * When false, achieved by calling a clone(), also passing False.
  10335. * This will make creation of children, recursive.
  10336. */
  10337. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10338. if (parent === void 0) { parent = null; }
  10339. _super.call(this, name, scene);
  10340. // Members
  10341. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10342. this.instances = new Array();
  10343. this._LODLevels = new Array();
  10344. this._onBeforeRenderCallbacks = new Array();
  10345. this._onAfterRenderCallbacks = new Array();
  10346. this._visibleInstances = {};
  10347. this._renderIdForInstances = new Array();
  10348. this._batchCache = new _InstancesBatch();
  10349. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10350. if (source) {
  10351. // Geometry
  10352. if (source._geometry) {
  10353. source._geometry.applyToMesh(this);
  10354. }
  10355. // Deep copy
  10356. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10357. // Material
  10358. this.material = source.material;
  10359. if (!doNotCloneChildren) {
  10360. for (var index = 0; index < scene.meshes.length; index++) {
  10361. var mesh = scene.meshes[index];
  10362. if (mesh.parent === source) {
  10363. // doNotCloneChildren is always going to be False
  10364. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10365. }
  10366. }
  10367. }
  10368. for (index = 0; index < scene.particleSystems.length; index++) {
  10369. var system = scene.particleSystems[index];
  10370. if (system.emitter === source) {
  10371. system.clone(system.name, this);
  10372. }
  10373. }
  10374. this.computeWorldMatrix(true);
  10375. }
  10376. // Parent
  10377. if (parent !== null) {
  10378. this.parent = parent;
  10379. }
  10380. }
  10381. Object.defineProperty(Mesh, "FRONTSIDE", {
  10382. get: function () {
  10383. return Mesh._FRONTSIDE;
  10384. },
  10385. enumerable: true,
  10386. configurable: true
  10387. });
  10388. Object.defineProperty(Mesh, "BACKSIDE", {
  10389. get: function () {
  10390. return Mesh._BACKSIDE;
  10391. },
  10392. enumerable: true,
  10393. configurable: true
  10394. });
  10395. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10396. get: function () {
  10397. return Mesh._DOUBLESIDE;
  10398. },
  10399. enumerable: true,
  10400. configurable: true
  10401. });
  10402. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10403. get: function () {
  10404. return Mesh._DEFAULTSIDE;
  10405. },
  10406. enumerable: true,
  10407. configurable: true
  10408. });
  10409. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10410. // Methods
  10411. get: function () {
  10412. return this._LODLevels.length > 0;
  10413. },
  10414. enumerable: true,
  10415. configurable: true
  10416. });
  10417. Mesh.prototype._sortLODLevels = function () {
  10418. this._LODLevels.sort(function (a, b) {
  10419. if (a.distance < b.distance) {
  10420. return 1;
  10421. }
  10422. if (a.distance > b.distance) {
  10423. return -1;
  10424. }
  10425. return 0;
  10426. });
  10427. };
  10428. /**
  10429. * Add a mesh as LOD level triggered at the given distance.
  10430. * @param {number} distance - the distance from the center of the object to show this level
  10431. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10432. * @return {BABYLON.Mesh} this mesh (for chaining)
  10433. */
  10434. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10435. if (mesh && mesh._masterMesh) {
  10436. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10437. return this;
  10438. }
  10439. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10440. this._LODLevels.push(level);
  10441. if (mesh) {
  10442. mesh._masterMesh = this;
  10443. }
  10444. this._sortLODLevels();
  10445. return this;
  10446. };
  10447. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10448. for (var index = 0; index < this._LODLevels.length; index++) {
  10449. var level = this._LODLevels[index];
  10450. if (level.distance === distance) {
  10451. return level.mesh;
  10452. }
  10453. }
  10454. return null;
  10455. };
  10456. /**
  10457. * Remove a mesh from the LOD array
  10458. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10459. * @return {BABYLON.Mesh} this mesh (for chaining)
  10460. */
  10461. Mesh.prototype.removeLODLevel = function (mesh) {
  10462. for (var index = 0; index < this._LODLevels.length; index++) {
  10463. if (this._LODLevels[index].mesh === mesh) {
  10464. this._LODLevels.splice(index, 1);
  10465. if (mesh) {
  10466. mesh._masterMesh = null;
  10467. }
  10468. }
  10469. }
  10470. this._sortLODLevels();
  10471. return this;
  10472. };
  10473. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10474. if (!this._LODLevels || this._LODLevels.length === 0) {
  10475. return this;
  10476. }
  10477. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10478. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10479. return this;
  10480. }
  10481. for (var index = 0; index < this._LODLevels.length; index++) {
  10482. var level = this._LODLevels[index];
  10483. if (level.distance < distanceToCamera) {
  10484. if (level.mesh) {
  10485. level.mesh._preActivate();
  10486. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10487. }
  10488. return level.mesh;
  10489. }
  10490. }
  10491. return this;
  10492. };
  10493. Object.defineProperty(Mesh.prototype, "geometry", {
  10494. get: function () {
  10495. return this._geometry;
  10496. },
  10497. enumerable: true,
  10498. configurable: true
  10499. });
  10500. Mesh.prototype.getTotalVertices = function () {
  10501. if (!this._geometry) {
  10502. return 0;
  10503. }
  10504. return this._geometry.getTotalVertices();
  10505. };
  10506. Mesh.prototype.getVerticesData = function (kind) {
  10507. if (!this._geometry) {
  10508. return null;
  10509. }
  10510. return this._geometry.getVerticesData(kind);
  10511. };
  10512. Mesh.prototype.getVertexBuffer = function (kind) {
  10513. if (!this._geometry) {
  10514. return undefined;
  10515. }
  10516. return this._geometry.getVertexBuffer(kind);
  10517. };
  10518. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10519. if (!this._geometry) {
  10520. if (this._delayInfo) {
  10521. return this._delayInfo.indexOf(kind) !== -1;
  10522. }
  10523. return false;
  10524. }
  10525. return this._geometry.isVerticesDataPresent(kind);
  10526. };
  10527. Mesh.prototype.getVerticesDataKinds = function () {
  10528. if (!this._geometry) {
  10529. var result = [];
  10530. if (this._delayInfo) {
  10531. for (var kind in this._delayInfo) {
  10532. result.push(kind);
  10533. }
  10534. }
  10535. return result;
  10536. }
  10537. return this._geometry.getVerticesDataKinds();
  10538. };
  10539. Mesh.prototype.getTotalIndices = function () {
  10540. if (!this._geometry) {
  10541. return 0;
  10542. }
  10543. return this._geometry.getTotalIndices();
  10544. };
  10545. Mesh.prototype.getIndices = function () {
  10546. if (!this._geometry) {
  10547. return [];
  10548. }
  10549. return this._geometry.getIndices();
  10550. };
  10551. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10552. get: function () {
  10553. return this._masterMesh !== null && this._masterMesh !== undefined;
  10554. },
  10555. enumerable: true,
  10556. configurable: true
  10557. });
  10558. Mesh.prototype.isReady = function () {
  10559. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10560. return false;
  10561. }
  10562. return _super.prototype.isReady.call(this);
  10563. };
  10564. Mesh.prototype.isDisposed = function () {
  10565. return this._isDisposed;
  10566. };
  10567. // Methods
  10568. Mesh.prototype._preActivate = function () {
  10569. var sceneRenderId = this.getScene().getRenderId();
  10570. if (this._preActivateId === sceneRenderId) {
  10571. return;
  10572. }
  10573. this._preActivateId = sceneRenderId;
  10574. this._visibleInstances = null;
  10575. };
  10576. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10577. if (!this._visibleInstances) {
  10578. this._visibleInstances = {};
  10579. this._visibleInstances.defaultRenderId = renderId;
  10580. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10581. }
  10582. if (!this._visibleInstances[renderId]) {
  10583. this._visibleInstances[renderId] = new Array();
  10584. }
  10585. this._visibleInstances[renderId].push(instance);
  10586. };
  10587. Mesh.prototype.refreshBoundingInfo = function () {
  10588. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10589. if (data) {
  10590. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10591. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10592. }
  10593. if (this.subMeshes) {
  10594. for (var index = 0; index < this.subMeshes.length; index++) {
  10595. this.subMeshes[index].refreshBoundingInfo();
  10596. }
  10597. }
  10598. this._updateBoundingInfo();
  10599. };
  10600. Mesh.prototype._createGlobalSubMesh = function () {
  10601. var totalVertices = this.getTotalVertices();
  10602. if (!totalVertices || !this.getIndices()) {
  10603. return null;
  10604. }
  10605. this.releaseSubMeshes();
  10606. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10607. };
  10608. Mesh.prototype.subdivide = function (count) {
  10609. if (count < 1) {
  10610. return;
  10611. }
  10612. var totalIndices = this.getTotalIndices();
  10613. var subdivisionSize = (totalIndices / count) | 0;
  10614. var offset = 0;
  10615. while (subdivisionSize % 3 !== 0) {
  10616. subdivisionSize++;
  10617. }
  10618. this.releaseSubMeshes();
  10619. for (var index = 0; index < count; index++) {
  10620. if (offset >= totalIndices) {
  10621. break;
  10622. }
  10623. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10624. offset += subdivisionSize;
  10625. }
  10626. this.synchronizeInstances();
  10627. };
  10628. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10629. if (kind instanceof Array) {
  10630. var temp = data;
  10631. data = kind;
  10632. kind = temp;
  10633. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10634. }
  10635. if (!this._geometry) {
  10636. var vertexData = new BABYLON.VertexData();
  10637. vertexData.set(data, kind);
  10638. var scene = this.getScene();
  10639. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10640. }
  10641. else {
  10642. this._geometry.setVerticesData(kind, data, updatable, stride);
  10643. }
  10644. };
  10645. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10646. if (!this._geometry) {
  10647. return;
  10648. }
  10649. if (!makeItUnique) {
  10650. this._geometry.updateVerticesData(kind, data, updateExtends);
  10651. }
  10652. else {
  10653. this.makeGeometryUnique();
  10654. this.updateVerticesData(kind, data, updateExtends, false);
  10655. }
  10656. };
  10657. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10658. if (!this._geometry) {
  10659. return;
  10660. }
  10661. if (!makeItUnique) {
  10662. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10663. }
  10664. else {
  10665. this.makeGeometryUnique();
  10666. this.updateVerticesDataDirectly(kind, data, offset, false);
  10667. }
  10668. };
  10669. Mesh.prototype.makeGeometryUnique = function () {
  10670. if (!this._geometry) {
  10671. return;
  10672. }
  10673. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10674. geometry.applyToMesh(this);
  10675. };
  10676. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10677. if (!this._geometry) {
  10678. var vertexData = new BABYLON.VertexData();
  10679. vertexData.indices = indices;
  10680. var scene = this.getScene();
  10681. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10682. }
  10683. else {
  10684. this._geometry.setIndices(indices, totalVertices);
  10685. }
  10686. };
  10687. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10688. var engine = this.getScene().getEngine();
  10689. // Wireframe
  10690. var indexToBind;
  10691. switch (fillMode) {
  10692. case BABYLON.Material.PointFillMode:
  10693. indexToBind = null;
  10694. break;
  10695. case BABYLON.Material.WireFrameFillMode:
  10696. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10697. break;
  10698. default:
  10699. case BABYLON.Material.TriangleFillMode:
  10700. indexToBind = this._geometry.getIndexBuffer();
  10701. break;
  10702. }
  10703. // VBOs
  10704. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10705. };
  10706. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10707. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10708. return;
  10709. }
  10710. var engine = this.getScene().getEngine();
  10711. switch (fillMode) {
  10712. case BABYLON.Material.PointFillMode:
  10713. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10714. break;
  10715. case BABYLON.Material.WireFrameFillMode:
  10716. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10717. break;
  10718. default:
  10719. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10720. }
  10721. };
  10722. Mesh.prototype.registerBeforeRender = function (func) {
  10723. this._onBeforeRenderCallbacks.push(func);
  10724. };
  10725. Mesh.prototype.unregisterBeforeRender = function (func) {
  10726. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10727. if (index > -1) {
  10728. this._onBeforeRenderCallbacks.splice(index, 1);
  10729. }
  10730. };
  10731. Mesh.prototype.registerAfterRender = function (func) {
  10732. this._onAfterRenderCallbacks.push(func);
  10733. };
  10734. Mesh.prototype.unregisterAfterRender = function (func) {
  10735. var index = this._onAfterRenderCallbacks.indexOf(func);
  10736. if (index > -1) {
  10737. this._onAfterRenderCallbacks.splice(index, 1);
  10738. }
  10739. };
  10740. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10741. var scene = this.getScene();
  10742. this._batchCache.mustReturn = false;
  10743. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10744. this._batchCache.visibleInstances[subMeshId] = null;
  10745. if (this._visibleInstances) {
  10746. var currentRenderId = scene.getRenderId();
  10747. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10748. var selfRenderId = this._renderId;
  10749. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10750. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10751. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10752. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10753. }
  10754. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10755. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10756. this._batchCache.mustReturn = true;
  10757. return this._batchCache;
  10758. }
  10759. if (currentRenderId !== selfRenderId) {
  10760. this._batchCache.renderSelf[subMeshId] = false;
  10761. }
  10762. }
  10763. this._renderIdForInstances[subMeshId] = currentRenderId;
  10764. }
  10765. return this._batchCache;
  10766. };
  10767. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10768. var visibleInstances = batch.visibleInstances[subMesh._id];
  10769. var matricesCount = visibleInstances.length + 1;
  10770. var bufferSize = matricesCount * 16 * 4;
  10771. while (this._instancesBufferSize < bufferSize) {
  10772. this._instancesBufferSize *= 2;
  10773. }
  10774. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10775. if (this._worldMatricesInstancesBuffer) {
  10776. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10777. }
  10778. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10779. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10780. }
  10781. var offset = 0;
  10782. var instancesCount = 0;
  10783. var world = this.getWorldMatrix();
  10784. if (batch.renderSelf[subMesh._id]) {
  10785. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10786. offset += 16;
  10787. instancesCount++;
  10788. }
  10789. if (visibleInstances) {
  10790. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10791. var instance = visibleInstances[instanceIndex];
  10792. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10793. offset += 16;
  10794. instancesCount++;
  10795. }
  10796. }
  10797. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10798. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10799. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10800. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10801. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10802. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10803. this._draw(subMesh, fillMode, instancesCount);
  10804. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10805. };
  10806. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10807. var scene = this.getScene();
  10808. var engine = scene.getEngine();
  10809. if (hardwareInstancedRendering) {
  10810. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10811. }
  10812. else {
  10813. if (batch.renderSelf[subMesh._id]) {
  10814. // Draw
  10815. if (onBeforeDraw) {
  10816. onBeforeDraw(false, this.getWorldMatrix());
  10817. }
  10818. this._draw(subMesh, fillMode);
  10819. }
  10820. if (batch.visibleInstances[subMesh._id]) {
  10821. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10822. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10823. // World
  10824. var world = instance.getWorldMatrix();
  10825. if (onBeforeDraw) {
  10826. onBeforeDraw(true, world);
  10827. }
  10828. // Draw
  10829. this._draw(subMesh, fillMode);
  10830. }
  10831. }
  10832. }
  10833. };
  10834. Mesh.prototype.render = function (subMesh) {
  10835. var scene = this.getScene();
  10836. // Managing instances
  10837. var batch = this._getInstancesRenderList(subMesh._id);
  10838. if (batch.mustReturn) {
  10839. return;
  10840. }
  10841. // Checking geometry state
  10842. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10843. return;
  10844. }
  10845. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10846. this._onBeforeRenderCallbacks[callbackIndex](this);
  10847. }
  10848. var engine = scene.getEngine();
  10849. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10850. // Material
  10851. var effectiveMaterial = subMesh.getMaterial();
  10852. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10853. return;
  10854. }
  10855. // Outline - step 1
  10856. var savedDepthWrite = engine.getDepthWrite();
  10857. if (this.renderOutline) {
  10858. engine.setDepthWrite(false);
  10859. scene.getOutlineRenderer().render(subMesh, batch);
  10860. engine.setDepthWrite(savedDepthWrite);
  10861. }
  10862. effectiveMaterial._preBind();
  10863. var effect = effectiveMaterial.getEffect();
  10864. // Bind
  10865. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10866. this._bind(subMesh, effect, fillMode);
  10867. var world = this.getWorldMatrix();
  10868. effectiveMaterial.bind(world, this);
  10869. // Draw
  10870. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10871. if (isInstance) {
  10872. effectiveMaterial.bindOnlyWorldMatrix(world);
  10873. }
  10874. });
  10875. // Unbind
  10876. effectiveMaterial.unbind();
  10877. // Outline - step 2
  10878. if (this.renderOutline && savedDepthWrite) {
  10879. engine.setDepthWrite(true);
  10880. engine.setColorWrite(false);
  10881. scene.getOutlineRenderer().render(subMesh, batch);
  10882. engine.setColorWrite(true);
  10883. }
  10884. // Overlay
  10885. if (this.renderOverlay) {
  10886. var currentMode = engine.getAlphaMode();
  10887. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10888. scene.getOutlineRenderer().render(subMesh, batch, true);
  10889. engine.setAlphaMode(currentMode);
  10890. }
  10891. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10892. this._onAfterRenderCallbacks[callbackIndex](this);
  10893. }
  10894. };
  10895. Mesh.prototype.getEmittedParticleSystems = function () {
  10896. var results = new Array();
  10897. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10898. var particleSystem = this.getScene().particleSystems[index];
  10899. if (particleSystem.emitter === this) {
  10900. results.push(particleSystem);
  10901. }
  10902. }
  10903. return results;
  10904. };
  10905. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10906. var results = new Array();
  10907. var descendants = this.getDescendants();
  10908. descendants.push(this);
  10909. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10910. var particleSystem = this.getScene().particleSystems[index];
  10911. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10912. results.push(particleSystem);
  10913. }
  10914. }
  10915. return results;
  10916. };
  10917. Mesh.prototype.getChildren = function () {
  10918. var results = [];
  10919. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10920. var mesh = this.getScene().meshes[index];
  10921. if (mesh.parent === this) {
  10922. results.push(mesh);
  10923. }
  10924. }
  10925. return results;
  10926. };
  10927. Mesh.prototype._checkDelayState = function () {
  10928. var _this = this;
  10929. var that = this;
  10930. var scene = this.getScene();
  10931. if (this._geometry) {
  10932. this._geometry.load(scene);
  10933. }
  10934. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10935. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10936. scene._addPendingData(that);
  10937. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  10938. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10939. if (data instanceof ArrayBuffer) {
  10940. _this._delayLoadingFunction(data, _this);
  10941. }
  10942. else {
  10943. _this._delayLoadingFunction(JSON.parse(data), _this);
  10944. }
  10945. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10946. scene._removePendingData(_this);
  10947. }, function () {
  10948. }, scene.database, getBinaryData);
  10949. }
  10950. };
  10951. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10952. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10953. return false;
  10954. }
  10955. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10956. return false;
  10957. }
  10958. this._checkDelayState();
  10959. return true;
  10960. };
  10961. Mesh.prototype.setMaterialByID = function (id) {
  10962. var materials = this.getScene().materials;
  10963. for (var index = 0; index < materials.length; index++) {
  10964. if (materials[index].id === id) {
  10965. this.material = materials[index];
  10966. return;
  10967. }
  10968. }
  10969. // Multi
  10970. var multiMaterials = this.getScene().multiMaterials;
  10971. for (index = 0; index < multiMaterials.length; index++) {
  10972. if (multiMaterials[index].id === id) {
  10973. this.material = multiMaterials[index];
  10974. return;
  10975. }
  10976. }
  10977. };
  10978. Mesh.prototype.getAnimatables = function () {
  10979. var results = [];
  10980. if (this.material) {
  10981. results.push(this.material);
  10982. }
  10983. if (this.skeleton) {
  10984. results.push(this.skeleton);
  10985. }
  10986. return results;
  10987. };
  10988. // Geometry
  10989. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10990. // Position
  10991. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10992. return;
  10993. }
  10994. this._resetPointsArrayCache();
  10995. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10996. var temp = [];
  10997. for (var index = 0; index < data.length; index += 3) {
  10998. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10999. }
  11000. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11001. // Normals
  11002. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11003. return;
  11004. }
  11005. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11006. for (index = 0; index < data.length; index += 3) {
  11007. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11008. }
  11009. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11010. };
  11011. // Cache
  11012. Mesh.prototype._resetPointsArrayCache = function () {
  11013. this._positions = null;
  11014. };
  11015. Mesh.prototype._generatePointsArray = function () {
  11016. if (this._positions)
  11017. return true;
  11018. this._positions = [];
  11019. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11020. if (!data) {
  11021. return false;
  11022. }
  11023. for (var index = 0; index < data.length; index += 3) {
  11024. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11025. }
  11026. return true;
  11027. };
  11028. // Clone
  11029. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11030. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11031. };
  11032. // Dispose
  11033. Mesh.prototype.dispose = function (doNotRecurse) {
  11034. if (this._geometry) {
  11035. this._geometry.releaseForMesh(this, true);
  11036. }
  11037. // Instances
  11038. if (this._worldMatricesInstancesBuffer) {
  11039. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11040. this._worldMatricesInstancesBuffer = null;
  11041. }
  11042. while (this.instances.length) {
  11043. this.instances[0].dispose();
  11044. }
  11045. _super.prototype.dispose.call(this, doNotRecurse);
  11046. };
  11047. // Geometric tools
  11048. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11049. var _this = this;
  11050. var scene = this.getScene();
  11051. var onload = function (img) {
  11052. // Getting height map data
  11053. var canvas = document.createElement("canvas");
  11054. var context = canvas.getContext("2d");
  11055. var heightMapWidth = img.width;
  11056. var heightMapHeight = img.height;
  11057. canvas.width = heightMapWidth;
  11058. canvas.height = heightMapHeight;
  11059. context.drawImage(img, 0, 0);
  11060. // Create VertexData from map data
  11061. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11062. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11063. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11064. //execute success callback, if set
  11065. if (onSuccess) {
  11066. onSuccess(_this);
  11067. }
  11068. };
  11069. BABYLON.Tools.LoadImage(url, onload, function () {
  11070. }, scene.database);
  11071. };
  11072. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11073. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11074. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11075. return;
  11076. }
  11077. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11078. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11079. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11080. var position = BABYLON.Vector3.Zero();
  11081. var normal = BABYLON.Vector3.Zero();
  11082. var uv = BABYLON.Vector2.Zero();
  11083. for (var index = 0; index < positions.length; index += 3) {
  11084. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11085. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11086. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11087. // Compute height
  11088. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11089. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11090. var pos = (u + v * heightMapWidth) * 4;
  11091. var r = buffer[pos] / 255.0;
  11092. var g = buffer[pos + 1] / 255.0;
  11093. var b = buffer[pos + 2] / 255.0;
  11094. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11095. normal.normalize();
  11096. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11097. position = position.add(normal);
  11098. position.toArray(positions, index);
  11099. }
  11100. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11101. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11102. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11103. };
  11104. Mesh.prototype.convertToFlatShadedMesh = function () {
  11105. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11106. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11107. var kinds = this.getVerticesDataKinds();
  11108. var vbs = [];
  11109. var data = [];
  11110. var newdata = [];
  11111. var updatableNormals = false;
  11112. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11113. var kind = kinds[kindIndex];
  11114. var vertexBuffer = this.getVertexBuffer(kind);
  11115. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11116. updatableNormals = vertexBuffer.isUpdatable();
  11117. kinds.splice(kindIndex, 1);
  11118. kindIndex--;
  11119. continue;
  11120. }
  11121. vbs[kind] = vertexBuffer;
  11122. data[kind] = vbs[kind].getData();
  11123. newdata[kind] = [];
  11124. }
  11125. // Save previous submeshes
  11126. var previousSubmeshes = this.subMeshes.slice(0);
  11127. var indices = this.getIndices();
  11128. var totalIndices = this.getTotalIndices();
  11129. for (var index = 0; index < totalIndices; index++) {
  11130. var vertexIndex = indices[index];
  11131. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11132. kind = kinds[kindIndex];
  11133. var stride = vbs[kind].getStrideSize();
  11134. for (var offset = 0; offset < stride; offset++) {
  11135. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11136. }
  11137. }
  11138. }
  11139. // Updating faces & normal
  11140. var normals = [];
  11141. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11142. for (index = 0; index < totalIndices; index += 3) {
  11143. indices[index] = index;
  11144. indices[index + 1] = index + 1;
  11145. indices[index + 2] = index + 2;
  11146. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11147. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11148. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11149. var p1p2 = p1.subtract(p2);
  11150. var p3p2 = p3.subtract(p2);
  11151. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11152. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11153. normals.push(normal.x);
  11154. normals.push(normal.y);
  11155. normals.push(normal.z);
  11156. }
  11157. }
  11158. this.setIndices(indices);
  11159. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11160. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11161. kind = kinds[kindIndex];
  11162. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11163. }
  11164. // Updating submeshes
  11165. this.releaseSubMeshes();
  11166. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11167. var previousOne = previousSubmeshes[submeshIndex];
  11168. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11169. }
  11170. this.synchronizeInstances();
  11171. };
  11172. // Instances
  11173. Mesh.prototype.createInstance = function (name) {
  11174. return new BABYLON.InstancedMesh(name, this);
  11175. };
  11176. Mesh.prototype.synchronizeInstances = function () {
  11177. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11178. var instance = this.instances[instanceIndex];
  11179. instance._syncSubMeshes();
  11180. }
  11181. };
  11182. /**
  11183. * Simplify the mesh according to the given array of settings.
  11184. * Function will return immediately and will simplify async.
  11185. * @param settings a collection of simplification settings.
  11186. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11187. * @param type the type of simplification to run.
  11188. * successCallback optional success callback to be called after the simplification finished processing all settings.
  11189. */
  11190. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11191. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11192. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11193. this.getScene().simplificationQueue.addTask({
  11194. settings: settings,
  11195. parallelProcessing: parallelProcessing,
  11196. mesh: this,
  11197. simplificationType: simplificationType,
  11198. successCallback: successCallback
  11199. });
  11200. };
  11201. // Statics
  11202. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11203. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11204. var ribbon = new Mesh(name, scene);
  11205. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11206. vertexData.applyToMesh(ribbon, updatable);
  11207. return ribbon;
  11208. };
  11209. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11210. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11211. var box = new Mesh(name, scene);
  11212. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11213. vertexData.applyToMesh(box, updatable);
  11214. return box;
  11215. };
  11216. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11217. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11218. var sphere = new Mesh(name, scene);
  11219. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11220. vertexData.applyToMesh(sphere, updatable);
  11221. return sphere;
  11222. };
  11223. // Cylinder and cone (Code inspired by SharpDX.org)
  11224. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11225. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11226. // subdivisions is a new parameter, we need to support old signature
  11227. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11228. if (scene !== undefined) {
  11229. updatable = scene;
  11230. }
  11231. scene = subdivisions;
  11232. subdivisions = 1;
  11233. }
  11234. var cylinder = new Mesh(name, scene);
  11235. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11236. vertexData.applyToMesh(cylinder, updatable);
  11237. return cylinder;
  11238. };
  11239. // Torus (Code from SharpDX.org)
  11240. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11241. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11242. var torus = new Mesh(name, scene);
  11243. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11244. vertexData.applyToMesh(torus, updatable);
  11245. return torus;
  11246. };
  11247. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11248. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11249. var torusKnot = new Mesh(name, scene);
  11250. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11251. vertexData.applyToMesh(torusKnot, updatable);
  11252. return torusKnot;
  11253. };
  11254. // Lines
  11255. Mesh.CreateLines = function (name, points, scene, updatable) {
  11256. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11257. var vertexData = BABYLON.VertexData.CreateLines(points);
  11258. vertexData.applyToMesh(lines, updatable);
  11259. return lines;
  11260. };
  11261. // Plane & ground
  11262. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11263. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11264. var plane = new Mesh(name, scene);
  11265. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11266. vertexData.applyToMesh(plane, updatable);
  11267. return plane;
  11268. };
  11269. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11270. var ground = new BABYLON.GroundMesh(name, scene);
  11271. ground._setReady(false);
  11272. ground._subdivisions = subdivisions;
  11273. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11274. vertexData.applyToMesh(ground, updatable);
  11275. ground._setReady(true);
  11276. return ground;
  11277. };
  11278. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11279. var tiledGround = new Mesh(name, scene);
  11280. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11281. vertexData.applyToMesh(tiledGround, updatable);
  11282. return tiledGround;
  11283. };
  11284. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11285. var ground = new BABYLON.GroundMesh(name, scene);
  11286. ground._subdivisions = subdivisions;
  11287. ground._setReady(false);
  11288. var onload = function (img) {
  11289. // Getting height map data
  11290. var canvas = document.createElement("canvas");
  11291. var context = canvas.getContext("2d");
  11292. var heightMapWidth = img.width;
  11293. var heightMapHeight = img.height;
  11294. canvas.width = heightMapWidth;
  11295. canvas.height = heightMapHeight;
  11296. context.drawImage(img, 0, 0);
  11297. // Create VertexData from map data
  11298. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11299. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11300. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11301. vertexData.applyToMesh(ground, updatable);
  11302. ground._setReady(true);
  11303. //execute ready callback, if set
  11304. if (onReady) {
  11305. onReady(ground);
  11306. }
  11307. };
  11308. BABYLON.Tools.LoadImage(url, onload, function () {
  11309. }, scene.database);
  11310. return ground;
  11311. };
  11312. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11313. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11314. var path3D = new BABYLON.Path3D(path);
  11315. var tangents = path3D.getTangents();
  11316. var normals = path3D.getNormals();
  11317. var distances = path3D.getDistances();
  11318. var pi2 = Math.PI * 2;
  11319. var step = pi2 / tesselation;
  11320. var returnRadius = function (i, distance) { return radius; };
  11321. var radiusFunctionFinal = radiusFunction || returnRadius;
  11322. var circlePaths = [];
  11323. var circlePath;
  11324. var rad;
  11325. var normal;
  11326. var rotated;
  11327. var rotationMatrix;
  11328. for (var i = 0; i < path.length; i++) {
  11329. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11330. circlePath = []; // current circle array
  11331. normal = normals[i]; // current normal
  11332. for (var ang = 0; ang < pi2; ang += step) {
  11333. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11334. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11335. circlePath.push(rotated);
  11336. }
  11337. circlePaths.push(circlePath);
  11338. }
  11339. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11340. return tube;
  11341. };
  11342. // Tools
  11343. Mesh.MinMax = function (meshes) {
  11344. var minVector = null;
  11345. var maxVector = null;
  11346. for (var i in meshes) {
  11347. var mesh = meshes[i];
  11348. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11349. if (!minVector) {
  11350. minVector = boundingBox.minimumWorld;
  11351. maxVector = boundingBox.maximumWorld;
  11352. continue;
  11353. }
  11354. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11355. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11356. }
  11357. return {
  11358. min: minVector,
  11359. max: maxVector
  11360. };
  11361. };
  11362. Mesh.Center = function (meshesOrMinMaxVector) {
  11363. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11364. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11365. };
  11366. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11367. if (disposeSource === void 0) { disposeSource = true; }
  11368. var source = meshes[0];
  11369. var material = source.material;
  11370. var scene = source.getScene();
  11371. if (!allow32BitsIndices) {
  11372. var totalVertices = 0;
  11373. for (var index = 0; index < meshes.length; index++) {
  11374. totalVertices += meshes[index].getTotalVertices();
  11375. if (totalVertices > 65536) {
  11376. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11377. return null;
  11378. }
  11379. }
  11380. }
  11381. // Merge
  11382. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11383. vertexData.transform(source.getWorldMatrix());
  11384. for (index = 1; index < meshes.length; index++) {
  11385. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11386. otherVertexData.transform(meshes[index].getWorldMatrix());
  11387. vertexData.merge(otherVertexData);
  11388. }
  11389. var newMesh = new Mesh(source.name + "_merged", scene);
  11390. vertexData.applyToMesh(newMesh);
  11391. // Setting properties
  11392. newMesh.material = material;
  11393. newMesh.checkCollisions = source.checkCollisions;
  11394. // Cleaning
  11395. if (disposeSource) {
  11396. for (index = 0; index < meshes.length; index++) {
  11397. meshes[index].dispose();
  11398. }
  11399. }
  11400. return newMesh;
  11401. };
  11402. // Consts
  11403. Mesh._FRONTSIDE = 0;
  11404. Mesh._BACKSIDE = 1;
  11405. Mesh._DOUBLESIDE = 2;
  11406. Mesh._DEFAULTSIDE = 0;
  11407. return Mesh;
  11408. })(BABYLON.AbstractMesh);
  11409. BABYLON.Mesh = Mesh;
  11410. })(BABYLON || (BABYLON = {}));
  11411. //# sourceMappingURL=babylon.mesh.js.map
  11412. var BABYLON;
  11413. (function (BABYLON) {
  11414. var GroundMesh = (function (_super) {
  11415. __extends(GroundMesh, _super);
  11416. function GroundMesh(name, scene) {
  11417. _super.call(this, name, scene);
  11418. this.generateOctree = false;
  11419. this._worldInverse = new BABYLON.Matrix();
  11420. }
  11421. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11422. get: function () {
  11423. return this._subdivisions;
  11424. },
  11425. enumerable: true,
  11426. configurable: true
  11427. });
  11428. GroundMesh.prototype.optimize = function (chunksCount) {
  11429. this.subdivide(this._subdivisions);
  11430. this.createOrUpdateSubmeshesOctree(32);
  11431. };
  11432. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11433. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11434. this.getWorldMatrix().invertToRef(this._worldInverse);
  11435. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11436. var pickInfo = this.intersects(ray);
  11437. if (pickInfo.hit) {
  11438. return pickInfo.pickedPoint.y;
  11439. }
  11440. return 0;
  11441. };
  11442. return GroundMesh;
  11443. })(BABYLON.Mesh);
  11444. BABYLON.GroundMesh = GroundMesh;
  11445. })(BABYLON || (BABYLON = {}));
  11446. //# sourceMappingURL=babylon.groundMesh.js.map
  11447. var BABYLON;
  11448. (function (BABYLON) {
  11449. /**
  11450. * Creates an instance based on a source mesh.
  11451. */
  11452. var InstancedMesh = (function (_super) {
  11453. __extends(InstancedMesh, _super);
  11454. function InstancedMesh(name, source) {
  11455. _super.call(this, name, source.getScene());
  11456. source.instances.push(this);
  11457. this._sourceMesh = source;
  11458. this.position.copyFrom(source.position);
  11459. this.rotation.copyFrom(source.rotation);
  11460. this.scaling.copyFrom(source.scaling);
  11461. if (source.rotationQuaternion) {
  11462. this.rotationQuaternion = source.rotationQuaternion.clone();
  11463. }
  11464. this.infiniteDistance = source.infiniteDistance;
  11465. this.setPivotMatrix(source.getPivotMatrix());
  11466. this.refreshBoundingInfo();
  11467. this._syncSubMeshes();
  11468. }
  11469. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11470. // Methods
  11471. get: function () {
  11472. return this._sourceMesh.receiveShadows;
  11473. },
  11474. enumerable: true,
  11475. configurable: true
  11476. });
  11477. Object.defineProperty(InstancedMesh.prototype, "material", {
  11478. get: function () {
  11479. return this._sourceMesh.material;
  11480. },
  11481. enumerable: true,
  11482. configurable: true
  11483. });
  11484. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11485. get: function () {
  11486. return this._sourceMesh.visibility;
  11487. },
  11488. enumerable: true,
  11489. configurable: true
  11490. });
  11491. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11492. get: function () {
  11493. return this._sourceMesh.skeleton;
  11494. },
  11495. enumerable: true,
  11496. configurable: true
  11497. });
  11498. InstancedMesh.prototype.getTotalVertices = function () {
  11499. return this._sourceMesh.getTotalVertices();
  11500. };
  11501. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11502. get: function () {
  11503. return this._sourceMesh;
  11504. },
  11505. enumerable: true,
  11506. configurable: true
  11507. });
  11508. InstancedMesh.prototype.getVerticesData = function (kind) {
  11509. return this._sourceMesh.getVerticesData(kind);
  11510. };
  11511. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11512. return this._sourceMesh.isVerticesDataPresent(kind);
  11513. };
  11514. InstancedMesh.prototype.getIndices = function () {
  11515. return this._sourceMesh.getIndices();
  11516. };
  11517. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11518. get: function () {
  11519. return this._sourceMesh._positions;
  11520. },
  11521. enumerable: true,
  11522. configurable: true
  11523. });
  11524. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11525. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11526. if (data) {
  11527. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11528. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11529. }
  11530. this._updateBoundingInfo();
  11531. };
  11532. InstancedMesh.prototype._preActivate = function () {
  11533. if (this._currentLOD) {
  11534. this._currentLOD._preActivate();
  11535. }
  11536. };
  11537. InstancedMesh.prototype._activate = function (renderId) {
  11538. if (this._currentLOD) {
  11539. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11540. }
  11541. };
  11542. InstancedMesh.prototype.getLOD = function (camera) {
  11543. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11544. if (this._currentLOD === this.sourceMesh) {
  11545. return this;
  11546. }
  11547. return this._currentLOD;
  11548. };
  11549. InstancedMesh.prototype._syncSubMeshes = function () {
  11550. this.releaseSubMeshes();
  11551. if (this._sourceMesh.subMeshes) {
  11552. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11553. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11554. }
  11555. }
  11556. };
  11557. InstancedMesh.prototype._generatePointsArray = function () {
  11558. return this._sourceMesh._generatePointsArray();
  11559. };
  11560. // Clone
  11561. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11562. var result = this._sourceMesh.createInstance(name);
  11563. // Deep copy
  11564. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11565. // Bounding info
  11566. this.refreshBoundingInfo();
  11567. // Parent
  11568. if (newParent) {
  11569. result.parent = newParent;
  11570. }
  11571. if (!doNotCloneChildren) {
  11572. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11573. var mesh = this.getScene().meshes[index];
  11574. if (mesh.parent === this) {
  11575. mesh.clone(mesh.name, result);
  11576. }
  11577. }
  11578. }
  11579. result.computeWorldMatrix(true);
  11580. return result;
  11581. };
  11582. // Dispoe
  11583. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11584. // Remove from mesh
  11585. var index = this._sourceMesh.instances.indexOf(this);
  11586. this._sourceMesh.instances.splice(index, 1);
  11587. _super.prototype.dispose.call(this, doNotRecurse);
  11588. };
  11589. return InstancedMesh;
  11590. })(BABYLON.AbstractMesh);
  11591. BABYLON.InstancedMesh = InstancedMesh;
  11592. })(BABYLON || (BABYLON = {}));
  11593. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11594. (function (BABYLON) {
  11595. var SubMesh = (function () {
  11596. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11597. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11598. this.materialIndex = materialIndex;
  11599. this.verticesStart = verticesStart;
  11600. this.verticesCount = verticesCount;
  11601. this.indexStart = indexStart;
  11602. this.indexCount = indexCount;
  11603. this._renderId = 0;
  11604. this._mesh = mesh;
  11605. this._renderingMesh = renderingMesh || mesh;
  11606. mesh.subMeshes.push(this);
  11607. this._id = mesh.subMeshes.length - 1;
  11608. if (createBoundingBox) {
  11609. this.refreshBoundingInfo();
  11610. }
  11611. }
  11612. SubMesh.prototype.getBoundingInfo = function () {
  11613. return this._boundingInfo;
  11614. };
  11615. SubMesh.prototype.getMesh = function () {
  11616. return this._mesh;
  11617. };
  11618. SubMesh.prototype.getRenderingMesh = function () {
  11619. return this._renderingMesh;
  11620. };
  11621. SubMesh.prototype.getMaterial = function () {
  11622. var rootMaterial = this._renderingMesh.material;
  11623. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11624. var multiMaterial = rootMaterial;
  11625. return multiMaterial.getSubMaterial(this.materialIndex);
  11626. }
  11627. if (!rootMaterial) {
  11628. return this._mesh.getScene().defaultMaterial;
  11629. }
  11630. return rootMaterial;
  11631. };
  11632. // Methods
  11633. SubMesh.prototype.refreshBoundingInfo = function () {
  11634. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11635. if (!data) {
  11636. this._boundingInfo = this._mesh._boundingInfo;
  11637. return;
  11638. }
  11639. var indices = this._renderingMesh.getIndices();
  11640. var extend;
  11641. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11642. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11643. }
  11644. else {
  11645. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11646. }
  11647. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11648. };
  11649. SubMesh.prototype._checkCollision = function (collider) {
  11650. return this._boundingInfo._checkCollision(collider);
  11651. };
  11652. SubMesh.prototype.updateBoundingInfo = function (world) {
  11653. if (!this._boundingInfo) {
  11654. this.refreshBoundingInfo();
  11655. }
  11656. this._boundingInfo._update(world);
  11657. };
  11658. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11659. return this._boundingInfo.isInFrustum(frustumPlanes);
  11660. };
  11661. SubMesh.prototype.render = function () {
  11662. this._renderingMesh.render(this);
  11663. };
  11664. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11665. if (!this._linesIndexBuffer) {
  11666. var linesIndices = [];
  11667. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11668. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11669. }
  11670. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11671. this.linesIndexCount = linesIndices.length;
  11672. }
  11673. return this._linesIndexBuffer;
  11674. };
  11675. SubMesh.prototype.canIntersects = function (ray) {
  11676. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11677. };
  11678. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11679. var intersectInfo = null;
  11680. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11681. var p0 = positions[indices[index]];
  11682. var p1 = positions[indices[index + 1]];
  11683. var p2 = positions[indices[index + 2]];
  11684. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11685. if (currentIntersectInfo) {
  11686. if (currentIntersectInfo.distance < 0) {
  11687. continue;
  11688. }
  11689. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11690. intersectInfo = currentIntersectInfo;
  11691. intersectInfo.faceId = index / 3;
  11692. if (fastCheck) {
  11693. break;
  11694. }
  11695. }
  11696. }
  11697. }
  11698. return intersectInfo;
  11699. };
  11700. // Clone
  11701. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11702. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11703. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11704. return result;
  11705. };
  11706. // Dispose
  11707. SubMesh.prototype.dispose = function () {
  11708. if (this._linesIndexBuffer) {
  11709. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11710. this._linesIndexBuffer = null;
  11711. }
  11712. // Remove from mesh
  11713. var index = this._mesh.subMeshes.indexOf(this);
  11714. this._mesh.subMeshes.splice(index, 1);
  11715. };
  11716. // Statics
  11717. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11718. var minVertexIndex = Number.MAX_VALUE;
  11719. var maxVertexIndex = -Number.MAX_VALUE;
  11720. renderingMesh = renderingMesh || mesh;
  11721. var indices = renderingMesh.getIndices();
  11722. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11723. var vertexIndex = indices[index];
  11724. if (vertexIndex < minVertexIndex)
  11725. minVertexIndex = vertexIndex;
  11726. if (vertexIndex > maxVertexIndex)
  11727. maxVertexIndex = vertexIndex;
  11728. }
  11729. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11730. };
  11731. return SubMesh;
  11732. })();
  11733. BABYLON.SubMesh = SubMesh;
  11734. })(BABYLON || (BABYLON = {}));
  11735. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11736. (function (BABYLON) {
  11737. var BaseTexture = (function () {
  11738. function BaseTexture(scene) {
  11739. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11740. this.hasAlpha = false;
  11741. this.getAlphaFromRGB = false;
  11742. this.level = 1;
  11743. this.isCube = false;
  11744. this.isRenderTarget = false;
  11745. this.animations = new Array();
  11746. this.coordinatesIndex = 0;
  11747. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11748. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11749. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11750. this.anisotropicFilteringLevel = 4;
  11751. this._scene = scene;
  11752. this._scene.textures.push(this);
  11753. }
  11754. BaseTexture.prototype.getScene = function () {
  11755. return this._scene;
  11756. };
  11757. BaseTexture.prototype.getTextureMatrix = function () {
  11758. return null;
  11759. };
  11760. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11761. return null;
  11762. };
  11763. BaseTexture.prototype.getInternalTexture = function () {
  11764. return this._texture;
  11765. };
  11766. BaseTexture.prototype.isReady = function () {
  11767. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11768. return true;
  11769. }
  11770. if (this._texture) {
  11771. return this._texture.isReady;
  11772. }
  11773. return false;
  11774. };
  11775. BaseTexture.prototype.getSize = function () {
  11776. if (this._texture._width) {
  11777. return { width: this._texture._width, height: this._texture._height };
  11778. }
  11779. if (this._texture._size) {
  11780. return { width: this._texture._size, height: this._texture._size };
  11781. }
  11782. return { width: 0, height: 0 };
  11783. };
  11784. BaseTexture.prototype.getBaseSize = function () {
  11785. if (!this.isReady())
  11786. return { width: 0, height: 0 };
  11787. if (this._texture._size) {
  11788. return { width: this._texture._size, height: this._texture._size };
  11789. }
  11790. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11791. };
  11792. BaseTexture.prototype.scale = function (ratio) {
  11793. };
  11794. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11795. get: function () {
  11796. return false;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11802. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11803. for (var index = 0; index < texturesCache.length; index++) {
  11804. var texturesCacheEntry = texturesCache[index];
  11805. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11806. texturesCache.splice(index, 1);
  11807. return;
  11808. }
  11809. }
  11810. };
  11811. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11812. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11813. for (var index = 0; index < texturesCache.length; index++) {
  11814. var texturesCacheEntry = texturesCache[index];
  11815. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11816. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11817. texturesCacheEntry.references++;
  11818. return texturesCacheEntry;
  11819. }
  11820. }
  11821. }
  11822. return null;
  11823. };
  11824. BaseTexture.prototype.delayLoad = function () {
  11825. };
  11826. BaseTexture.prototype.releaseInternalTexture = function () {
  11827. if (!this._texture) {
  11828. return;
  11829. }
  11830. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11831. this._texture.references--;
  11832. // Final reference ?
  11833. if (this._texture.references === 0) {
  11834. var index = texturesCache.indexOf(this._texture);
  11835. texturesCache.splice(index, 1);
  11836. this._scene.getEngine()._releaseTexture(this._texture);
  11837. delete this._texture;
  11838. }
  11839. };
  11840. BaseTexture.prototype.clone = function () {
  11841. return null;
  11842. };
  11843. BaseTexture.prototype.dispose = function () {
  11844. // Remove from scene
  11845. var index = this._scene.textures.indexOf(this);
  11846. if (index >= 0) {
  11847. this._scene.textures.splice(index, 1);
  11848. }
  11849. if (this._texture === undefined) {
  11850. return;
  11851. }
  11852. this.releaseInternalTexture();
  11853. // Callback
  11854. if (this.onDispose) {
  11855. this.onDispose();
  11856. }
  11857. };
  11858. return BaseTexture;
  11859. })();
  11860. BABYLON.BaseTexture = BaseTexture;
  11861. })(BABYLON || (BABYLON = {}));
  11862. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11863. (function (BABYLON) {
  11864. var RenderingGroup = (function () {
  11865. function RenderingGroup(index, scene) {
  11866. this.index = index;
  11867. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11868. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11869. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11870. this._scene = scene;
  11871. }
  11872. RenderingGroup.prototype.render = function (customRenderFunction) {
  11873. if (customRenderFunction) {
  11874. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11875. return true;
  11876. }
  11877. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11878. return false;
  11879. }
  11880. var engine = this._scene.getEngine();
  11881. // Opaque
  11882. var subIndex;
  11883. var submesh;
  11884. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11885. submesh = this._opaqueSubMeshes.data[subIndex];
  11886. submesh.render();
  11887. }
  11888. // Alpha test
  11889. engine.setAlphaTesting(true);
  11890. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11891. submesh = this._alphaTestSubMeshes.data[subIndex];
  11892. submesh.render();
  11893. }
  11894. engine.setAlphaTesting(false);
  11895. // Transparent
  11896. if (this._transparentSubMeshes.length) {
  11897. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11898. submesh = this._transparentSubMeshes.data[subIndex];
  11899. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11900. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11901. }
  11902. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11903. sortedArray.sort(function (a, b) {
  11904. // Alpha index first
  11905. if (a._alphaIndex > b._alphaIndex) {
  11906. return 1;
  11907. }
  11908. if (a._alphaIndex < b._alphaIndex) {
  11909. return -1;
  11910. }
  11911. // Then distance to camera
  11912. if (a._distanceToCamera < b._distanceToCamera) {
  11913. return 1;
  11914. }
  11915. if (a._distanceToCamera > b._distanceToCamera) {
  11916. return -1;
  11917. }
  11918. return 0;
  11919. });
  11920. // Rendering
  11921. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11922. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11923. submesh = sortedArray[subIndex];
  11924. submesh.render();
  11925. }
  11926. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11927. }
  11928. return true;
  11929. };
  11930. RenderingGroup.prototype.prepare = function () {
  11931. this._opaqueSubMeshes.reset();
  11932. this._transparentSubMeshes.reset();
  11933. this._alphaTestSubMeshes.reset();
  11934. };
  11935. RenderingGroup.prototype.dispatch = function (subMesh) {
  11936. var material = subMesh.getMaterial();
  11937. var mesh = subMesh.getMesh();
  11938. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11939. this._transparentSubMeshes.push(subMesh);
  11940. }
  11941. else if (material.needAlphaTesting()) {
  11942. this._alphaTestSubMeshes.push(subMesh);
  11943. }
  11944. else {
  11945. this._opaqueSubMeshes.push(subMesh); // Opaque
  11946. }
  11947. };
  11948. return RenderingGroup;
  11949. })();
  11950. BABYLON.RenderingGroup = RenderingGroup;
  11951. })(BABYLON || (BABYLON = {}));
  11952. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11953. (function (BABYLON) {
  11954. var RenderingManager = (function () {
  11955. function RenderingManager(scene) {
  11956. this._renderingGroups = new Array();
  11957. this._scene = scene;
  11958. }
  11959. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11960. if (this._scene._activeParticleSystems.length === 0) {
  11961. return;
  11962. }
  11963. // Particles
  11964. var beforeParticlesDate = BABYLON.Tools.Now;
  11965. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11966. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11967. if (particleSystem.renderingGroupId !== index) {
  11968. continue;
  11969. }
  11970. this._clearDepthBuffer();
  11971. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11972. this._scene._activeParticles += particleSystem.render();
  11973. }
  11974. }
  11975. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11976. };
  11977. RenderingManager.prototype._renderSprites = function (index) {
  11978. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11979. return;
  11980. }
  11981. // Sprites
  11982. var beforeSpritessDate = BABYLON.Tools.Now;
  11983. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11984. var spriteManager = this._scene.spriteManagers[id];
  11985. if (spriteManager.renderingGroupId === index) {
  11986. this._clearDepthBuffer();
  11987. spriteManager.render();
  11988. }
  11989. }
  11990. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11991. };
  11992. RenderingManager.prototype._clearDepthBuffer = function () {
  11993. if (this._depthBufferAlreadyCleaned) {
  11994. return;
  11995. }
  11996. this._scene.getEngine().clear(0, false, true);
  11997. this._depthBufferAlreadyCleaned = true;
  11998. };
  11999. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12000. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12001. this._depthBufferAlreadyCleaned = false;
  12002. var renderingGroup = this._renderingGroups[index];
  12003. var needToStepBack = false;
  12004. if (renderingGroup) {
  12005. this._clearDepthBuffer();
  12006. if (!renderingGroup.render(customRenderFunction)) {
  12007. this._renderingGroups.splice(index, 1);
  12008. needToStepBack = true;
  12009. }
  12010. }
  12011. if (renderSprites) {
  12012. this._renderSprites(index);
  12013. }
  12014. if (renderParticles) {
  12015. this._renderParticles(index, activeMeshes);
  12016. }
  12017. if (needToStepBack) {
  12018. index--;
  12019. }
  12020. }
  12021. };
  12022. RenderingManager.prototype.reset = function () {
  12023. for (var index in this._renderingGroups) {
  12024. var renderingGroup = this._renderingGroups[index];
  12025. renderingGroup.prepare();
  12026. }
  12027. };
  12028. RenderingManager.prototype.dispatch = function (subMesh) {
  12029. var mesh = subMesh.getMesh();
  12030. var renderingGroupId = mesh.renderingGroupId || 0;
  12031. if (!this._renderingGroups[renderingGroupId]) {
  12032. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12033. }
  12034. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12035. };
  12036. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12037. return RenderingManager;
  12038. })();
  12039. BABYLON.RenderingManager = RenderingManager;
  12040. })(BABYLON || (BABYLON = {}));
  12041. //# sourceMappingURL=babylon.renderingManager.js.map
  12042. var BABYLON;
  12043. (function (BABYLON) {
  12044. var Texture = (function (_super) {
  12045. __extends(Texture, _super);
  12046. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12047. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12048. if (onLoad === void 0) { onLoad = null; }
  12049. if (onError === void 0) { onError = null; }
  12050. if (buffer === void 0) { buffer = null; }
  12051. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12052. _super.call(this, scene);
  12053. this.uOffset = 0;
  12054. this.vOffset = 0;
  12055. this.uScale = 1.0;
  12056. this.vScale = 1.0;
  12057. this.uAng = 0;
  12058. this.vAng = 0;
  12059. this.wAng = 0;
  12060. this.name = url;
  12061. this.url = url;
  12062. this._noMipmap = noMipmap;
  12063. this._invertY = invertY;
  12064. this._samplingMode = samplingMode;
  12065. this._buffer = buffer;
  12066. this._deleteBuffer = deleteBuffer;
  12067. if (!url) {
  12068. return;
  12069. }
  12070. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12071. if (!this._texture) {
  12072. if (!scene.useDelayedTextureLoading) {
  12073. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12074. if (deleteBuffer) {
  12075. delete this._buffer;
  12076. }
  12077. }
  12078. else {
  12079. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12080. }
  12081. }
  12082. }
  12083. Texture.prototype.delayLoad = function () {
  12084. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12085. return;
  12086. }
  12087. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12088. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12089. if (!this._texture) {
  12090. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12091. if (this._deleteBuffer) {
  12092. delete this._buffer;
  12093. }
  12094. }
  12095. };
  12096. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12097. x -= this.uOffset + 0.5;
  12098. y -= this.vOffset + 0.5;
  12099. z -= 0.5;
  12100. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12101. t.x *= this.uScale;
  12102. t.y *= this.vScale;
  12103. t.x += 0.5;
  12104. t.y += 0.5;
  12105. t.z += 0.5;
  12106. };
  12107. Texture.prototype.getTextureMatrix = function () {
  12108. 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) {
  12109. return this._cachedTextureMatrix;
  12110. }
  12111. this._cachedUOffset = this.uOffset;
  12112. this._cachedVOffset = this.vOffset;
  12113. this._cachedUScale = this.uScale;
  12114. this._cachedVScale = this.vScale;
  12115. this._cachedUAng = this.uAng;
  12116. this._cachedVAng = this.vAng;
  12117. this._cachedWAng = this.wAng;
  12118. if (!this._cachedTextureMatrix) {
  12119. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12120. this._rowGenerationMatrix = new BABYLON.Matrix();
  12121. this._t0 = BABYLON.Vector3.Zero();
  12122. this._t1 = BABYLON.Vector3.Zero();
  12123. this._t2 = BABYLON.Vector3.Zero();
  12124. }
  12125. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12126. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12127. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12128. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12129. this._t1.subtractInPlace(this._t0);
  12130. this._t2.subtractInPlace(this._t0);
  12131. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12132. this._cachedTextureMatrix.m[0] = this._t1.x;
  12133. this._cachedTextureMatrix.m[1] = this._t1.y;
  12134. this._cachedTextureMatrix.m[2] = this._t1.z;
  12135. this._cachedTextureMatrix.m[4] = this._t2.x;
  12136. this._cachedTextureMatrix.m[5] = this._t2.y;
  12137. this._cachedTextureMatrix.m[6] = this._t2.z;
  12138. this._cachedTextureMatrix.m[8] = this._t0.x;
  12139. this._cachedTextureMatrix.m[9] = this._t0.y;
  12140. this._cachedTextureMatrix.m[10] = this._t0.z;
  12141. return this._cachedTextureMatrix;
  12142. };
  12143. Texture.prototype.getReflectionTextureMatrix = function () {
  12144. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12145. return this._cachedTextureMatrix;
  12146. }
  12147. if (!this._cachedTextureMatrix) {
  12148. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12149. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12150. }
  12151. this._cachedCoordinatesMode = this.coordinatesMode;
  12152. switch (this.coordinatesMode) {
  12153. case BABYLON.Texture.SPHERICAL_MODE:
  12154. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12155. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12156. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12157. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12158. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12159. break;
  12160. case BABYLON.Texture.PLANAR_MODE:
  12161. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12162. this._cachedTextureMatrix[0] = this.uScale;
  12163. this._cachedTextureMatrix[5] = this.vScale;
  12164. this._cachedTextureMatrix[12] = this.uOffset;
  12165. this._cachedTextureMatrix[13] = this.vOffset;
  12166. break;
  12167. case BABYLON.Texture.PROJECTION_MODE:
  12168. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12169. this._projectionModeMatrix.m[0] = 0.5;
  12170. this._projectionModeMatrix.m[5] = -0.5;
  12171. this._projectionModeMatrix.m[10] = 0.0;
  12172. this._projectionModeMatrix.m[12] = 0.5;
  12173. this._projectionModeMatrix.m[13] = 0.5;
  12174. this._projectionModeMatrix.m[14] = 1.0;
  12175. this._projectionModeMatrix.m[15] = 1.0;
  12176. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12177. break;
  12178. default:
  12179. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12180. break;
  12181. }
  12182. return this._cachedTextureMatrix;
  12183. };
  12184. Texture.prototype.clone = function () {
  12185. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12186. // Base texture
  12187. newTexture.hasAlpha = this.hasAlpha;
  12188. newTexture.level = this.level;
  12189. newTexture.wrapU = this.wrapU;
  12190. newTexture.wrapV = this.wrapV;
  12191. newTexture.coordinatesIndex = this.coordinatesIndex;
  12192. newTexture.coordinatesMode = this.coordinatesMode;
  12193. // Texture
  12194. newTexture.uOffset = this.uOffset;
  12195. newTexture.vOffset = this.vOffset;
  12196. newTexture.uScale = this.uScale;
  12197. newTexture.vScale = this.vScale;
  12198. newTexture.uAng = this.uAng;
  12199. newTexture.vAng = this.vAng;
  12200. newTexture.wAng = this.wAng;
  12201. return newTexture;
  12202. };
  12203. // Statics
  12204. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12205. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12206. if (onLoad === void 0) { onLoad = null; }
  12207. if (onError === void 0) { onError = null; }
  12208. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12209. };
  12210. // Constants
  12211. Texture.NEAREST_SAMPLINGMODE = 1;
  12212. Texture.BILINEAR_SAMPLINGMODE = 2;
  12213. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12214. Texture.EXPLICIT_MODE = 0;
  12215. Texture.SPHERICAL_MODE = 1;
  12216. Texture.PLANAR_MODE = 2;
  12217. Texture.CUBIC_MODE = 3;
  12218. Texture.PROJECTION_MODE = 4;
  12219. Texture.SKYBOX_MODE = 5;
  12220. Texture.CLAMP_ADDRESSMODE = 0;
  12221. Texture.WRAP_ADDRESSMODE = 1;
  12222. Texture.MIRROR_ADDRESSMODE = 2;
  12223. return Texture;
  12224. })(BABYLON.BaseTexture);
  12225. BABYLON.Texture = Texture;
  12226. })(BABYLON || (BABYLON = {}));
  12227. //# sourceMappingURL=babylon.texture.js.map
  12228. var BABYLON;
  12229. (function (BABYLON) {
  12230. var CubeTexture = (function (_super) {
  12231. __extends(CubeTexture, _super);
  12232. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12233. _super.call(this, scene);
  12234. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12235. this.name = rootUrl;
  12236. this.url = rootUrl;
  12237. this._noMipmap = noMipmap;
  12238. this.hasAlpha = false;
  12239. this._texture = this._getFromCache(rootUrl, noMipmap);
  12240. if (!extensions) {
  12241. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12242. }
  12243. this._extensions = extensions;
  12244. if (!this._texture) {
  12245. if (!scene.useDelayedTextureLoading) {
  12246. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12247. }
  12248. else {
  12249. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12250. }
  12251. }
  12252. this.isCube = true;
  12253. this._textureMatrix = BABYLON.Matrix.Identity();
  12254. }
  12255. CubeTexture.prototype.clone = function () {
  12256. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12257. // Base texture
  12258. newTexture.level = this.level;
  12259. newTexture.wrapU = this.wrapU;
  12260. newTexture.wrapV = this.wrapV;
  12261. newTexture.coordinatesIndex = this.coordinatesIndex;
  12262. newTexture.coordinatesMode = this.coordinatesMode;
  12263. return newTexture;
  12264. };
  12265. // Methods
  12266. CubeTexture.prototype.delayLoad = function () {
  12267. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12268. return;
  12269. }
  12270. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12271. this._texture = this._getFromCache(this.url, this._noMipmap);
  12272. if (!this._texture) {
  12273. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12274. }
  12275. };
  12276. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12277. return this._textureMatrix;
  12278. };
  12279. return CubeTexture;
  12280. })(BABYLON.BaseTexture);
  12281. BABYLON.CubeTexture = CubeTexture;
  12282. })(BABYLON || (BABYLON = {}));
  12283. //# sourceMappingURL=babylon.cubeTexture.js.map
  12284. var BABYLON;
  12285. (function (BABYLON) {
  12286. var RenderTargetTexture = (function (_super) {
  12287. __extends(RenderTargetTexture, _super);
  12288. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12289. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12290. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12291. _super.call(this, null, scene, !generateMipMaps);
  12292. this.renderList = new Array();
  12293. this.renderParticles = true;
  12294. this.renderSprites = false;
  12295. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12296. this._currentRefreshId = -1;
  12297. this._refreshRate = 1;
  12298. this.name = name;
  12299. this.isRenderTarget = true;
  12300. this._size = size;
  12301. this._generateMipMaps = generateMipMaps;
  12302. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12303. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12304. // Rendering groups
  12305. this._renderingManager = new BABYLON.RenderingManager(scene);
  12306. }
  12307. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12308. this._currentRefreshId = -1;
  12309. };
  12310. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12311. get: function () {
  12312. return this._refreshRate;
  12313. },
  12314. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12315. set: function (value) {
  12316. this._refreshRate = value;
  12317. this.resetRefreshCounter();
  12318. },
  12319. enumerable: true,
  12320. configurable: true
  12321. });
  12322. RenderTargetTexture.prototype._shouldRender = function () {
  12323. if (this._currentRefreshId === -1) {
  12324. this._currentRefreshId = 1;
  12325. return true;
  12326. }
  12327. if (this.refreshRate === this._currentRefreshId) {
  12328. this._currentRefreshId = 1;
  12329. return true;
  12330. }
  12331. this._currentRefreshId++;
  12332. return false;
  12333. };
  12334. RenderTargetTexture.prototype.isReady = function () {
  12335. if (!this.getScene().renderTargetsEnabled) {
  12336. return false;
  12337. }
  12338. return _super.prototype.isReady.call(this);
  12339. };
  12340. RenderTargetTexture.prototype.getRenderSize = function () {
  12341. return this._size;
  12342. };
  12343. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12344. get: function () {
  12345. return true;
  12346. },
  12347. enumerable: true,
  12348. configurable: true
  12349. });
  12350. RenderTargetTexture.prototype.scale = function (ratio) {
  12351. var newSize = this._size * ratio;
  12352. this.resize(newSize, this._generateMipMaps);
  12353. };
  12354. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12355. this.releaseInternalTexture();
  12356. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12357. };
  12358. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12359. var scene = this.getScene();
  12360. var engine = scene.getEngine();
  12361. if (this._waitingRenderList) {
  12362. this.renderList = [];
  12363. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12364. var id = this._waitingRenderList[index];
  12365. this.renderList.push(scene.getMeshByID(id));
  12366. }
  12367. delete this._waitingRenderList;
  12368. }
  12369. if (this.renderList && this.renderList.length === 0) {
  12370. return;
  12371. }
  12372. // Bind
  12373. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12374. engine.bindFramebuffer(this._texture);
  12375. }
  12376. this._renderingManager.reset();
  12377. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12378. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12379. var mesh = currentRenderList[meshIndex];
  12380. if (mesh) {
  12381. if (!mesh.isReady()) {
  12382. // Reset _currentRefreshId
  12383. this.resetRefreshCounter();
  12384. continue;
  12385. }
  12386. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12387. mesh._activate(scene.getRenderId());
  12388. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12389. var subMesh = mesh.subMeshes[subIndex];
  12390. scene._activeVertices += subMesh.indexCount;
  12391. this._renderingManager.dispatch(subMesh);
  12392. }
  12393. }
  12394. }
  12395. }
  12396. if (this.onBeforeRender) {
  12397. this.onBeforeRender();
  12398. }
  12399. // Clear
  12400. if (this.onClear) {
  12401. this.onClear(engine);
  12402. }
  12403. else {
  12404. engine.clear(scene.clearColor, true, true);
  12405. }
  12406. if (!this._doNotChangeAspectRatio) {
  12407. scene.updateTransformMatrix(true);
  12408. }
  12409. // Render
  12410. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12411. if (useCameraPostProcess) {
  12412. scene.postProcessManager._finalizeFrame(false, this._texture);
  12413. }
  12414. if (!this._doNotChangeAspectRatio) {
  12415. scene.updateTransformMatrix(true);
  12416. }
  12417. if (this.onAfterRender) {
  12418. this.onAfterRender();
  12419. }
  12420. // Dump ?
  12421. if (dumpForDebug) {
  12422. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12423. }
  12424. // Unbind
  12425. engine.unBindFramebuffer(this._texture);
  12426. if (this.onAfterUnbind) {
  12427. this.onAfterUnbind();
  12428. }
  12429. };
  12430. RenderTargetTexture.prototype.clone = function () {
  12431. var textureSize = this.getSize();
  12432. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12433. // Base texture
  12434. newTexture.hasAlpha = this.hasAlpha;
  12435. newTexture.level = this.level;
  12436. // RenderTarget Texture
  12437. newTexture.coordinatesMode = this.coordinatesMode;
  12438. newTexture.renderList = this.renderList.slice(0);
  12439. return newTexture;
  12440. };
  12441. return RenderTargetTexture;
  12442. })(BABYLON.Texture);
  12443. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12444. })(BABYLON || (BABYLON = {}));
  12445. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12446. var BABYLON;
  12447. (function (BABYLON) {
  12448. var ProceduralTexture = (function (_super) {
  12449. __extends(ProceduralTexture, _super);
  12450. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12451. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12452. _super.call(this, null, scene, !generateMipMaps);
  12453. this._currentRefreshId = -1;
  12454. this._refreshRate = 1;
  12455. this._vertexDeclaration = [2];
  12456. this._vertexStrideSize = 2 * 4;
  12457. this._uniforms = new Array();
  12458. this._samplers = new Array();
  12459. this._textures = new Array();
  12460. this._floats = new Array();
  12461. this._floatsArrays = {};
  12462. this._colors3 = new Array();
  12463. this._colors4 = new Array();
  12464. this._vectors2 = new Array();
  12465. this._vectors3 = new Array();
  12466. this._matrices = new Array();
  12467. this._fallbackTextureUsed = false;
  12468. scene._proceduralTextures.push(this);
  12469. this.name = name;
  12470. this.isRenderTarget = true;
  12471. this._size = size;
  12472. this._generateMipMaps = generateMipMaps;
  12473. this.setFragment(fragment);
  12474. this._fallbackTexture = fallbackTexture;
  12475. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12476. // VBO
  12477. var vertices = [];
  12478. vertices.push(1, 1);
  12479. vertices.push(-1, 1);
  12480. vertices.push(-1, -1);
  12481. vertices.push(1, -1);
  12482. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12483. // Indices
  12484. var indices = [];
  12485. indices.push(0);
  12486. indices.push(1);
  12487. indices.push(2);
  12488. indices.push(0);
  12489. indices.push(2);
  12490. indices.push(3);
  12491. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12492. }
  12493. ProceduralTexture.prototype.reset = function () {
  12494. if (this._effect === undefined) {
  12495. return;
  12496. }
  12497. var engine = this.getScene().getEngine();
  12498. engine._releaseEffect(this._effect);
  12499. };
  12500. ProceduralTexture.prototype.isReady = function () {
  12501. var _this = this;
  12502. var engine = this.getScene().getEngine();
  12503. var shaders;
  12504. if (!this._fragment) {
  12505. return false;
  12506. }
  12507. if (this._fallbackTextureUsed) {
  12508. return true;
  12509. }
  12510. if (this._fragment.fragmentElement !== undefined) {
  12511. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12512. }
  12513. else {
  12514. shaders = { vertex: "procedural", fragment: this._fragment };
  12515. }
  12516. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12517. _this.releaseInternalTexture();
  12518. if (_this._fallbackTexture) {
  12519. _this._texture = _this._fallbackTexture._texture;
  12520. _this._texture.references++;
  12521. }
  12522. _this._fallbackTextureUsed = true;
  12523. });
  12524. return this._effect.isReady();
  12525. };
  12526. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12527. this._currentRefreshId = -1;
  12528. };
  12529. ProceduralTexture.prototype.setFragment = function (fragment) {
  12530. this._fragment = fragment;
  12531. };
  12532. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12533. get: function () {
  12534. return this._refreshRate;
  12535. },
  12536. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12537. set: function (value) {
  12538. this._refreshRate = value;
  12539. this.resetRefreshCounter();
  12540. },
  12541. enumerable: true,
  12542. configurable: true
  12543. });
  12544. ProceduralTexture.prototype._shouldRender = function () {
  12545. if (!this.isReady() || !this._texture) {
  12546. return false;
  12547. }
  12548. if (this._fallbackTextureUsed) {
  12549. return false;
  12550. }
  12551. if (this._currentRefreshId === -1) {
  12552. this._currentRefreshId = 1;
  12553. return true;
  12554. }
  12555. if (this.refreshRate === this._currentRefreshId) {
  12556. this._currentRefreshId = 1;
  12557. return true;
  12558. }
  12559. this._currentRefreshId++;
  12560. return false;
  12561. };
  12562. ProceduralTexture.prototype.getRenderSize = function () {
  12563. return this._size;
  12564. };
  12565. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12566. if (this._fallbackTextureUsed) {
  12567. return;
  12568. }
  12569. this.releaseInternalTexture();
  12570. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12571. };
  12572. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12573. if (this._uniforms.indexOf(uniformName) === -1) {
  12574. this._uniforms.push(uniformName);
  12575. }
  12576. };
  12577. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12578. if (this._samplers.indexOf(name) === -1) {
  12579. this._samplers.push(name);
  12580. }
  12581. this._textures[name] = texture;
  12582. return this;
  12583. };
  12584. ProceduralTexture.prototype.setFloat = function (name, value) {
  12585. this._checkUniform(name);
  12586. this._floats[name] = value;
  12587. return this;
  12588. };
  12589. ProceduralTexture.prototype.setFloats = function (name, value) {
  12590. this._checkUniform(name);
  12591. this._floatsArrays[name] = value;
  12592. return this;
  12593. };
  12594. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12595. this._checkUniform(name);
  12596. this._colors3[name] = value;
  12597. return this;
  12598. };
  12599. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12600. this._checkUniform(name);
  12601. this._colors4[name] = value;
  12602. return this;
  12603. };
  12604. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12605. this._checkUniform(name);
  12606. this._vectors2[name] = value;
  12607. return this;
  12608. };
  12609. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12610. this._checkUniform(name);
  12611. this._vectors3[name] = value;
  12612. return this;
  12613. };
  12614. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12615. this._checkUniform(name);
  12616. this._matrices[name] = value;
  12617. return this;
  12618. };
  12619. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12620. var scene = this.getScene();
  12621. var engine = scene.getEngine();
  12622. engine.bindFramebuffer(this._texture);
  12623. // Clear
  12624. engine.clear(scene.clearColor, true, true);
  12625. // Render
  12626. engine.enableEffect(this._effect);
  12627. engine.setState(false);
  12628. for (var name in this._textures) {
  12629. this._effect.setTexture(name, this._textures[name]);
  12630. }
  12631. for (name in this._floats) {
  12632. this._effect.setFloat(name, this._floats[name]);
  12633. }
  12634. for (name in this._floatsArrays) {
  12635. this._effect.setArray(name, this._floatsArrays[name]);
  12636. }
  12637. for (name in this._colors3) {
  12638. this._effect.setColor3(name, this._colors3[name]);
  12639. }
  12640. for (name in this._colors4) {
  12641. var color = this._colors4[name];
  12642. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12643. }
  12644. for (name in this._vectors2) {
  12645. this._effect.setVector2(name, this._vectors2[name]);
  12646. }
  12647. for (name in this._vectors3) {
  12648. this._effect.setVector3(name, this._vectors3[name]);
  12649. }
  12650. for (name in this._matrices) {
  12651. this._effect.setMatrix(name, this._matrices[name]);
  12652. }
  12653. // VBOs
  12654. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12655. // Draw order
  12656. engine.draw(true, 0, 6);
  12657. // Unbind
  12658. engine.unBindFramebuffer(this._texture);
  12659. };
  12660. ProceduralTexture.prototype.clone = function () {
  12661. var textureSize = this.getSize();
  12662. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12663. // Base texture
  12664. newTexture.hasAlpha = this.hasAlpha;
  12665. newTexture.level = this.level;
  12666. // RenderTarget Texture
  12667. newTexture.coordinatesMode = this.coordinatesMode;
  12668. return newTexture;
  12669. };
  12670. ProceduralTexture.prototype.dispose = function () {
  12671. var index = this.getScene()._proceduralTextures.indexOf(this);
  12672. if (index >= 0) {
  12673. this.getScene()._proceduralTextures.splice(index, 1);
  12674. }
  12675. _super.prototype.dispose.call(this);
  12676. };
  12677. return ProceduralTexture;
  12678. })(BABYLON.Texture);
  12679. BABYLON.ProceduralTexture = ProceduralTexture;
  12680. })(BABYLON || (BABYLON = {}));
  12681. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12682. var BABYLON;
  12683. (function (BABYLON) {
  12684. var WoodProceduralTexture = (function (_super) {
  12685. __extends(WoodProceduralTexture, _super);
  12686. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12687. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12688. this._ampScale = 100.0;
  12689. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12690. this.updateShaderUniforms();
  12691. this.refreshRate = 0;
  12692. }
  12693. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12694. this.setFloat("ampScale", this._ampScale);
  12695. this.setColor3("woodColor", this._woodColor);
  12696. };
  12697. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12698. get: function () {
  12699. return this._ampScale;
  12700. },
  12701. set: function (value) {
  12702. this._ampScale = value;
  12703. this.updateShaderUniforms();
  12704. },
  12705. enumerable: true,
  12706. configurable: true
  12707. });
  12708. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12709. get: function () {
  12710. return this._woodColor;
  12711. },
  12712. set: function (value) {
  12713. this._woodColor = value;
  12714. this.updateShaderUniforms();
  12715. },
  12716. enumerable: true,
  12717. configurable: true
  12718. });
  12719. return WoodProceduralTexture;
  12720. })(BABYLON.ProceduralTexture);
  12721. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12722. var FireProceduralTexture = (function (_super) {
  12723. __extends(FireProceduralTexture, _super);
  12724. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12725. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12726. this._time = 0.0;
  12727. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12728. this._shift = 1.6;
  12729. this._autoGenerateTime = true;
  12730. this._alphaThreshold = 0.5;
  12731. this._fireColors = FireProceduralTexture.RedFireColors;
  12732. this.updateShaderUniforms();
  12733. this.refreshRate = 1;
  12734. }
  12735. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12736. this.setFloat("time", this._time);
  12737. this.setVector2("speed", this._speed);
  12738. this.setFloat("shift", this._shift);
  12739. this.setColor3("c1", this._fireColors[0]);
  12740. this.setColor3("c2", this._fireColors[1]);
  12741. this.setColor3("c3", this._fireColors[2]);
  12742. this.setColor3("c4", this._fireColors[3]);
  12743. this.setColor3("c5", this._fireColors[4]);
  12744. this.setColor3("c6", this._fireColors[5]);
  12745. this.setFloat("alphaThreshold", this._alphaThreshold);
  12746. };
  12747. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12748. if (this._autoGenerateTime) {
  12749. this._time += this.getScene().getAnimationRatio() * 0.03;
  12750. this.updateShaderUniforms();
  12751. }
  12752. _super.prototype.render.call(this, useCameraPostProcess);
  12753. };
  12754. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12755. get: function () {
  12756. return [
  12757. new BABYLON.Color3(0.5, 0.0, 1.0),
  12758. new BABYLON.Color3(0.9, 0.0, 1.0),
  12759. new BABYLON.Color3(0.2, 0.0, 1.0),
  12760. new BABYLON.Color3(1.0, 0.9, 1.0),
  12761. new BABYLON.Color3(0.1, 0.1, 1.0),
  12762. new BABYLON.Color3(0.9, 0.9, 1.0)
  12763. ];
  12764. },
  12765. enumerable: true,
  12766. configurable: true
  12767. });
  12768. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12769. get: function () {
  12770. return [
  12771. new BABYLON.Color3(0.5, 1.0, 0.0),
  12772. new BABYLON.Color3(0.5, 1.0, 0.0),
  12773. new BABYLON.Color3(0.3, 0.4, 0.0),
  12774. new BABYLON.Color3(0.5, 1.0, 0.0),
  12775. new BABYLON.Color3(0.2, 0.0, 0.0),
  12776. new BABYLON.Color3(0.5, 1.0, 0.0)
  12777. ];
  12778. },
  12779. enumerable: true,
  12780. configurable: true
  12781. });
  12782. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12783. get: function () {
  12784. return [
  12785. new BABYLON.Color3(0.5, 0.0, 0.1),
  12786. new BABYLON.Color3(0.9, 0.0, 0.0),
  12787. new BABYLON.Color3(0.2, 0.0, 0.0),
  12788. new BABYLON.Color3(1.0, 0.9, 0.0),
  12789. new BABYLON.Color3(0.1, 0.1, 0.1),
  12790. new BABYLON.Color3(0.9, 0.9, 0.9)
  12791. ];
  12792. },
  12793. enumerable: true,
  12794. configurable: true
  12795. });
  12796. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12797. get: function () {
  12798. return [
  12799. new BABYLON.Color3(0.1, 0.0, 0.5),
  12800. new BABYLON.Color3(0.0, 0.0, 0.5),
  12801. new BABYLON.Color3(0.1, 0.0, 0.2),
  12802. new BABYLON.Color3(0.0, 0.0, 1.0),
  12803. new BABYLON.Color3(0.1, 0.2, 0.3),
  12804. new BABYLON.Color3(0.0, 0.2, 0.9)
  12805. ];
  12806. },
  12807. enumerable: true,
  12808. configurable: true
  12809. });
  12810. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12811. get: function () {
  12812. return this._fireColors;
  12813. },
  12814. set: function (value) {
  12815. this._fireColors = value;
  12816. this.updateShaderUniforms();
  12817. },
  12818. enumerable: true,
  12819. configurable: true
  12820. });
  12821. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12822. get: function () {
  12823. return this._time;
  12824. },
  12825. set: function (value) {
  12826. this._time = value;
  12827. this.updateShaderUniforms();
  12828. },
  12829. enumerable: true,
  12830. configurable: true
  12831. });
  12832. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12833. get: function () {
  12834. return this._speed;
  12835. },
  12836. set: function (value) {
  12837. this._speed = value;
  12838. this.updateShaderUniforms();
  12839. },
  12840. enumerable: true,
  12841. configurable: true
  12842. });
  12843. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12844. get: function () {
  12845. return this._shift;
  12846. },
  12847. set: function (value) {
  12848. this._shift = value;
  12849. this.updateShaderUniforms();
  12850. },
  12851. enumerable: true,
  12852. configurable: true
  12853. });
  12854. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12855. get: function () {
  12856. return this._alphaThreshold;
  12857. },
  12858. set: function (value) {
  12859. this._alphaThreshold = value;
  12860. this.updateShaderUniforms();
  12861. },
  12862. enumerable: true,
  12863. configurable: true
  12864. });
  12865. return FireProceduralTexture;
  12866. })(BABYLON.ProceduralTexture);
  12867. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12868. var CloudProceduralTexture = (function (_super) {
  12869. __extends(CloudProceduralTexture, _super);
  12870. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12871. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12872. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12873. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12874. this.updateShaderUniforms();
  12875. this.refreshRate = 0;
  12876. }
  12877. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12878. this.setColor3("skyColor", this._skyColor);
  12879. this.setColor3("cloudColor", this._cloudColor);
  12880. };
  12881. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12882. get: function () {
  12883. return this._skyColor;
  12884. },
  12885. set: function (value) {
  12886. this._skyColor = value;
  12887. this.updateShaderUniforms();
  12888. },
  12889. enumerable: true,
  12890. configurable: true
  12891. });
  12892. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12893. get: function () {
  12894. return this._cloudColor;
  12895. },
  12896. set: function (value) {
  12897. this._cloudColor = value;
  12898. this.updateShaderUniforms();
  12899. },
  12900. enumerable: true,
  12901. configurable: true
  12902. });
  12903. return CloudProceduralTexture;
  12904. })(BABYLON.ProceduralTexture);
  12905. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12906. var GrassProceduralTexture = (function (_super) {
  12907. __extends(GrassProceduralTexture, _super);
  12908. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12909. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12910. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12911. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12912. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12913. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12914. this._grassColors = [
  12915. new BABYLON.Color3(0.29, 0.38, 0.02),
  12916. new BABYLON.Color3(0.36, 0.49, 0.09),
  12917. new BABYLON.Color3(0.51, 0.6, 0.28)
  12918. ];
  12919. this.updateShaderUniforms();
  12920. this.refreshRate = 0;
  12921. }
  12922. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12923. this.setColor3("herb1Color", this._grassColors[0]);
  12924. this.setColor3("herb2Color", this._grassColors[1]);
  12925. this.setColor3("herb3Color", this._grassColors[2]);
  12926. this.setColor3("groundColor", this._groundColor);
  12927. };
  12928. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12929. get: function () {
  12930. return this._grassColors;
  12931. },
  12932. set: function (value) {
  12933. this._grassColors = value;
  12934. this.updateShaderUniforms();
  12935. },
  12936. enumerable: true,
  12937. configurable: true
  12938. });
  12939. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12940. get: function () {
  12941. return this._groundColor;
  12942. },
  12943. set: function (value) {
  12944. this.groundColor = value;
  12945. this.updateShaderUniforms();
  12946. },
  12947. enumerable: true,
  12948. configurable: true
  12949. });
  12950. return GrassProceduralTexture;
  12951. })(BABYLON.ProceduralTexture);
  12952. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12953. var RoadProceduralTexture = (function (_super) {
  12954. __extends(RoadProceduralTexture, _super);
  12955. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12956. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12957. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12958. this.updateShaderUniforms();
  12959. this.refreshRate = 0;
  12960. }
  12961. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12962. this.setColor3("roadColor", this._roadColor);
  12963. };
  12964. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12965. get: function () {
  12966. return this._roadColor;
  12967. },
  12968. set: function (value) {
  12969. this._roadColor = value;
  12970. this.updateShaderUniforms();
  12971. },
  12972. enumerable: true,
  12973. configurable: true
  12974. });
  12975. return RoadProceduralTexture;
  12976. })(BABYLON.ProceduralTexture);
  12977. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12978. var BrickProceduralTexture = (function (_super) {
  12979. __extends(BrickProceduralTexture, _super);
  12980. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12981. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12982. this._numberOfBricksHeight = 15;
  12983. this._numberOfBricksWidth = 5;
  12984. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12985. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12986. this.updateShaderUniforms();
  12987. this.refreshRate = 0;
  12988. }
  12989. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12990. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12991. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12992. this.setColor3("brickColor", this._brickColor);
  12993. this.setColor3("jointColor", this._jointColor);
  12994. };
  12995. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12996. get: function () {
  12997. return this._numberOfBricksHeight;
  12998. },
  12999. enumerable: true,
  13000. configurable: true
  13001. });
  13002. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  13003. set: function (value) {
  13004. this._numberOfBricksHeight = value;
  13005. this.updateShaderUniforms();
  13006. },
  13007. enumerable: true,
  13008. configurable: true
  13009. });
  13010. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13011. get: function () {
  13012. return this._numberOfBricksWidth;
  13013. },
  13014. set: function (value) {
  13015. this._numberOfBricksHeight = value;
  13016. this.updateShaderUniforms();
  13017. },
  13018. enumerable: true,
  13019. configurable: true
  13020. });
  13021. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13022. get: function () {
  13023. return this._jointColor;
  13024. },
  13025. set: function (value) {
  13026. this._jointColor = value;
  13027. this.updateShaderUniforms();
  13028. },
  13029. enumerable: true,
  13030. configurable: true
  13031. });
  13032. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13033. get: function () {
  13034. return this._brickColor;
  13035. },
  13036. set: function (value) {
  13037. this._brickColor = value;
  13038. this.updateShaderUniforms();
  13039. },
  13040. enumerable: true,
  13041. configurable: true
  13042. });
  13043. return BrickProceduralTexture;
  13044. })(BABYLON.ProceduralTexture);
  13045. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13046. var MarbleProceduralTexture = (function (_super) {
  13047. __extends(MarbleProceduralTexture, _super);
  13048. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13049. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13050. this._numberOfTilesHeight = 3;
  13051. this._numberOfTilesWidth = 3;
  13052. this._amplitude = 9.0;
  13053. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13054. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13055. this.updateShaderUniforms();
  13056. this.refreshRate = 0;
  13057. }
  13058. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13059. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13060. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13061. this.setFloat("amplitude", this._amplitude);
  13062. this.setColor3("marbleColor", this._marbleColor);
  13063. this.setColor3("jointColor", this._jointColor);
  13064. };
  13065. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13066. get: function () {
  13067. return this._numberOfTilesHeight;
  13068. },
  13069. set: function (value) {
  13070. this._numberOfTilesHeight = value;
  13071. this.updateShaderUniforms();
  13072. },
  13073. enumerable: true,
  13074. configurable: true
  13075. });
  13076. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13077. get: function () {
  13078. return this._numberOfTilesWidth;
  13079. },
  13080. set: function (value) {
  13081. this._numberOfTilesWidth = value;
  13082. this.updateShaderUniforms();
  13083. },
  13084. enumerable: true,
  13085. configurable: true
  13086. });
  13087. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13088. get: function () {
  13089. return this._jointColor;
  13090. },
  13091. set: function (value) {
  13092. this._jointColor = value;
  13093. this.updateShaderUniforms();
  13094. },
  13095. enumerable: true,
  13096. configurable: true
  13097. });
  13098. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13099. get: function () {
  13100. return this._marbleColor;
  13101. },
  13102. set: function (value) {
  13103. this._marbleColor = value;
  13104. this.updateShaderUniforms();
  13105. },
  13106. enumerable: true,
  13107. configurable: true
  13108. });
  13109. return MarbleProceduralTexture;
  13110. })(BABYLON.ProceduralTexture);
  13111. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13112. })(BABYLON || (BABYLON = {}));
  13113. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13114. var BABYLON;
  13115. (function (BABYLON) {
  13116. var CustomProceduralTexture = (function (_super) {
  13117. __extends(CustomProceduralTexture, _super);
  13118. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13119. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13120. this._animate = true;
  13121. this._time = 0;
  13122. this._texturePath = texturePath;
  13123. //Try to load json
  13124. this.loadJson(texturePath);
  13125. this.refreshRate = 1;
  13126. }
  13127. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13128. var _this = this;
  13129. var that = this;
  13130. function noConfigFile() {
  13131. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13132. try {
  13133. that.setFragment(that._texturePath);
  13134. }
  13135. catch (ex) {
  13136. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13137. }
  13138. }
  13139. var configFileUrl = jsonUrl + "/config.json";
  13140. var xhr = new XMLHttpRequest();
  13141. xhr.open("GET", configFileUrl, true);
  13142. xhr.addEventListener("load", function () {
  13143. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13144. try {
  13145. _this._config = JSON.parse(xhr.response);
  13146. _this.updateShaderUniforms();
  13147. _this.updateTextures();
  13148. _this.setFragment(_this._texturePath + "/custom");
  13149. _this._animate = _this._config.animate;
  13150. _this.refreshRate = _this._config.refreshrate;
  13151. }
  13152. catch (ex) {
  13153. noConfigFile();
  13154. }
  13155. }
  13156. else {
  13157. noConfigFile();
  13158. }
  13159. }, false);
  13160. xhr.addEventListener("error", function () {
  13161. noConfigFile();
  13162. }, false);
  13163. try {
  13164. xhr.send();
  13165. }
  13166. catch (ex) {
  13167. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13168. }
  13169. };
  13170. CustomProceduralTexture.prototype.isReady = function () {
  13171. if (!_super.prototype.isReady.call(this)) {
  13172. return false;
  13173. }
  13174. for (var name in this._textures) {
  13175. var texture = this._textures[name];
  13176. if (!texture.isReady()) {
  13177. return false;
  13178. }
  13179. }
  13180. return true;
  13181. };
  13182. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13183. if (this._animate) {
  13184. this._time += this.getScene().getAnimationRatio() * 0.03;
  13185. this.updateShaderUniforms();
  13186. }
  13187. _super.prototype.render.call(this, useCameraPostProcess);
  13188. };
  13189. CustomProceduralTexture.prototype.updateTextures = function () {
  13190. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13191. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13192. }
  13193. };
  13194. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13195. if (this._config) {
  13196. for (var j = 0; j < this._config.uniforms.length; j++) {
  13197. var uniform = this._config.uniforms[j];
  13198. switch (uniform.type) {
  13199. case "float":
  13200. this.setFloat(uniform.name, uniform.value);
  13201. break;
  13202. case "color3":
  13203. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13204. break;
  13205. case "color4":
  13206. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13207. break;
  13208. case "vector2":
  13209. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13210. break;
  13211. case "vector3":
  13212. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13213. break;
  13214. }
  13215. }
  13216. }
  13217. this.setFloat("time", this._time);
  13218. };
  13219. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13220. get: function () {
  13221. return this._animate;
  13222. },
  13223. set: function (value) {
  13224. this._animate = value;
  13225. },
  13226. enumerable: true,
  13227. configurable: true
  13228. });
  13229. return CustomProceduralTexture;
  13230. })(BABYLON.ProceduralTexture);
  13231. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13232. })(BABYLON || (BABYLON = {}));
  13233. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13234. var BABYLON;
  13235. (function (BABYLON) {
  13236. var MirrorTexture = (function (_super) {
  13237. __extends(MirrorTexture, _super);
  13238. function MirrorTexture(name, size, scene, generateMipMaps) {
  13239. var _this = this;
  13240. _super.call(this, name, size, scene, generateMipMaps, true);
  13241. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13242. this._transformMatrix = BABYLON.Matrix.Zero();
  13243. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13244. this.onBeforeRender = function () {
  13245. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13246. _this._savedViewMatrix = scene.getViewMatrix();
  13247. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13248. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13249. scene.clipPlane = _this.mirrorPlane;
  13250. scene.getEngine().cullBackFaces = false;
  13251. };
  13252. this.onAfterRender = function () {
  13253. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13254. scene.getEngine().cullBackFaces = true;
  13255. delete scene.clipPlane;
  13256. };
  13257. }
  13258. MirrorTexture.prototype.clone = function () {
  13259. var textureSize = this.getSize();
  13260. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13261. // Base texture
  13262. newTexture.hasAlpha = this.hasAlpha;
  13263. newTexture.level = this.level;
  13264. // Mirror Texture
  13265. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13266. newTexture.renderList = this.renderList.slice(0);
  13267. return newTexture;
  13268. };
  13269. return MirrorTexture;
  13270. })(BABYLON.RenderTargetTexture);
  13271. BABYLON.MirrorTexture = MirrorTexture;
  13272. })(BABYLON || (BABYLON = {}));
  13273. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13274. var BABYLON;
  13275. (function (BABYLON) {
  13276. var DynamicTexture = (function (_super) {
  13277. __extends(DynamicTexture, _super);
  13278. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13280. _super.call(this, null, scene, !generateMipMaps);
  13281. this.name = name;
  13282. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13283. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13284. this._generateMipMaps = generateMipMaps;
  13285. if (options.getContext) {
  13286. this._canvas = options;
  13287. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13288. }
  13289. else {
  13290. this._canvas = document.createElement("canvas");
  13291. if (options.width) {
  13292. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13293. }
  13294. else {
  13295. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13296. }
  13297. }
  13298. var textureSize = this.getSize();
  13299. this._canvas.width = textureSize.width;
  13300. this._canvas.height = textureSize.height;
  13301. this._context = this._canvas.getContext("2d");
  13302. }
  13303. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13304. get: function () {
  13305. return true;
  13306. },
  13307. enumerable: true,
  13308. configurable: true
  13309. });
  13310. DynamicTexture.prototype.scale = function (ratio) {
  13311. var textureSize = this.getSize();
  13312. textureSize.width *= ratio;
  13313. textureSize.height *= ratio;
  13314. this._canvas.width = textureSize.width;
  13315. this._canvas.height = textureSize.height;
  13316. this.releaseInternalTexture();
  13317. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13318. };
  13319. DynamicTexture.prototype.getContext = function () {
  13320. return this._context;
  13321. };
  13322. DynamicTexture.prototype.clear = function () {
  13323. var size = this.getSize();
  13324. this._context.fillRect(0, 0, size.width, size.height);
  13325. };
  13326. DynamicTexture.prototype.update = function (invertY) {
  13327. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13328. };
  13329. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13330. if (update === void 0) { update = true; }
  13331. var size = this.getSize();
  13332. if (clearColor) {
  13333. this._context.fillStyle = clearColor;
  13334. this._context.fillRect(0, 0, size.width, size.height);
  13335. }
  13336. this._context.font = font;
  13337. if (x === null) {
  13338. var textSize = this._context.measureText(text);
  13339. x = (size.width - textSize.width) / 2;
  13340. }
  13341. this._context.fillStyle = color;
  13342. this._context.fillText(text, x, y);
  13343. if (update) {
  13344. this.update(invertY);
  13345. }
  13346. };
  13347. DynamicTexture.prototype.clone = function () {
  13348. var textureSize = this.getSize();
  13349. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13350. // Base texture
  13351. newTexture.hasAlpha = this.hasAlpha;
  13352. newTexture.level = this.level;
  13353. // Dynamic Texture
  13354. newTexture.wrapU = this.wrapU;
  13355. newTexture.wrapV = this.wrapV;
  13356. return newTexture;
  13357. };
  13358. return DynamicTexture;
  13359. })(BABYLON.Texture);
  13360. BABYLON.DynamicTexture = DynamicTexture;
  13361. })(BABYLON || (BABYLON = {}));
  13362. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13363. var BABYLON;
  13364. (function (BABYLON) {
  13365. var VideoTexture = (function (_super) {
  13366. __extends(VideoTexture, _super);
  13367. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13368. var _this = this;
  13369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13370. _super.call(this, null, scene, !generateMipMaps, invertY);
  13371. this._autoLaunch = true;
  13372. this.name = name;
  13373. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13374. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13375. var requiredWidth = size.width || size;
  13376. var requiredHeight = size.height || size;
  13377. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13378. var textureSize = this.getSize();
  13379. this.video = document.createElement("video");
  13380. this.video.width = textureSize.width;
  13381. this.video.height = textureSize.height;
  13382. this.video.autoplay = false;
  13383. this.video.loop = true;
  13384. this.video.addEventListener("canplaythrough", function () {
  13385. if (_this._texture) {
  13386. _this._texture.isReady = true;
  13387. }
  13388. });
  13389. urls.forEach(function (url) {
  13390. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13391. var source = document.createElement("source");
  13392. source.src = url;
  13393. _this.video.appendChild(source);
  13394. });
  13395. this._lastUpdate = BABYLON.Tools.Now;
  13396. }
  13397. VideoTexture.prototype.update = function () {
  13398. if (this._autoLaunch) {
  13399. this._autoLaunch = false;
  13400. this.video.play();
  13401. }
  13402. var now = BABYLON.Tools.Now;
  13403. if (now - this._lastUpdate < 15) {
  13404. return false;
  13405. }
  13406. this._lastUpdate = now;
  13407. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13408. return true;
  13409. };
  13410. return VideoTexture;
  13411. })(BABYLON.Texture);
  13412. BABYLON.VideoTexture = VideoTexture;
  13413. })(BABYLON || (BABYLON = {}));
  13414. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13415. (function (BABYLON) {
  13416. var EffectFallbacks = (function () {
  13417. function EffectFallbacks() {
  13418. this._defines = {};
  13419. this._currentRank = 32;
  13420. this._maxRank = -1;
  13421. }
  13422. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13423. if (!this._defines[rank]) {
  13424. if (rank < this._currentRank) {
  13425. this._currentRank = rank;
  13426. }
  13427. if (rank > this._maxRank) {
  13428. this._maxRank = rank;
  13429. }
  13430. this._defines[rank] = new Array();
  13431. }
  13432. this._defines[rank].push(define);
  13433. };
  13434. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13435. get: function () {
  13436. return this._currentRank <= this._maxRank;
  13437. },
  13438. enumerable: true,
  13439. configurable: true
  13440. });
  13441. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13442. var currentFallbacks = this._defines[this._currentRank];
  13443. for (var index = 0; index < currentFallbacks.length; index++) {
  13444. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13445. }
  13446. this._currentRank++;
  13447. return currentDefines;
  13448. };
  13449. return EffectFallbacks;
  13450. })();
  13451. BABYLON.EffectFallbacks = EffectFallbacks;
  13452. var Effect = (function () {
  13453. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13454. var _this = this;
  13455. this._isReady = false;
  13456. this._compilationError = "";
  13457. this._valueCache = [];
  13458. this._engine = engine;
  13459. this.name = baseName;
  13460. this.defines = defines;
  13461. this._uniformsNames = uniformsNames.concat(samplers);
  13462. this._samplers = samplers;
  13463. this._attributesNames = attributesNames;
  13464. this.onError = onError;
  13465. this.onCompiled = onCompiled;
  13466. var vertexSource;
  13467. var fragmentSource;
  13468. if (baseName.vertexElement) {
  13469. vertexSource = document.getElementById(baseName.vertexElement);
  13470. if (!vertexSource) {
  13471. vertexSource = baseName.vertexElement;
  13472. }
  13473. }
  13474. else {
  13475. vertexSource = baseName.vertex || baseName;
  13476. }
  13477. if (baseName.fragmentElement) {
  13478. fragmentSource = document.getElementById(baseName.fragmentElement);
  13479. if (!fragmentSource) {
  13480. fragmentSource = baseName.fragmentElement;
  13481. }
  13482. }
  13483. else {
  13484. fragmentSource = baseName.fragment || baseName;
  13485. }
  13486. this._loadVertexShader(vertexSource, function (vertexCode) {
  13487. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13488. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13489. });
  13490. });
  13491. }
  13492. // Properties
  13493. Effect.prototype.isReady = function () {
  13494. return this._isReady;
  13495. };
  13496. Effect.prototype.getProgram = function () {
  13497. return this._program;
  13498. };
  13499. Effect.prototype.getAttributesNames = function () {
  13500. return this._attributesNames;
  13501. };
  13502. Effect.prototype.getAttributeLocation = function (index) {
  13503. return this._attributes[index];
  13504. };
  13505. Effect.prototype.getAttributeLocationByName = function (name) {
  13506. var index = this._attributesNames.indexOf(name);
  13507. return this._attributes[index];
  13508. };
  13509. Effect.prototype.getAttributesCount = function () {
  13510. return this._attributes.length;
  13511. };
  13512. Effect.prototype.getUniformIndex = function (uniformName) {
  13513. return this._uniformsNames.indexOf(uniformName);
  13514. };
  13515. Effect.prototype.getUniform = function (uniformName) {
  13516. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13517. };
  13518. Effect.prototype.getSamplers = function () {
  13519. return this._samplers;
  13520. };
  13521. Effect.prototype.getCompilationError = function () {
  13522. return this._compilationError;
  13523. };
  13524. // Methods
  13525. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13526. // DOM element ?
  13527. if (vertex instanceof HTMLElement) {
  13528. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13529. callback(vertexCode);
  13530. return;
  13531. }
  13532. // Is in local store ?
  13533. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13534. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13535. return;
  13536. }
  13537. var vertexShaderUrl;
  13538. if (vertex[0] === ".") {
  13539. vertexShaderUrl = vertex;
  13540. }
  13541. else {
  13542. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13543. }
  13544. // Vertex shader
  13545. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13546. };
  13547. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13548. // DOM element ?
  13549. if (fragment instanceof HTMLElement) {
  13550. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13551. callback(fragmentCode);
  13552. return;
  13553. }
  13554. // Is in local store ?
  13555. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13556. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13557. return;
  13558. }
  13559. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13560. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13561. return;
  13562. }
  13563. var fragmentShaderUrl;
  13564. if (fragment[0] === ".") {
  13565. fragmentShaderUrl = fragment;
  13566. }
  13567. else {
  13568. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13569. }
  13570. // Fragment shader
  13571. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13572. };
  13573. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13574. try {
  13575. var engine = this._engine;
  13576. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13577. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13578. this._attributes = engine.getAttributes(this._program, attributesNames);
  13579. for (var index = 0; index < this._samplers.length; index++) {
  13580. var sampler = this.getUniform(this._samplers[index]);
  13581. if (sampler == null) {
  13582. this._samplers.splice(index, 1);
  13583. index--;
  13584. }
  13585. }
  13586. engine.bindSamplers(this);
  13587. this._isReady = true;
  13588. if (this.onCompiled) {
  13589. this.onCompiled(this);
  13590. }
  13591. }
  13592. catch (e) {
  13593. // Is it a problem with precision?
  13594. if (e.message.indexOf("highp") !== -1) {
  13595. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13596. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13597. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13598. return;
  13599. }
  13600. // Let's go through fallbacks then
  13601. if (fallbacks && fallbacks.isMoreFallbacks) {
  13602. defines = fallbacks.reduce(defines);
  13603. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13604. }
  13605. else {
  13606. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13607. BABYLON.Tools.Error("Defines: " + defines);
  13608. BABYLON.Tools.Error("Error: " + e.message);
  13609. this._compilationError = e.message;
  13610. if (this.onError) {
  13611. this.onError(this, this._compilationError);
  13612. }
  13613. }
  13614. }
  13615. };
  13616. Effect.prototype._bindTexture = function (channel, texture) {
  13617. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13618. };
  13619. Effect.prototype.setTexture = function (channel, texture) {
  13620. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13621. };
  13622. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13623. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13624. };
  13625. //public _cacheMatrix(uniformName, matrix) {
  13626. // if (!this._valueCache[uniformName]) {
  13627. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13628. // }
  13629. // for (var index = 0; index < 16; index++) {
  13630. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13631. // }
  13632. //};
  13633. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13634. if (!this._valueCache[uniformName]) {
  13635. this._valueCache[uniformName] = [x, y];
  13636. return;
  13637. }
  13638. this._valueCache[uniformName][0] = x;
  13639. this._valueCache[uniformName][1] = y;
  13640. };
  13641. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13642. if (!this._valueCache[uniformName]) {
  13643. this._valueCache[uniformName] = [x, y, z];
  13644. return;
  13645. }
  13646. this._valueCache[uniformName][0] = x;
  13647. this._valueCache[uniformName][1] = y;
  13648. this._valueCache[uniformName][2] = z;
  13649. };
  13650. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13651. if (!this._valueCache[uniformName]) {
  13652. this._valueCache[uniformName] = [x, y, z, w];
  13653. return;
  13654. }
  13655. this._valueCache[uniformName][0] = x;
  13656. this._valueCache[uniformName][1] = y;
  13657. this._valueCache[uniformName][2] = z;
  13658. this._valueCache[uniformName][3] = w;
  13659. };
  13660. Effect.prototype.setArray = function (uniformName, array) {
  13661. this._engine.setArray(this.getUniform(uniformName), array);
  13662. return this;
  13663. };
  13664. Effect.prototype.setArray2 = function (uniformName, array) {
  13665. this._engine.setArray2(this.getUniform(uniformName), array);
  13666. return this;
  13667. };
  13668. Effect.prototype.setArray3 = function (uniformName, array) {
  13669. this._engine.setArray3(this.getUniform(uniformName), array);
  13670. return this;
  13671. };
  13672. Effect.prototype.setArray4 = function (uniformName, array) {
  13673. this._engine.setArray4(this.getUniform(uniformName), array);
  13674. return this;
  13675. };
  13676. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13677. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13678. return this;
  13679. };
  13680. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13681. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13682. // return;
  13683. //this._cacheMatrix(uniformName, matrix);
  13684. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13685. return this;
  13686. };
  13687. Effect.prototype.setFloat = function (uniformName, value) {
  13688. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13689. return this;
  13690. this._valueCache[uniformName] = value;
  13691. this._engine.setFloat(this.getUniform(uniformName), value);
  13692. return this;
  13693. };
  13694. Effect.prototype.setBool = function (uniformName, bool) {
  13695. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13696. return this;
  13697. this._valueCache[uniformName] = bool;
  13698. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13699. return this;
  13700. };
  13701. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13702. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13703. return this;
  13704. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13705. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13706. return this;
  13707. };
  13708. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13709. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13710. return this;
  13711. this._cacheFloat2(uniformName, x, y);
  13712. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13713. return this;
  13714. };
  13715. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13716. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13717. return this;
  13718. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13719. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13720. return this;
  13721. };
  13722. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13723. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13724. return this;
  13725. this._cacheFloat3(uniformName, x, y, z);
  13726. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13727. return this;
  13728. };
  13729. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13730. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13731. return this;
  13732. this._cacheFloat4(uniformName, x, y, z, w);
  13733. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13734. return this;
  13735. };
  13736. Effect.prototype.setColor3 = function (uniformName, color3) {
  13737. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13738. return this;
  13739. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13740. this._engine.setColor3(this.getUniform(uniformName), color3);
  13741. return this;
  13742. };
  13743. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13744. 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)
  13745. return this;
  13746. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13747. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13748. return this;
  13749. };
  13750. // Statics
  13751. 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}",
  13752. 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}",
  13753. 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}",
  13754. 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}",
  13755. 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}",
  13756. 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}",
  13757. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13758. 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}",
  13759. 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}",
  13760. 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 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)) + 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 vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) + bias < depth.z) visibility -= 0.25;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t, float bias)\n{\n 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.02 + bias);\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 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 || 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}",
  13761. 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}",
  13762. 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}",
  13763. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13764. 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}",
  13765. 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}",
  13766. 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}",
  13767. 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}",
  13768. 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}",
  13769. 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}",
  13770. 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}",
  13771. 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}",
  13772. 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}",
  13773. 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}",
  13774. 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}",
  13775. 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}",
  13776. 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}",
  13777. 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}",
  13778. 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}",
  13779. 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}",
  13780. 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}",
  13781. 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}",
  13782. 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}",
  13783. 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}",
  13784. 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}",
  13785. 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}",
  13786. 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}",
  13787. 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}",
  13788. 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\n#ifdef VSM\n float depth = vPosition.z / vPosition.w;\n\n float moment1 = depth;\n float moment2 = moment1 * moment1;\n\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  13789. 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}",
  13790. 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}",
  13791. 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}",
  13792. 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}",
  13793. 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}",
  13794. 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}",
  13795. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(OPACITY) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef BASIC_RENDER\n#ifdef OPACITY\n gl_FragColor = diffuseColor * texture2D(opacitySampler, vUV);\n#else\n gl_FragColor = diffuseColor;\n#endif\n#else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\n\n}",
  13796. 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}",
  13797. };
  13798. return Effect;
  13799. })();
  13800. BABYLON.Effect = Effect;
  13801. })(BABYLON || (BABYLON = {}));
  13802. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13803. (function (BABYLON) {
  13804. var Material = (function () {
  13805. function Material(name, scene, doNotAdd) {
  13806. this.name = name;
  13807. this.checkReadyOnEveryCall = true;
  13808. this.checkReadyOnlyOnce = false;
  13809. this.state = "";
  13810. this.alpha = 1.0;
  13811. this.backFaceCulling = true;
  13812. this._wasPreviouslyReady = false;
  13813. this._fillMode = Material.TriangleFillMode;
  13814. this.pointSize = 1.0;
  13815. this.id = name;
  13816. this._scene = scene;
  13817. if (!doNotAdd) {
  13818. scene.materials.push(this);
  13819. }
  13820. }
  13821. Object.defineProperty(Material, "TriangleFillMode", {
  13822. get: function () {
  13823. return Material._TriangleFillMode;
  13824. },
  13825. enumerable: true,
  13826. configurable: true
  13827. });
  13828. Object.defineProperty(Material, "WireFrameFillMode", {
  13829. get: function () {
  13830. return Material._WireFrameFillMode;
  13831. },
  13832. enumerable: true,
  13833. configurable: true
  13834. });
  13835. Object.defineProperty(Material, "PointFillMode", {
  13836. get: function () {
  13837. return Material._PointFillMode;
  13838. },
  13839. enumerable: true,
  13840. configurable: true
  13841. });
  13842. Object.defineProperty(Material.prototype, "wireframe", {
  13843. get: function () {
  13844. return this._fillMode === Material.WireFrameFillMode;
  13845. },
  13846. set: function (value) {
  13847. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13848. },
  13849. enumerable: true,
  13850. configurable: true
  13851. });
  13852. Object.defineProperty(Material.prototype, "pointsCloud", {
  13853. get: function () {
  13854. return this._fillMode === Material.PointFillMode;
  13855. },
  13856. set: function (value) {
  13857. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13858. },
  13859. enumerable: true,
  13860. configurable: true
  13861. });
  13862. Object.defineProperty(Material.prototype, "fillMode", {
  13863. get: function () {
  13864. return this._fillMode;
  13865. },
  13866. set: function (value) {
  13867. this._fillMode = value;
  13868. },
  13869. enumerable: true,
  13870. configurable: true
  13871. });
  13872. Material.prototype.isReady = function (mesh, useInstances) {
  13873. return true;
  13874. };
  13875. Material.prototype.getEffect = function () {
  13876. return this._effect;
  13877. };
  13878. Material.prototype.getScene = function () {
  13879. return this._scene;
  13880. };
  13881. Material.prototype.needAlphaBlending = function () {
  13882. return (this.alpha < 1.0);
  13883. };
  13884. Material.prototype.needAlphaTesting = function () {
  13885. return false;
  13886. };
  13887. Material.prototype.getAlphaTestTexture = function () {
  13888. return null;
  13889. };
  13890. Material.prototype.trackCreation = function (onCompiled, onError) {
  13891. };
  13892. Material.prototype._preBind = function () {
  13893. var engine = this._scene.getEngine();
  13894. engine.enableEffect(this._effect);
  13895. engine.setState(this.backFaceCulling);
  13896. };
  13897. Material.prototype.bind = function (world, mesh) {
  13898. this._scene._cachedMaterial = this;
  13899. if (this.onBind) {
  13900. this.onBind(this);
  13901. }
  13902. };
  13903. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13904. };
  13905. Material.prototype.unbind = function () {
  13906. };
  13907. Material.prototype.dispose = function (forceDisposeEffect) {
  13908. // Remove from scene
  13909. var index = this._scene.materials.indexOf(this);
  13910. this._scene.materials.splice(index, 1);
  13911. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13912. if (forceDisposeEffect && this._effect) {
  13913. this._scene.getEngine()._releaseEffect(this._effect);
  13914. this._effect = null;
  13915. }
  13916. // Callback
  13917. if (this.onDispose) {
  13918. this.onDispose();
  13919. }
  13920. };
  13921. Material._TriangleFillMode = 0;
  13922. Material._WireFrameFillMode = 1;
  13923. Material._PointFillMode = 2;
  13924. return Material;
  13925. })();
  13926. BABYLON.Material = Material;
  13927. })(BABYLON || (BABYLON = {}));
  13928. //# sourceMappingURL=babylon.material.js.map
  13929. var BABYLON;
  13930. (function (BABYLON) {
  13931. var maxSimultaneousLights = 4;
  13932. var FresnelParameters = (function () {
  13933. function FresnelParameters() {
  13934. this.isEnabled = true;
  13935. this.leftColor = BABYLON.Color3.White();
  13936. this.rightColor = BABYLON.Color3.Black();
  13937. this.bias = 0;
  13938. this.power = 1;
  13939. }
  13940. return FresnelParameters;
  13941. })();
  13942. BABYLON.FresnelParameters = FresnelParameters;
  13943. var StandardMaterial = (function (_super) {
  13944. __extends(StandardMaterial, _super);
  13945. function StandardMaterial(name, scene) {
  13946. var _this = this;
  13947. _super.call(this, name, scene);
  13948. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13949. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13950. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13951. this.specularPower = 64;
  13952. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13953. this.useAlphaFromDiffuseTexture = false;
  13954. this.useSpecularOverAlpha = true;
  13955. this.fogEnabled = true;
  13956. this._cachedDefines = null;
  13957. this._renderTargets = new BABYLON.SmartArray(16);
  13958. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13959. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13960. this._scaledDiffuse = new BABYLON.Color3();
  13961. this._scaledSpecular = new BABYLON.Color3();
  13962. this.getRenderTargetTextures = function () {
  13963. _this._renderTargets.reset();
  13964. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13965. _this._renderTargets.push(_this.reflectionTexture);
  13966. }
  13967. return _this._renderTargets;
  13968. };
  13969. }
  13970. StandardMaterial.prototype.needAlphaBlending = function () {
  13971. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13972. };
  13973. StandardMaterial.prototype.needAlphaTesting = function () {
  13974. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13975. };
  13976. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13977. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13978. };
  13979. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13980. return this.diffuseTexture;
  13981. };
  13982. // Methods
  13983. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13984. if (this.checkReadyOnlyOnce) {
  13985. if (this._wasPreviouslyReady) {
  13986. return true;
  13987. }
  13988. }
  13989. var scene = this.getScene();
  13990. if (!this.checkReadyOnEveryCall) {
  13991. if (this._renderId === scene.getRenderId()) {
  13992. return true;
  13993. }
  13994. }
  13995. var engine = scene.getEngine();
  13996. var defines = [];
  13997. var fallbacks = new BABYLON.EffectFallbacks();
  13998. var needNormals = false;
  13999. var needUVs = false;
  14000. // Textures
  14001. if (scene.texturesEnabled) {
  14002. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14003. if (!this.diffuseTexture.isReady()) {
  14004. return false;
  14005. }
  14006. else {
  14007. needUVs = true;
  14008. defines.push("#define DIFFUSE");
  14009. }
  14010. }
  14011. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14012. if (!this.ambientTexture.isReady()) {
  14013. return false;
  14014. }
  14015. else {
  14016. needUVs = true;
  14017. defines.push("#define AMBIENT");
  14018. }
  14019. }
  14020. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14021. if (!this.opacityTexture.isReady()) {
  14022. return false;
  14023. }
  14024. else {
  14025. needUVs = true;
  14026. defines.push("#define OPACITY");
  14027. if (this.opacityTexture.getAlphaFromRGB) {
  14028. defines.push("#define OPACITYRGB");
  14029. }
  14030. }
  14031. }
  14032. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14033. if (!this.reflectionTexture.isReady()) {
  14034. return false;
  14035. }
  14036. else {
  14037. needNormals = true;
  14038. needUVs = true;
  14039. defines.push("#define REFLECTION");
  14040. fallbacks.addFallback(0, "REFLECTION");
  14041. }
  14042. }
  14043. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14044. if (!this.emissiveTexture.isReady()) {
  14045. return false;
  14046. }
  14047. else {
  14048. needUVs = true;
  14049. defines.push("#define EMISSIVE");
  14050. }
  14051. }
  14052. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14053. if (!this.specularTexture.isReady()) {
  14054. return false;
  14055. }
  14056. else {
  14057. needUVs = true;
  14058. defines.push("#define SPECULAR");
  14059. fallbacks.addFallback(0, "SPECULAR");
  14060. }
  14061. }
  14062. }
  14063. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14064. if (!this.bumpTexture.isReady()) {
  14065. return false;
  14066. }
  14067. else {
  14068. needUVs = true;
  14069. defines.push("#define BUMP");
  14070. fallbacks.addFallback(0, "BUMP");
  14071. }
  14072. }
  14073. // Effect
  14074. if (this.useSpecularOverAlpha) {
  14075. defines.push("#define SPECULAROVERALPHA");
  14076. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14077. }
  14078. if (scene.clipPlane) {
  14079. defines.push("#define CLIPPLANE");
  14080. }
  14081. if (engine.getAlphaTesting()) {
  14082. defines.push("#define ALPHATEST");
  14083. }
  14084. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14085. defines.push("#define ALPHAFROMDIFFUSE");
  14086. }
  14087. // Point size
  14088. if (this.pointsCloud || scene.forcePointsCloud) {
  14089. defines.push("#define POINTSIZE");
  14090. }
  14091. // Fog
  14092. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14093. defines.push("#define FOG");
  14094. fallbacks.addFallback(1, "FOG");
  14095. }
  14096. var shadowsActivated = false;
  14097. var lightIndex = 0;
  14098. if (scene.lightsEnabled) {
  14099. for (var index = 0; index < scene.lights.length; index++) {
  14100. var light = scene.lights[index];
  14101. if (!light.isEnabled()) {
  14102. continue;
  14103. }
  14104. // Excluded check
  14105. if (light._excludedMeshesIds.length > 0) {
  14106. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14107. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14108. if (excludedMesh) {
  14109. light.excludedMeshes.push(excludedMesh);
  14110. }
  14111. }
  14112. light._excludedMeshesIds = [];
  14113. }
  14114. // Included check
  14115. if (light._includedOnlyMeshesIds.length > 0) {
  14116. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14117. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14118. if (includedOnlyMesh) {
  14119. light.includedOnlyMeshes.push(includedOnlyMesh);
  14120. }
  14121. }
  14122. light._includedOnlyMeshesIds = [];
  14123. }
  14124. if (!light.canAffectMesh(mesh)) {
  14125. continue;
  14126. }
  14127. needNormals = true;
  14128. defines.push("#define LIGHT" + lightIndex);
  14129. if (lightIndex > 0) {
  14130. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14131. }
  14132. var type;
  14133. if (light instanceof BABYLON.SpotLight) {
  14134. type = "#define SPOTLIGHT" + lightIndex;
  14135. }
  14136. else if (light instanceof BABYLON.HemisphericLight) {
  14137. type = "#define HEMILIGHT" + lightIndex;
  14138. }
  14139. else {
  14140. type = "#define POINTDIRLIGHT" + lightIndex;
  14141. }
  14142. defines.push(type);
  14143. if (lightIndex > 0) {
  14144. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14145. }
  14146. // Shadows
  14147. if (scene.shadowsEnabled) {
  14148. var shadowGenerator = light.getShadowGenerator();
  14149. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14150. defines.push("#define SHADOW" + lightIndex);
  14151. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14152. if (!shadowsActivated) {
  14153. defines.push("#define SHADOWS");
  14154. shadowsActivated = true;
  14155. }
  14156. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14157. defines.push("#define SHADOWVSM" + lightIndex);
  14158. if (lightIndex > 0) {
  14159. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14160. }
  14161. }
  14162. if (shadowGenerator.usePoissonSampling) {
  14163. defines.push("#define SHADOWPCF" + lightIndex);
  14164. if (lightIndex > 0) {
  14165. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14166. }
  14167. }
  14168. }
  14169. }
  14170. lightIndex++;
  14171. if (lightIndex === maxSimultaneousLights)
  14172. break;
  14173. }
  14174. }
  14175. if (StandardMaterial.FresnelEnabled) {
  14176. // Fresnel
  14177. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14178. var fresnelRank = 1;
  14179. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14180. defines.push("#define DIFFUSEFRESNEL");
  14181. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14182. fresnelRank++;
  14183. }
  14184. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14185. defines.push("#define OPACITYFRESNEL");
  14186. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14187. fresnelRank++;
  14188. }
  14189. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14190. defines.push("#define REFLECTIONFRESNEL");
  14191. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14192. fresnelRank++;
  14193. }
  14194. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14195. defines.push("#define EMISSIVEFRESNEL");
  14196. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14197. fresnelRank++;
  14198. }
  14199. needNormals = true;
  14200. defines.push("#define FRESNEL");
  14201. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14202. }
  14203. }
  14204. // Attribs
  14205. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14206. if (mesh) {
  14207. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14208. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14209. defines.push("#define NORMAL");
  14210. }
  14211. if (needUVs) {
  14212. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14213. attribs.push(BABYLON.VertexBuffer.UVKind);
  14214. defines.push("#define UV1");
  14215. }
  14216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14217. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14218. defines.push("#define UV2");
  14219. }
  14220. }
  14221. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14222. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14223. defines.push("#define VERTEXCOLOR");
  14224. if (mesh.hasVertexAlpha) {
  14225. defines.push("#define VERTEXALPHA");
  14226. }
  14227. }
  14228. if (mesh.useBones) {
  14229. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14230. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14231. defines.push("#define BONES");
  14232. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14233. defines.push("#define BONES4");
  14234. fallbacks.addFallback(0, "BONES4");
  14235. }
  14236. // Instances
  14237. if (useInstances) {
  14238. defines.push("#define INSTANCES");
  14239. attribs.push("world0");
  14240. attribs.push("world1");
  14241. attribs.push("world2");
  14242. attribs.push("world3");
  14243. }
  14244. }
  14245. // Get correct effect
  14246. var join = defines.join("\n");
  14247. if (this._cachedDefines !== join) {
  14248. this._cachedDefines = join;
  14249. scene.resetCachedMaterial();
  14250. // Legacy browser patch
  14251. var shaderName = "default";
  14252. if (!scene.getEngine().getCaps().standardDerivatives) {
  14253. shaderName = "legacydefault";
  14254. }
  14255. 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);
  14256. }
  14257. if (!this._effect.isReady()) {
  14258. return false;
  14259. }
  14260. this._renderId = scene.getRenderId();
  14261. this._wasPreviouslyReady = true;
  14262. return true;
  14263. };
  14264. StandardMaterial.prototype.unbind = function () {
  14265. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14266. this._effect.setTexture("reflection2DSampler", null);
  14267. }
  14268. };
  14269. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14270. this._effect.setMatrix("world", world);
  14271. };
  14272. StandardMaterial.prototype.bind = function (world, mesh) {
  14273. var scene = this.getScene();
  14274. // Matrices
  14275. this.bindOnlyWorldMatrix(world);
  14276. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14277. // Bones
  14278. if (mesh.useBones) {
  14279. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14280. }
  14281. if (scene.getCachedMaterial() !== this) {
  14282. if (StandardMaterial.FresnelEnabled) {
  14283. // Fresnel
  14284. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14285. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14286. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14287. }
  14288. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14289. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14290. }
  14291. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14292. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14293. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14294. }
  14295. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14296. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14297. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14298. }
  14299. }
  14300. // Textures
  14301. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14302. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14303. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14304. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14305. }
  14306. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14307. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14308. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14309. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14310. }
  14311. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14312. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14313. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14314. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14315. }
  14316. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14317. if (this.reflectionTexture.isCube) {
  14318. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14319. }
  14320. else {
  14321. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14322. }
  14323. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14324. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14325. }
  14326. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14327. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14328. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14329. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14330. }
  14331. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14332. this._effect.setTexture("specularSampler", this.specularTexture);
  14333. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14334. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14335. }
  14336. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14337. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14338. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14339. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14340. }
  14341. // Clip plane
  14342. if (scene.clipPlane) {
  14343. var clipPlane = scene.clipPlane;
  14344. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14345. }
  14346. // Point size
  14347. if (this.pointsCloud) {
  14348. this._effect.setFloat("pointSize", this.pointSize);
  14349. }
  14350. // Colors
  14351. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14352. // Scaling down color according to emissive
  14353. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14354. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14355. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14356. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14357. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14358. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14359. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14360. }
  14361. // Scaling down color according to emissive
  14362. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14363. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14364. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14365. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14366. if (scene.lightsEnabled) {
  14367. var lightIndex = 0;
  14368. for (var index = 0; index < scene.lights.length; index++) {
  14369. var light = scene.lights[index];
  14370. if (!light.isEnabled()) {
  14371. continue;
  14372. }
  14373. if (!light.canAffectMesh(mesh)) {
  14374. continue;
  14375. }
  14376. if (light instanceof BABYLON.PointLight) {
  14377. // Point Light
  14378. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14379. }
  14380. else if (light instanceof BABYLON.DirectionalLight) {
  14381. // Directional Light
  14382. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14383. }
  14384. else if (light instanceof BABYLON.SpotLight) {
  14385. // Spot Light
  14386. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14387. }
  14388. else if (light instanceof BABYLON.HemisphericLight) {
  14389. // Hemispheric Light
  14390. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14391. }
  14392. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14393. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14394. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14395. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14396. // Shadows
  14397. if (scene.shadowsEnabled) {
  14398. var shadowGenerator = light.getShadowGenerator();
  14399. if (mesh.receiveShadows && shadowGenerator) {
  14400. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14401. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14402. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.getBias());
  14403. }
  14404. }
  14405. lightIndex++;
  14406. if (lightIndex === maxSimultaneousLights)
  14407. break;
  14408. }
  14409. }
  14410. // View
  14411. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14412. this._effect.setMatrix("view", scene.getViewMatrix());
  14413. }
  14414. // Fog
  14415. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14416. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14417. this._effect.setColor3("vFogColor", scene.fogColor);
  14418. }
  14419. _super.prototype.bind.call(this, world, mesh);
  14420. };
  14421. StandardMaterial.prototype.getAnimatables = function () {
  14422. var results = [];
  14423. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14424. results.push(this.diffuseTexture);
  14425. }
  14426. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14427. results.push(this.ambientTexture);
  14428. }
  14429. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14430. results.push(this.opacityTexture);
  14431. }
  14432. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14433. results.push(this.reflectionTexture);
  14434. }
  14435. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14436. results.push(this.emissiveTexture);
  14437. }
  14438. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14439. results.push(this.specularTexture);
  14440. }
  14441. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14442. results.push(this.bumpTexture);
  14443. }
  14444. return results;
  14445. };
  14446. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14447. if (this.diffuseTexture) {
  14448. this.diffuseTexture.dispose();
  14449. }
  14450. if (this.ambientTexture) {
  14451. this.ambientTexture.dispose();
  14452. }
  14453. if (this.opacityTexture) {
  14454. this.opacityTexture.dispose();
  14455. }
  14456. if (this.reflectionTexture) {
  14457. this.reflectionTexture.dispose();
  14458. }
  14459. if (this.emissiveTexture) {
  14460. this.emissiveTexture.dispose();
  14461. }
  14462. if (this.specularTexture) {
  14463. this.specularTexture.dispose();
  14464. }
  14465. if (this.bumpTexture) {
  14466. this.bumpTexture.dispose();
  14467. }
  14468. _super.prototype.dispose.call(this, forceDisposeEffect);
  14469. };
  14470. StandardMaterial.prototype.clone = function (name) {
  14471. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14472. // Base material
  14473. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14474. newStandardMaterial.alpha = this.alpha;
  14475. newStandardMaterial.fillMode = this.fillMode;
  14476. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14477. // Standard material
  14478. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14479. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14480. }
  14481. if (this.ambientTexture && this.ambientTexture.clone) {
  14482. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14483. }
  14484. if (this.opacityTexture && this.opacityTexture.clone) {
  14485. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14486. }
  14487. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14488. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14489. }
  14490. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14491. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14492. }
  14493. if (this.specularTexture && this.specularTexture.clone) {
  14494. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14495. }
  14496. if (this.bumpTexture && this.bumpTexture.clone) {
  14497. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14498. }
  14499. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14500. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14501. newStandardMaterial.specularColor = this.specularColor.clone();
  14502. newStandardMaterial.specularPower = this.specularPower;
  14503. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14504. return newStandardMaterial;
  14505. };
  14506. // Statics
  14507. // Flags used to enable or disable a type of texture for all Standard Materials
  14508. StandardMaterial.DiffuseTextureEnabled = true;
  14509. StandardMaterial.AmbientTextureEnabled = true;
  14510. StandardMaterial.OpacityTextureEnabled = true;
  14511. StandardMaterial.ReflectionTextureEnabled = true;
  14512. StandardMaterial.EmissiveTextureEnabled = true;
  14513. StandardMaterial.SpecularTextureEnabled = true;
  14514. StandardMaterial.BumpTextureEnabled = true;
  14515. StandardMaterial.FresnelEnabled = true;
  14516. return StandardMaterial;
  14517. })(BABYLON.Material);
  14518. BABYLON.StandardMaterial = StandardMaterial;
  14519. })(BABYLON || (BABYLON = {}));
  14520. //# sourceMappingURL=babylon.standardMaterial.js.map
  14521. var BABYLON;
  14522. (function (BABYLON) {
  14523. var MultiMaterial = (function (_super) {
  14524. __extends(MultiMaterial, _super);
  14525. function MultiMaterial(name, scene) {
  14526. _super.call(this, name, scene, true);
  14527. this.subMaterials = new Array();
  14528. scene.multiMaterials.push(this);
  14529. }
  14530. // Properties
  14531. MultiMaterial.prototype.getSubMaterial = function (index) {
  14532. if (index < 0 || index >= this.subMaterials.length) {
  14533. return this.getScene().defaultMaterial;
  14534. }
  14535. return this.subMaterials[index];
  14536. };
  14537. // Methods
  14538. MultiMaterial.prototype.isReady = function (mesh) {
  14539. for (var index = 0; index < this.subMaterials.length; index++) {
  14540. var subMaterial = this.subMaterials[index];
  14541. if (subMaterial) {
  14542. if (!this.subMaterials[index].isReady(mesh)) {
  14543. return false;
  14544. }
  14545. }
  14546. }
  14547. return true;
  14548. };
  14549. return MultiMaterial;
  14550. })(BABYLON.Material);
  14551. BABYLON.MultiMaterial = MultiMaterial;
  14552. })(BABYLON || (BABYLON = {}));
  14553. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14554. (function (BABYLON) {
  14555. var Database = (function () {
  14556. function Database(urlToScene, callbackManifestChecked) {
  14557. // Handling various flavors of prefixed version of IndexedDB
  14558. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14559. this.callbackManifestChecked = callbackManifestChecked;
  14560. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14561. this.db = null;
  14562. this.enableSceneOffline = false;
  14563. this.enableTexturesOffline = false;
  14564. this.manifestVersionFound = 0;
  14565. this.mustUpdateRessources = false;
  14566. this.hasReachedQuota = false;
  14567. this.checkManifestFile();
  14568. }
  14569. Database.prototype.checkManifestFile = function () {
  14570. var _this = this;
  14571. function noManifestFile() {
  14572. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14573. that.enableSceneOffline = false;
  14574. that.enableTexturesOffline = false;
  14575. that.callbackManifestChecked(false);
  14576. }
  14577. var that = this;
  14578. var manifestURL = this.currentSceneUrl + ".manifest";
  14579. var xhr = new XMLHttpRequest();
  14580. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14581. xhr.open("GET", manifestURLTimeStamped, true);
  14582. xhr.addEventListener("load", function () {
  14583. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14584. try {
  14585. var manifestFile = JSON.parse(xhr.response);
  14586. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14587. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14588. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14589. _this.manifestVersionFound = manifestFile.version;
  14590. }
  14591. if (_this.callbackManifestChecked) {
  14592. _this.callbackManifestChecked(true);
  14593. }
  14594. }
  14595. catch (ex) {
  14596. noManifestFile();
  14597. }
  14598. }
  14599. else {
  14600. noManifestFile();
  14601. }
  14602. }, false);
  14603. xhr.addEventListener("error", function (event) {
  14604. noManifestFile();
  14605. }, false);
  14606. try {
  14607. xhr.send();
  14608. }
  14609. catch (ex) {
  14610. BABYLON.Tools.Error("Error on XHR send request.");
  14611. that.callbackManifestChecked(false);
  14612. }
  14613. };
  14614. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14615. var _this = this;
  14616. function handleError() {
  14617. that.isSupported = false;
  14618. if (errorCallback)
  14619. errorCallback();
  14620. }
  14621. var that = this;
  14622. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14623. // Your browser doesn't support IndexedDB
  14624. this.isSupported = false;
  14625. if (errorCallback)
  14626. errorCallback();
  14627. }
  14628. else {
  14629. // If the DB hasn't been opened or created yet
  14630. if (!this.db) {
  14631. this.hasReachedQuota = false;
  14632. this.isSupported = true;
  14633. var request = this.idbFactory.open("babylonjs", 1);
  14634. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14635. request.onerror = function (event) {
  14636. handleError();
  14637. };
  14638. // executes when a version change transaction cannot complete due to other active transactions
  14639. request.onblocked = function (event) {
  14640. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14641. handleError();
  14642. };
  14643. // DB has been opened successfully
  14644. request.onsuccess = function (event) {
  14645. _this.db = request.result;
  14646. successCallback();
  14647. };
  14648. // Initialization of the DB. Creating Scenes & Textures stores
  14649. request.onupgradeneeded = function (event) {
  14650. _this.db = (event.target).result;
  14651. try {
  14652. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14653. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14654. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14655. }
  14656. catch (ex) {
  14657. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14658. handleError();
  14659. }
  14660. };
  14661. }
  14662. else {
  14663. if (successCallback)
  14664. successCallback();
  14665. }
  14666. }
  14667. };
  14668. Database.prototype.loadImageFromDB = function (url, image) {
  14669. var _this = this;
  14670. var completeURL = Database.ReturnFullUrlLocation(url);
  14671. var saveAndLoadImage = function () {
  14672. if (!_this.hasReachedQuota && _this.db !== null) {
  14673. // the texture is not yet in the DB, let's try to save it
  14674. _this._saveImageIntoDBAsync(completeURL, image);
  14675. }
  14676. else {
  14677. image.src = url;
  14678. }
  14679. };
  14680. if (!this.mustUpdateRessources) {
  14681. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14682. }
  14683. else {
  14684. saveAndLoadImage();
  14685. }
  14686. };
  14687. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14688. if (this.isSupported && this.db !== null) {
  14689. var texture;
  14690. var transaction = this.db.transaction(["textures"]);
  14691. transaction.onabort = function (event) {
  14692. image.src = url;
  14693. };
  14694. transaction.oncomplete = function (event) {
  14695. var blobTextureURL;
  14696. if (texture) {
  14697. var URL = window.URL || window.webkitURL;
  14698. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14699. image.onerror = function () {
  14700. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14701. image.src = url;
  14702. };
  14703. image.src = blobTextureURL;
  14704. }
  14705. else {
  14706. notInDBCallback();
  14707. }
  14708. };
  14709. var getRequest = transaction.objectStore("textures").get(url);
  14710. getRequest.onsuccess = function (event) {
  14711. texture = (event.target).result;
  14712. };
  14713. getRequest.onerror = function (event) {
  14714. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14715. image.src = url;
  14716. };
  14717. }
  14718. else {
  14719. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14720. image.src = url;
  14721. }
  14722. };
  14723. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14724. var _this = this;
  14725. if (this.isSupported) {
  14726. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14727. var generateBlobUrl = function () {
  14728. var blobTextureURL;
  14729. if (blob) {
  14730. var URL = window.URL || window.webkitURL;
  14731. try {
  14732. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14733. }
  14734. catch (ex) {
  14735. blobTextureURL = URL.createObjectURL(blob);
  14736. }
  14737. }
  14738. image.src = blobTextureURL;
  14739. };
  14740. if (Database.isUASupportingBlobStorage) {
  14741. var xhr = new XMLHttpRequest(), blob;
  14742. xhr.open("GET", url, true);
  14743. xhr.responseType = "blob";
  14744. xhr.addEventListener("load", function () {
  14745. if (xhr.status === 200) {
  14746. // Blob as response (XHR2)
  14747. blob = xhr.response;
  14748. var transaction = _this.db.transaction(["textures"], "readwrite");
  14749. // the transaction could abort because of a QuotaExceededError error
  14750. transaction.onabort = function (event) {
  14751. try {
  14752. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14753. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14754. this.hasReachedQuota = true;
  14755. }
  14756. }
  14757. catch (ex) {
  14758. }
  14759. generateBlobUrl();
  14760. };
  14761. transaction.oncomplete = function (event) {
  14762. generateBlobUrl();
  14763. };
  14764. var newTexture = { textureUrl: url, data: blob };
  14765. try {
  14766. // Put the blob into the dabase
  14767. var addRequest = transaction.objectStore("textures").put(newTexture);
  14768. addRequest.onsuccess = function (event) {
  14769. };
  14770. addRequest.onerror = function (event) {
  14771. generateBlobUrl();
  14772. };
  14773. }
  14774. catch (ex) {
  14775. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14776. if (ex.code === 25) {
  14777. Database.isUASupportingBlobStorage = false;
  14778. }
  14779. image.src = url;
  14780. }
  14781. }
  14782. else {
  14783. image.src = url;
  14784. }
  14785. }, false);
  14786. xhr.addEventListener("error", function (event) {
  14787. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14788. image.src = url;
  14789. }, false);
  14790. xhr.send();
  14791. }
  14792. else {
  14793. image.src = url;
  14794. }
  14795. }
  14796. else {
  14797. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14798. image.src = url;
  14799. }
  14800. };
  14801. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14802. var _this = this;
  14803. var updateVersion = function (event) {
  14804. // the version is not yet in the DB or we need to update it
  14805. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14806. };
  14807. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14808. };
  14809. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14810. var _this = this;
  14811. if (this.isSupported) {
  14812. var version;
  14813. try {
  14814. var transaction = this.db.transaction(["versions"]);
  14815. transaction.oncomplete = function (event) {
  14816. if (version) {
  14817. // If the version in the JSON file is > than the version in DB
  14818. if (_this.manifestVersionFound > version.data) {
  14819. _this.mustUpdateRessources = true;
  14820. updateInDBCallback();
  14821. }
  14822. else {
  14823. callback(version.data);
  14824. }
  14825. }
  14826. else {
  14827. _this.mustUpdateRessources = true;
  14828. updateInDBCallback();
  14829. }
  14830. };
  14831. transaction.onabort = function (event) {
  14832. callback(-1);
  14833. };
  14834. var getRequest = transaction.objectStore("versions").get(url);
  14835. getRequest.onsuccess = function (event) {
  14836. version = (event.target).result;
  14837. };
  14838. getRequest.onerror = function (event) {
  14839. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14840. callback(-1);
  14841. };
  14842. }
  14843. catch (ex) {
  14844. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14845. callback(-1);
  14846. }
  14847. }
  14848. else {
  14849. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14850. callback(-1);
  14851. }
  14852. };
  14853. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14854. var _this = this;
  14855. if (this.isSupported && !this.hasReachedQuota) {
  14856. try {
  14857. // Open a transaction to the database
  14858. var transaction = this.db.transaction(["versions"], "readwrite");
  14859. // the transaction could abort because of a QuotaExceededError error
  14860. transaction.onabort = function (event) {
  14861. try {
  14862. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14863. _this.hasReachedQuota = true;
  14864. }
  14865. }
  14866. catch (ex) {
  14867. }
  14868. callback(-1);
  14869. };
  14870. transaction.oncomplete = function (event) {
  14871. callback(_this.manifestVersionFound);
  14872. };
  14873. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14874. // Put the scene into the database
  14875. var addRequest = transaction.objectStore("versions").put(newVersion);
  14876. addRequest.onsuccess = function (event) {
  14877. };
  14878. addRequest.onerror = function (event) {
  14879. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14880. };
  14881. }
  14882. catch (ex) {
  14883. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14884. callback(-1);
  14885. }
  14886. }
  14887. else {
  14888. callback(-1);
  14889. }
  14890. };
  14891. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14892. var _this = this;
  14893. var completeUrl = Database.ReturnFullUrlLocation(url);
  14894. var saveAndLoadFile = function (event) {
  14895. // the scene is not yet in the DB, let's try to save it
  14896. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14897. };
  14898. this._checkVersionFromDB(completeUrl, function (version) {
  14899. if (version !== -1) {
  14900. if (!_this.mustUpdateRessources) {
  14901. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14902. }
  14903. else {
  14904. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14905. }
  14906. }
  14907. else {
  14908. errorCallback();
  14909. }
  14910. });
  14911. };
  14912. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14913. if (this.isSupported) {
  14914. var targetStore;
  14915. if (url.indexOf(".babylon") !== -1) {
  14916. targetStore = "scenes";
  14917. }
  14918. else {
  14919. targetStore = "textures";
  14920. }
  14921. var file;
  14922. var transaction = this.db.transaction([targetStore]);
  14923. transaction.oncomplete = function (event) {
  14924. if (file) {
  14925. callback(file.data);
  14926. }
  14927. else {
  14928. notInDBCallback();
  14929. }
  14930. };
  14931. transaction.onabort = function (event) {
  14932. notInDBCallback();
  14933. };
  14934. var getRequest = transaction.objectStore(targetStore).get(url);
  14935. getRequest.onsuccess = function (event) {
  14936. file = (event.target).result;
  14937. };
  14938. getRequest.onerror = function (event) {
  14939. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14940. notInDBCallback();
  14941. };
  14942. }
  14943. else {
  14944. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14945. callback();
  14946. }
  14947. };
  14948. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14949. var _this = this;
  14950. if (this.isSupported) {
  14951. var targetStore;
  14952. if (url.indexOf(".babylon") !== -1) {
  14953. targetStore = "scenes";
  14954. }
  14955. else {
  14956. targetStore = "textures";
  14957. }
  14958. // Create XHR
  14959. var xhr = new XMLHttpRequest(), fileData;
  14960. xhr.open("GET", url, true);
  14961. if (useArrayBuffer) {
  14962. xhr.responseType = "arraybuffer";
  14963. }
  14964. xhr.onprogress = progressCallback;
  14965. xhr.addEventListener("load", function () {
  14966. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14967. // Blob as response (XHR2)
  14968. //fileData = xhr.responseText;
  14969. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14970. if (!_this.hasReachedQuota) {
  14971. // Open a transaction to the database
  14972. var transaction = _this.db.transaction([targetStore], "readwrite");
  14973. // the transaction could abort because of a QuotaExceededError error
  14974. transaction.onabort = function (event) {
  14975. try {
  14976. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14977. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14978. this.hasReachedQuota = true;
  14979. }
  14980. }
  14981. catch (ex) {
  14982. }
  14983. callback(fileData);
  14984. };
  14985. transaction.oncomplete = function (event) {
  14986. callback(fileData);
  14987. };
  14988. var newFile;
  14989. if (targetStore === "scenes") {
  14990. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14991. }
  14992. else {
  14993. newFile = { textureUrl: url, data: fileData };
  14994. }
  14995. try {
  14996. // Put the scene into the database
  14997. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14998. addRequest.onsuccess = function (event) {
  14999. };
  15000. addRequest.onerror = function (event) {
  15001. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15002. };
  15003. }
  15004. catch (ex) {
  15005. callback(fileData);
  15006. }
  15007. }
  15008. else {
  15009. callback(fileData);
  15010. }
  15011. }
  15012. else {
  15013. callback();
  15014. }
  15015. }, false);
  15016. xhr.addEventListener("error", function (event) {
  15017. BABYLON.Tools.Error("error on XHR request.");
  15018. callback();
  15019. }, false);
  15020. xhr.send();
  15021. }
  15022. else {
  15023. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15024. callback();
  15025. }
  15026. };
  15027. Database.isUASupportingBlobStorage = true;
  15028. Database.parseURL = function (url) {
  15029. var a = document.createElement('a');
  15030. a.href = url;
  15031. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15032. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15033. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15034. return absLocation;
  15035. };
  15036. Database.ReturnFullUrlLocation = function (url) {
  15037. if (url.indexOf("http:/") === -1) {
  15038. return (BABYLON.Database.parseURL(window.location.href) + url);
  15039. }
  15040. else {
  15041. return url;
  15042. }
  15043. };
  15044. return Database;
  15045. })();
  15046. BABYLON.Database = Database;
  15047. })(BABYLON || (BABYLON = {}));
  15048. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15049. (function (BABYLON) {
  15050. var SpriteManager = (function () {
  15051. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  15052. this.name = name;
  15053. this.cellSize = cellSize;
  15054. this.sprites = new Array();
  15055. this.renderingGroupId = 0;
  15056. this.fogEnabled = true;
  15057. this._vertexDeclaration = [3, 4, 4, 4];
  15058. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15059. this._capacity = capacity;
  15060. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  15061. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15062. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15063. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15064. this._scene = scene;
  15065. this._scene.spriteManagers.push(this);
  15066. // VBO
  15067. this._vertexDeclaration = [3, 4, 4, 4];
  15068. this._vertexStrideSize = 15 * 4;
  15069. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15070. var indices = [];
  15071. var index = 0;
  15072. for (var count = 0; count < capacity; count++) {
  15073. indices.push(index);
  15074. indices.push(index + 1);
  15075. indices.push(index + 2);
  15076. indices.push(index);
  15077. indices.push(index + 2);
  15078. indices.push(index + 3);
  15079. index += 4;
  15080. }
  15081. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15082. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15083. // Effects
  15084. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15085. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15086. }
  15087. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15088. var arrayOffset = index * 15;
  15089. if (offsetX == 0)
  15090. offsetX = this._epsilon;
  15091. else if (offsetX == 1)
  15092. offsetX = 1 - this._epsilon;
  15093. if (offsetY == 0)
  15094. offsetY = this._epsilon;
  15095. else if (offsetY == 1)
  15096. offsetY = 1 - this._epsilon;
  15097. this._vertices[arrayOffset] = sprite.position.x;
  15098. this._vertices[arrayOffset + 1] = sprite.position.y;
  15099. this._vertices[arrayOffset + 2] = sprite.position.z;
  15100. this._vertices[arrayOffset + 3] = sprite.angle;
  15101. this._vertices[arrayOffset + 4] = sprite.size;
  15102. this._vertices[arrayOffset + 5] = offsetX;
  15103. this._vertices[arrayOffset + 6] = offsetY;
  15104. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  15105. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  15106. var offset = (sprite.cellIndex / rowSize) >> 0;
  15107. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  15108. this._vertices[arrayOffset + 10] = offset;
  15109. // Color
  15110. this._vertices[arrayOffset + 11] = sprite.color.r;
  15111. this._vertices[arrayOffset + 12] = sprite.color.g;
  15112. this._vertices[arrayOffset + 13] = sprite.color.b;
  15113. this._vertices[arrayOffset + 14] = sprite.color.a;
  15114. };
  15115. SpriteManager.prototype.render = function () {
  15116. // Check
  15117. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15118. return;
  15119. var engine = this._scene.getEngine();
  15120. var baseSize = this._spriteTexture.getBaseSize();
  15121. // Sprites
  15122. var deltaTime = engine.getDeltaTime();
  15123. var max = Math.min(this._capacity, this.sprites.length);
  15124. var rowSize = baseSize.width / this.cellSize;
  15125. var offset = 0;
  15126. for (var index = 0; index < max; index++) {
  15127. var sprite = this.sprites[index];
  15128. if (!sprite) {
  15129. continue;
  15130. }
  15131. sprite._animate(deltaTime);
  15132. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15133. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15134. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15135. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15136. }
  15137. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15138. // Render
  15139. var effect = this._effectBase;
  15140. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15141. effect = this._effectFog;
  15142. }
  15143. engine.enableEffect(effect);
  15144. var viewMatrix = this._scene.getViewMatrix();
  15145. effect.setTexture("diffuseSampler", this._spriteTexture);
  15146. effect.setMatrix("view", viewMatrix);
  15147. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15148. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15149. // Fog
  15150. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15151. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15152. effect.setColor3("vFogColor", this._scene.fogColor);
  15153. }
  15154. // VBOs
  15155. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15156. // Draw order
  15157. effect.setBool("alphaTest", true);
  15158. engine.setColorWrite(false);
  15159. engine.draw(true, 0, max * 6);
  15160. engine.setColorWrite(true);
  15161. effect.setBool("alphaTest", false);
  15162. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15163. engine.draw(true, 0, max * 6);
  15164. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15165. };
  15166. SpriteManager.prototype.dispose = function () {
  15167. if (this._vertexBuffer) {
  15168. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15169. this._vertexBuffer = null;
  15170. }
  15171. if (this._indexBuffer) {
  15172. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15173. this._indexBuffer = null;
  15174. }
  15175. if (this._spriteTexture) {
  15176. this._spriteTexture.dispose();
  15177. this._spriteTexture = null;
  15178. }
  15179. // Remove from scene
  15180. var index = this._scene.spriteManagers.indexOf(this);
  15181. this._scene.spriteManagers.splice(index, 1);
  15182. // Callback
  15183. if (this.onDispose) {
  15184. this.onDispose();
  15185. }
  15186. };
  15187. return SpriteManager;
  15188. })();
  15189. BABYLON.SpriteManager = SpriteManager;
  15190. })(BABYLON || (BABYLON = {}));
  15191. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15192. (function (BABYLON) {
  15193. var Sprite = (function () {
  15194. function Sprite(name, manager) {
  15195. this.name = name;
  15196. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15197. this.size = 1.0;
  15198. this.angle = 0;
  15199. this.cellIndex = 0;
  15200. this.invertU = 0;
  15201. this.invertV = 0;
  15202. this.animations = new Array();
  15203. this._animationStarted = false;
  15204. this._loopAnimation = false;
  15205. this._fromIndex = 0;
  15206. this._toIndex = 0;
  15207. this._delay = 0;
  15208. this._direction = 1;
  15209. this._frameCount = 0;
  15210. this._time = 0;
  15211. this._manager = manager;
  15212. this._manager.sprites.push(this);
  15213. this.position = BABYLON.Vector3.Zero();
  15214. }
  15215. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15216. this._fromIndex = from;
  15217. this._toIndex = to;
  15218. this._loopAnimation = loop;
  15219. this._delay = delay;
  15220. this._animationStarted = true;
  15221. this._direction = from < to ? 1 : -1;
  15222. this.cellIndex = from;
  15223. this._time = 0;
  15224. };
  15225. Sprite.prototype.stopAnimation = function () {
  15226. this._animationStarted = false;
  15227. };
  15228. Sprite.prototype._animate = function (deltaTime) {
  15229. if (!this._animationStarted)
  15230. return;
  15231. this._time += deltaTime;
  15232. if (this._time > this._delay) {
  15233. this._time = this._time % this._delay;
  15234. this.cellIndex += this._direction;
  15235. if (this.cellIndex == this._toIndex) {
  15236. if (this._loopAnimation) {
  15237. this.cellIndex = this._fromIndex;
  15238. }
  15239. else {
  15240. this._animationStarted = false;
  15241. if (this.disposeWhenFinishedAnimating) {
  15242. this.dispose();
  15243. }
  15244. }
  15245. }
  15246. }
  15247. };
  15248. Sprite.prototype.dispose = function () {
  15249. for (var i = 0; i < this._manager.sprites.length; i++) {
  15250. if (this._manager.sprites[i] == this) {
  15251. this._manager.sprites.splice(i, 1);
  15252. }
  15253. }
  15254. };
  15255. return Sprite;
  15256. })();
  15257. BABYLON.Sprite = Sprite;
  15258. })(BABYLON || (BABYLON = {}));
  15259. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15260. (function (BABYLON) {
  15261. var Layer = (function () {
  15262. function Layer(name, imgUrl, scene, isBackground, color) {
  15263. this.name = name;
  15264. this._vertexDeclaration = [2];
  15265. this._vertexStrideSize = 2 * 4;
  15266. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15267. this.isBackground = isBackground === undefined ? true : isBackground;
  15268. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15269. this._scene = scene;
  15270. this._scene.layers.push(this);
  15271. // VBO
  15272. var vertices = [];
  15273. vertices.push(1, 1);
  15274. vertices.push(-1, 1);
  15275. vertices.push(-1, -1);
  15276. vertices.push(1, -1);
  15277. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15278. // Indices
  15279. var indices = [];
  15280. indices.push(0);
  15281. indices.push(1);
  15282. indices.push(2);
  15283. indices.push(0);
  15284. indices.push(2);
  15285. indices.push(3);
  15286. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15287. // Effects
  15288. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15289. }
  15290. Layer.prototype.render = function () {
  15291. // Check
  15292. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15293. return;
  15294. var engine = this._scene.getEngine();
  15295. // Render
  15296. engine.enableEffect(this._effect);
  15297. engine.setState(false);
  15298. // Texture
  15299. this._effect.setTexture("textureSampler", this.texture);
  15300. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15301. // Color
  15302. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15303. // VBOs
  15304. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15305. // Draw order
  15306. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15307. engine.draw(true, 0, 6);
  15308. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15309. };
  15310. Layer.prototype.dispose = function () {
  15311. if (this._vertexBuffer) {
  15312. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15313. this._vertexBuffer = null;
  15314. }
  15315. if (this._indexBuffer) {
  15316. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15317. this._indexBuffer = null;
  15318. }
  15319. if (this.texture) {
  15320. this.texture.dispose();
  15321. this.texture = null;
  15322. }
  15323. // Remove from scene
  15324. var index = this._scene.layers.indexOf(this);
  15325. this._scene.layers.splice(index, 1);
  15326. // Callback
  15327. if (this.onDispose) {
  15328. this.onDispose();
  15329. }
  15330. };
  15331. return Layer;
  15332. })();
  15333. BABYLON.Layer = Layer;
  15334. })(BABYLON || (BABYLON = {}));
  15335. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15336. (function (BABYLON) {
  15337. var Particle = (function () {
  15338. function Particle() {
  15339. this.position = BABYLON.Vector3.Zero();
  15340. this.direction = BABYLON.Vector3.Zero();
  15341. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15342. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15343. this.lifeTime = 1.0;
  15344. this.age = 0;
  15345. this.size = 0;
  15346. this.angle = 0;
  15347. this.angularSpeed = 0;
  15348. }
  15349. Particle.prototype.copyTo = function (other) {
  15350. other.position.copyFrom(this.position);
  15351. other.direction.copyFrom(this.direction);
  15352. other.color.copyFrom(this.color);
  15353. other.colorStep.copyFrom(this.colorStep);
  15354. other.lifeTime = this.lifeTime;
  15355. other.age = this.age;
  15356. other.size = this.size;
  15357. other.angle = this.angle;
  15358. other.angularSpeed = this.angularSpeed;
  15359. };
  15360. return Particle;
  15361. })();
  15362. BABYLON.Particle = Particle;
  15363. })(BABYLON || (BABYLON = {}));
  15364. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15365. (function (BABYLON) {
  15366. var randomNumber = function (min, max) {
  15367. if (min === max) {
  15368. return (min);
  15369. }
  15370. var random = Math.random();
  15371. return ((random * (max - min)) + min);
  15372. };
  15373. var ParticleSystem = (function () {
  15374. function ParticleSystem(name, capacity, scene, customEffect) {
  15375. var _this = this;
  15376. this.name = name;
  15377. this.renderingGroupId = 0;
  15378. this.emitter = null;
  15379. this.emitRate = 10;
  15380. this.manualEmitCount = -1;
  15381. this.updateSpeed = 0.01;
  15382. this.targetStopDuration = 0;
  15383. this.disposeOnStop = false;
  15384. this.minEmitPower = 1;
  15385. this.maxEmitPower = 1;
  15386. this.minLifeTime = 1;
  15387. this.maxLifeTime = 1;
  15388. this.minSize = 1;
  15389. this.maxSize = 1;
  15390. this.minAngularSpeed = 0;
  15391. this.maxAngularSpeed = 0;
  15392. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15393. this.forceDepthWrite = false;
  15394. this.gravity = BABYLON.Vector3.Zero();
  15395. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15396. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15397. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15398. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15399. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15400. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15401. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15402. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15403. this.particles = new Array();
  15404. this._vertexDeclaration = [3, 4, 4];
  15405. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15406. this._stockParticles = new Array();
  15407. this._newPartsExcess = 0;
  15408. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15409. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15410. this._scaledDirection = BABYLON.Vector3.Zero();
  15411. this._scaledGravity = BABYLON.Vector3.Zero();
  15412. this._currentRenderId = -1;
  15413. this._started = false;
  15414. this._stopped = false;
  15415. this._actualFrame = 0;
  15416. this.id = name;
  15417. this._capacity = capacity;
  15418. this._scene = scene;
  15419. this._customEffect = customEffect;
  15420. scene.particleSystems.push(this);
  15421. // VBO
  15422. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15423. var indices = [];
  15424. var index = 0;
  15425. for (var count = 0; count < capacity; count++) {
  15426. indices.push(index);
  15427. indices.push(index + 1);
  15428. indices.push(index + 2);
  15429. indices.push(index);
  15430. indices.push(index + 2);
  15431. indices.push(index + 3);
  15432. index += 4;
  15433. }
  15434. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15435. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15436. // Default behaviors
  15437. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15438. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15439. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15440. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15441. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15442. };
  15443. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15444. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15445. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15446. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15447. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15448. };
  15449. this.updateFunction = function (particles) {
  15450. for (var index = 0; index < particles.length; index++) {
  15451. var particle = particles[index];
  15452. particle.age += _this._scaledUpdateSpeed;
  15453. if (particle.age >= particle.lifeTime) {
  15454. _this.recycleParticle(particle);
  15455. index--;
  15456. continue;
  15457. }
  15458. else {
  15459. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15460. particle.color.addInPlace(_this._scaledColorStep);
  15461. if (particle.color.a < 0)
  15462. particle.color.a = 0;
  15463. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15464. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15465. particle.position.addInPlace(_this._scaledDirection);
  15466. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15467. particle.direction.addInPlace(_this._scaledGravity);
  15468. }
  15469. }
  15470. };
  15471. }
  15472. ParticleSystem.prototype.recycleParticle = function (particle) {
  15473. var lastParticle = this.particles.pop();
  15474. if (lastParticle !== particle) {
  15475. lastParticle.copyTo(particle);
  15476. this._stockParticles.push(lastParticle);
  15477. }
  15478. };
  15479. ParticleSystem.prototype.getCapacity = function () {
  15480. return this._capacity;
  15481. };
  15482. ParticleSystem.prototype.isAlive = function () {
  15483. return this._alive;
  15484. };
  15485. ParticleSystem.prototype.isStarted = function () {
  15486. return this._started;
  15487. };
  15488. ParticleSystem.prototype.start = function () {
  15489. this._started = true;
  15490. this._stopped = false;
  15491. this._actualFrame = 0;
  15492. };
  15493. ParticleSystem.prototype.stop = function () {
  15494. this._stopped = true;
  15495. };
  15496. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15497. var offset = index * 11;
  15498. this._vertices[offset] = particle.position.x;
  15499. this._vertices[offset + 1] = particle.position.y;
  15500. this._vertices[offset + 2] = particle.position.z;
  15501. this._vertices[offset + 3] = particle.color.r;
  15502. this._vertices[offset + 4] = particle.color.g;
  15503. this._vertices[offset + 5] = particle.color.b;
  15504. this._vertices[offset + 6] = particle.color.a;
  15505. this._vertices[offset + 7] = particle.angle;
  15506. this._vertices[offset + 8] = particle.size;
  15507. this._vertices[offset + 9] = offsetX;
  15508. this._vertices[offset + 10] = offsetY;
  15509. };
  15510. ParticleSystem.prototype._update = function (newParticles) {
  15511. // Update current
  15512. this._alive = this.particles.length > 0;
  15513. this.updateFunction(this.particles);
  15514. // Add new ones
  15515. var worldMatrix;
  15516. if (this.emitter.position) {
  15517. worldMatrix = this.emitter.getWorldMatrix();
  15518. }
  15519. else {
  15520. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15521. }
  15522. for (var index = 0; index < newParticles; index++) {
  15523. if (this.particles.length === this._capacity) {
  15524. break;
  15525. }
  15526. if (this._stockParticles.length !== 0) {
  15527. var particle = this._stockParticles.pop();
  15528. particle.age = 0;
  15529. }
  15530. else {
  15531. particle = new BABYLON.Particle();
  15532. }
  15533. this.particles.push(particle);
  15534. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15535. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15536. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15537. particle.size = randomNumber(this.minSize, this.maxSize);
  15538. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15539. this.startPositionFunction(worldMatrix, particle.position);
  15540. var step = randomNumber(0, 1.0);
  15541. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15542. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15543. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15544. }
  15545. };
  15546. ParticleSystem.prototype._getEffect = function () {
  15547. if (this._customEffect) {
  15548. return this._customEffect;
  15549. }
  15550. ;
  15551. var defines = [];
  15552. if (this._scene.clipPlane) {
  15553. defines.push("#define CLIPPLANE");
  15554. }
  15555. // Effect
  15556. var join = defines.join("\n");
  15557. if (this._cachedDefines !== join) {
  15558. this._cachedDefines = join;
  15559. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15560. }
  15561. return this._effect;
  15562. };
  15563. ParticleSystem.prototype.animate = function () {
  15564. if (!this._started)
  15565. return;
  15566. var effect = this._getEffect();
  15567. // Check
  15568. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15569. return;
  15570. if (this._currentRenderId === this._scene.getRenderId()) {
  15571. return;
  15572. }
  15573. this._currentRenderId = this._scene.getRenderId();
  15574. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15575. // determine the number of particles we need to create
  15576. var emitCout;
  15577. if (this.manualEmitCount > -1) {
  15578. emitCout = this.manualEmitCount;
  15579. this.manualEmitCount = 0;
  15580. }
  15581. else {
  15582. emitCout = this.emitRate;
  15583. }
  15584. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15585. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15586. if (this._newPartsExcess > 1.0) {
  15587. newParticles += this._newPartsExcess >> 0;
  15588. this._newPartsExcess -= this._newPartsExcess >> 0;
  15589. }
  15590. this._alive = false;
  15591. if (!this._stopped) {
  15592. this._actualFrame += this._scaledUpdateSpeed;
  15593. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15594. this.stop();
  15595. }
  15596. else {
  15597. newParticles = 0;
  15598. }
  15599. this._update(newParticles);
  15600. // Stopped?
  15601. if (this._stopped) {
  15602. if (!this._alive) {
  15603. this._started = false;
  15604. if (this.disposeOnStop) {
  15605. this._scene._toBeDisposed.push(this);
  15606. }
  15607. }
  15608. }
  15609. // Update VBO
  15610. var offset = 0;
  15611. for (var index = 0; index < this.particles.length; index++) {
  15612. var particle = this.particles[index];
  15613. this._appendParticleVertex(offset++, particle, 0, 0);
  15614. this._appendParticleVertex(offset++, particle, 1, 0);
  15615. this._appendParticleVertex(offset++, particle, 1, 1);
  15616. this._appendParticleVertex(offset++, particle, 0, 1);
  15617. }
  15618. var engine = this._scene.getEngine();
  15619. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15620. };
  15621. ParticleSystem.prototype.render = function () {
  15622. var effect = this._getEffect();
  15623. // Check
  15624. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15625. return 0;
  15626. var engine = this._scene.getEngine();
  15627. // Render
  15628. engine.enableEffect(effect);
  15629. engine.setState(false);
  15630. var viewMatrix = this._scene.getViewMatrix();
  15631. effect.setTexture("diffuseSampler", this.particleTexture);
  15632. effect.setMatrix("view", viewMatrix);
  15633. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15634. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15635. if (this._scene.clipPlane) {
  15636. var clipPlane = this._scene.clipPlane;
  15637. var invView = viewMatrix.clone();
  15638. invView.invert();
  15639. effect.setMatrix("invView", invView);
  15640. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15641. }
  15642. // VBOs
  15643. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15644. // Draw order
  15645. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15646. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15647. }
  15648. else {
  15649. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15650. }
  15651. if (this.forceDepthWrite) {
  15652. engine.setDepthWrite(true);
  15653. }
  15654. engine.draw(true, 0, this.particles.length * 6);
  15655. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15656. return this.particles.length;
  15657. };
  15658. ParticleSystem.prototype.dispose = function () {
  15659. if (this._vertexBuffer) {
  15660. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15661. this._vertexBuffer = null;
  15662. }
  15663. if (this._indexBuffer) {
  15664. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15665. this._indexBuffer = null;
  15666. }
  15667. if (this.particleTexture) {
  15668. this.particleTexture.dispose();
  15669. this.particleTexture = null;
  15670. }
  15671. // Remove from scene
  15672. var index = this._scene.particleSystems.indexOf(this);
  15673. this._scene.particleSystems.splice(index, 1);
  15674. // Callback
  15675. if (this.onDispose) {
  15676. this.onDispose();
  15677. }
  15678. };
  15679. // Clone
  15680. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15681. var result = new ParticleSystem(name, this._capacity, this._scene);
  15682. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15683. if (newEmitter === undefined) {
  15684. newEmitter = this.emitter;
  15685. }
  15686. result.emitter = newEmitter;
  15687. if (this.particleTexture) {
  15688. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15689. }
  15690. result.start();
  15691. return result;
  15692. };
  15693. // Statics
  15694. ParticleSystem.BLENDMODE_ONEONE = 0;
  15695. ParticleSystem.BLENDMODE_STANDARD = 1;
  15696. return ParticleSystem;
  15697. })();
  15698. BABYLON.ParticleSystem = ParticleSystem;
  15699. })(BABYLON || (BABYLON = {}));
  15700. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15701. (function (BABYLON) {
  15702. var Animation = (function () {
  15703. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15704. this.name = name;
  15705. this.targetProperty = targetProperty;
  15706. this.framePerSecond = framePerSecond;
  15707. this.dataType = dataType;
  15708. this.loopMode = loopMode;
  15709. this._offsetsCache = {};
  15710. this._highLimitsCache = {};
  15711. this._stopped = false;
  15712. this.targetPropertyPath = targetProperty.split(".");
  15713. this.dataType = dataType;
  15714. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15715. }
  15716. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15717. var dataType = undefined;
  15718. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15719. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15720. }
  15721. else if (from instanceof BABYLON.Quaternion) {
  15722. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15723. }
  15724. else if (from instanceof BABYLON.Vector3) {
  15725. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15726. }
  15727. else if (from instanceof BABYLON.Vector2) {
  15728. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15729. }
  15730. else if (from instanceof BABYLON.Color3) {
  15731. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15732. }
  15733. if (dataType == undefined) {
  15734. return null;
  15735. }
  15736. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15737. var keys = [];
  15738. keys.push({ frame: 0, value: from });
  15739. keys.push({ frame: totalFrame, value: to });
  15740. animation.setKeys(keys);
  15741. mesh.animations.push(animation);
  15742. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15743. };
  15744. // Methods
  15745. Animation.prototype.isStopped = function () {
  15746. return this._stopped;
  15747. };
  15748. Animation.prototype.getKeys = function () {
  15749. return this._keys;
  15750. };
  15751. Animation.prototype.getEasingFunction = function () {
  15752. return this._easingFunction;
  15753. };
  15754. Animation.prototype.setEasingFunction = function (easingFunction) {
  15755. this._easingFunction = easingFunction;
  15756. };
  15757. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15758. return startValue + (endValue - startValue) * gradient;
  15759. };
  15760. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15761. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15762. };
  15763. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15764. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15765. };
  15766. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15767. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15768. };
  15769. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15770. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15771. };
  15772. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15773. var startScale = new BABYLON.Vector3(0, 0, 0);
  15774. var startRotation = new BABYLON.Quaternion();
  15775. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15776. startValue.decompose(startScale, startRotation, startTranslation);
  15777. var endScale = new BABYLON.Vector3(0, 0, 0);
  15778. var endRotation = new BABYLON.Quaternion();
  15779. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15780. endValue.decompose(endScale, endRotation, endTranslation);
  15781. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15782. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15783. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15784. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15785. return result;
  15786. };
  15787. Animation.prototype.clone = function () {
  15788. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15789. clone.setKeys(this._keys);
  15790. return clone;
  15791. };
  15792. Animation.prototype.setKeys = function (values) {
  15793. this._keys = values.slice(0);
  15794. this._offsetsCache = {};
  15795. this._highLimitsCache = {};
  15796. };
  15797. Animation.prototype._getKeyValue = function (value) {
  15798. if (typeof value === "function") {
  15799. return value();
  15800. }
  15801. return value;
  15802. };
  15803. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15804. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15805. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15806. }
  15807. this.currentFrame = currentFrame;
  15808. for (var key = 0; key < this._keys.length; key++) {
  15809. // for each frame, we need the key just before the frame superior
  15810. if (this._keys[key + 1].frame >= currentFrame) {
  15811. var startValue = this._getKeyValue(this._keys[key].value);
  15812. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15813. // gradient : percent of currentFrame between the frame inf and the frame sup
  15814. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15815. // check for easingFunction and correction of gradient
  15816. if (this._easingFunction != null) {
  15817. gradient = this._easingFunction.ease(gradient);
  15818. }
  15819. switch (this.dataType) {
  15820. case Animation.ANIMATIONTYPE_FLOAT:
  15821. switch (loopMode) {
  15822. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15823. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15824. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15825. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15826. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15827. }
  15828. break;
  15829. case Animation.ANIMATIONTYPE_QUATERNION:
  15830. var quaternion = null;
  15831. switch (loopMode) {
  15832. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15833. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15834. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15835. break;
  15836. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15837. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15838. break;
  15839. }
  15840. return quaternion;
  15841. case Animation.ANIMATIONTYPE_VECTOR3:
  15842. switch (loopMode) {
  15843. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15844. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15845. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15846. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15847. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15848. }
  15849. case Animation.ANIMATIONTYPE_VECTOR2:
  15850. switch (loopMode) {
  15851. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15852. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15853. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15854. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15855. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15856. }
  15857. case Animation.ANIMATIONTYPE_COLOR3:
  15858. switch (loopMode) {
  15859. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15860. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15861. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15862. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15863. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15864. }
  15865. case Animation.ANIMATIONTYPE_MATRIX:
  15866. switch (loopMode) {
  15867. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15868. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15869. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15870. return startValue;
  15871. }
  15872. default:
  15873. break;
  15874. }
  15875. break;
  15876. }
  15877. }
  15878. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15879. };
  15880. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15881. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15882. this._stopped = true;
  15883. return false;
  15884. }
  15885. var returnValue = true;
  15886. // Adding a start key at frame 0 if missing
  15887. if (this._keys[0].frame !== 0) {
  15888. var newKey = { frame: 0, value: this._keys[0].value };
  15889. this._keys.splice(0, 0, newKey);
  15890. }
  15891. // Check limits
  15892. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15893. from = this._keys[0].frame;
  15894. }
  15895. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15896. to = this._keys[this._keys.length - 1].frame;
  15897. }
  15898. // Compute ratio
  15899. var range = to - from;
  15900. var offsetValue;
  15901. // ratio represents the frame delta between from and to
  15902. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15903. var highLimitValue = 0;
  15904. if (ratio > range && !loop) {
  15905. returnValue = false;
  15906. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15907. }
  15908. else {
  15909. // Get max value if required
  15910. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15911. var keyOffset = to.toString() + from.toString();
  15912. if (!this._offsetsCache[keyOffset]) {
  15913. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15914. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15915. switch (this.dataType) {
  15916. case Animation.ANIMATIONTYPE_FLOAT:
  15917. this._offsetsCache[keyOffset] = toValue - fromValue;
  15918. break;
  15919. case Animation.ANIMATIONTYPE_QUATERNION:
  15920. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15921. break;
  15922. case Animation.ANIMATIONTYPE_VECTOR3:
  15923. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15924. case Animation.ANIMATIONTYPE_VECTOR2:
  15925. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15926. case Animation.ANIMATIONTYPE_COLOR3:
  15927. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15928. default:
  15929. break;
  15930. }
  15931. this._highLimitsCache[keyOffset] = toValue;
  15932. }
  15933. highLimitValue = this._highLimitsCache[keyOffset];
  15934. offsetValue = this._offsetsCache[keyOffset];
  15935. }
  15936. }
  15937. if (offsetValue === undefined) {
  15938. switch (this.dataType) {
  15939. case Animation.ANIMATIONTYPE_FLOAT:
  15940. offsetValue = 0;
  15941. break;
  15942. case Animation.ANIMATIONTYPE_QUATERNION:
  15943. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15944. break;
  15945. case Animation.ANIMATIONTYPE_VECTOR3:
  15946. offsetValue = BABYLON.Vector3.Zero();
  15947. break;
  15948. case Animation.ANIMATIONTYPE_VECTOR2:
  15949. offsetValue = BABYLON.Vector2.Zero();
  15950. break;
  15951. case Animation.ANIMATIONTYPE_COLOR3:
  15952. offsetValue = BABYLON.Color3.Black();
  15953. }
  15954. }
  15955. // Compute value
  15956. var repeatCount = (ratio / range) >> 0;
  15957. var currentFrame = returnValue ? from + ratio % range : to;
  15958. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15959. // Set value
  15960. if (this.targetPropertyPath.length > 1) {
  15961. var property = this._target[this.targetPropertyPath[0]];
  15962. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15963. property = property[this.targetPropertyPath[index]];
  15964. }
  15965. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15966. }
  15967. else {
  15968. this._target[this.targetPropertyPath[0]] = currentValue;
  15969. }
  15970. if (this._target.markAsDirty) {
  15971. this._target.markAsDirty(this.targetProperty);
  15972. }
  15973. if (!returnValue) {
  15974. this._stopped = true;
  15975. }
  15976. return returnValue;
  15977. };
  15978. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15979. get: function () {
  15980. return Animation._ANIMATIONTYPE_FLOAT;
  15981. },
  15982. enumerable: true,
  15983. configurable: true
  15984. });
  15985. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15986. get: function () {
  15987. return Animation._ANIMATIONTYPE_VECTOR3;
  15988. },
  15989. enumerable: true,
  15990. configurable: true
  15991. });
  15992. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15993. get: function () {
  15994. return Animation._ANIMATIONTYPE_VECTOR2;
  15995. },
  15996. enumerable: true,
  15997. configurable: true
  15998. });
  15999. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16000. get: function () {
  16001. return Animation._ANIMATIONTYPE_QUATERNION;
  16002. },
  16003. enumerable: true,
  16004. configurable: true
  16005. });
  16006. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16007. get: function () {
  16008. return Animation._ANIMATIONTYPE_MATRIX;
  16009. },
  16010. enumerable: true,
  16011. configurable: true
  16012. });
  16013. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16014. get: function () {
  16015. return Animation._ANIMATIONTYPE_COLOR3;
  16016. },
  16017. enumerable: true,
  16018. configurable: true
  16019. });
  16020. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16021. get: function () {
  16022. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16023. },
  16024. enumerable: true,
  16025. configurable: true
  16026. });
  16027. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16028. get: function () {
  16029. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16030. },
  16031. enumerable: true,
  16032. configurable: true
  16033. });
  16034. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16035. get: function () {
  16036. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16037. },
  16038. enumerable: true,
  16039. configurable: true
  16040. });
  16041. // Statics
  16042. Animation._ANIMATIONTYPE_FLOAT = 0;
  16043. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16044. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16045. Animation._ANIMATIONTYPE_MATRIX = 3;
  16046. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16047. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16048. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16049. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16050. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16051. return Animation;
  16052. })();
  16053. BABYLON.Animation = Animation;
  16054. })(BABYLON || (BABYLON = {}));
  16055. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16056. (function (BABYLON) {
  16057. var Animatable = (function () {
  16058. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16059. if (fromFrame === void 0) { fromFrame = 0; }
  16060. if (toFrame === void 0) { toFrame = 100; }
  16061. if (loopAnimation === void 0) { loopAnimation = false; }
  16062. if (speedRatio === void 0) { speedRatio = 1.0; }
  16063. this.target = target;
  16064. this.fromFrame = fromFrame;
  16065. this.toFrame = toFrame;
  16066. this.loopAnimation = loopAnimation;
  16067. this.speedRatio = speedRatio;
  16068. this.onAnimationEnd = onAnimationEnd;
  16069. this._animations = new Array();
  16070. this._paused = false;
  16071. this.animationStarted = false;
  16072. if (animations) {
  16073. this.appendAnimations(target, animations);
  16074. }
  16075. this._scene = scene;
  16076. scene._activeAnimatables.push(this);
  16077. }
  16078. // Methods
  16079. Animatable.prototype.appendAnimations = function (target, animations) {
  16080. for (var index = 0; index < animations.length; index++) {
  16081. var animation = animations[index];
  16082. animation._target = target;
  16083. this._animations.push(animation);
  16084. }
  16085. };
  16086. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16087. var animations = this._animations;
  16088. for (var index = 0; index < animations.length; index++) {
  16089. if (animations[index].targetProperty === property) {
  16090. return animations[index];
  16091. }
  16092. }
  16093. return null;
  16094. };
  16095. Animatable.prototype.pause = function () {
  16096. if (this._paused) {
  16097. return;
  16098. }
  16099. this._paused = true;
  16100. };
  16101. Animatable.prototype.restart = function () {
  16102. this._paused = false;
  16103. };
  16104. Animatable.prototype.stop = function () {
  16105. var index = this._scene._activeAnimatables.indexOf(this);
  16106. if (index > -1) {
  16107. this._scene._activeAnimatables.splice(index, 1);
  16108. }
  16109. if (this.onAnimationEnd) {
  16110. this.onAnimationEnd();
  16111. }
  16112. };
  16113. Animatable.prototype._animate = function (delay) {
  16114. if (this._paused) {
  16115. if (!this._pausedDelay) {
  16116. this._pausedDelay = delay;
  16117. }
  16118. return true;
  16119. }
  16120. if (!this._localDelayOffset) {
  16121. this._localDelayOffset = delay;
  16122. }
  16123. else if (this._pausedDelay) {
  16124. this._localDelayOffset += delay - this._pausedDelay;
  16125. this._pausedDelay = null;
  16126. }
  16127. // Animating
  16128. var running = false;
  16129. var animations = this._animations;
  16130. for (var index = 0; index < animations.length; index++) {
  16131. var animation = animations[index];
  16132. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16133. running = running || isRunning;
  16134. }
  16135. if (!running && this.onAnimationEnd) {
  16136. this.onAnimationEnd();
  16137. }
  16138. return running;
  16139. };
  16140. return Animatable;
  16141. })();
  16142. BABYLON.Animatable = Animatable;
  16143. })(BABYLON || (BABYLON = {}));
  16144. //# sourceMappingURL=babylon.animatable.js.map
  16145. var BABYLON;
  16146. (function (BABYLON) {
  16147. var EasingFunction = (function () {
  16148. function EasingFunction() {
  16149. // Properties
  16150. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16151. }
  16152. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16153. get: function () {
  16154. return EasingFunction._EASINGMODE_EASEIN;
  16155. },
  16156. enumerable: true,
  16157. configurable: true
  16158. });
  16159. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16160. get: function () {
  16161. return EasingFunction._EASINGMODE_EASEOUT;
  16162. },
  16163. enumerable: true,
  16164. configurable: true
  16165. });
  16166. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16167. get: function () {
  16168. return EasingFunction._EASINGMODE_EASEINOUT;
  16169. },
  16170. enumerable: true,
  16171. configurable: true
  16172. });
  16173. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16174. var n = Math.min(Math.max(easingMode, 0), 2);
  16175. this._easingMode = n;
  16176. };
  16177. EasingFunction.prototype.getEasingMode = function () {
  16178. return this._easingMode;
  16179. };
  16180. EasingFunction.prototype.easeInCore = function (gradient) {
  16181. throw new Error('You must implement this method');
  16182. };
  16183. EasingFunction.prototype.ease = function (gradient) {
  16184. switch (this._easingMode) {
  16185. case EasingFunction.EASINGMODE_EASEIN:
  16186. return this.easeInCore(gradient);
  16187. case EasingFunction.EASINGMODE_EASEOUT:
  16188. return (1 - this.easeInCore(1 - gradient));
  16189. }
  16190. if (gradient >= 0.5) {
  16191. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16192. }
  16193. return (this.easeInCore(gradient * 2) * 0.5);
  16194. };
  16195. //Statics
  16196. EasingFunction._EASINGMODE_EASEIN = 0;
  16197. EasingFunction._EASINGMODE_EASEOUT = 1;
  16198. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16199. return EasingFunction;
  16200. })();
  16201. BABYLON.EasingFunction = EasingFunction;
  16202. var CircleEase = (function (_super) {
  16203. __extends(CircleEase, _super);
  16204. function CircleEase() {
  16205. _super.apply(this, arguments);
  16206. }
  16207. CircleEase.prototype.easeInCore = function (gradient) {
  16208. gradient = Math.max(0, Math.min(1, gradient));
  16209. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16210. };
  16211. return CircleEase;
  16212. })(EasingFunction);
  16213. BABYLON.CircleEase = CircleEase;
  16214. var BackEase = (function (_super) {
  16215. __extends(BackEase, _super);
  16216. function BackEase(amplitude) {
  16217. if (amplitude === void 0) { amplitude = 1; }
  16218. _super.call(this);
  16219. this.amplitude = amplitude;
  16220. }
  16221. BackEase.prototype.easeInCore = function (gradient) {
  16222. var num = Math.max(0, this.amplitude);
  16223. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16224. };
  16225. return BackEase;
  16226. })(EasingFunction);
  16227. BABYLON.BackEase = BackEase;
  16228. var BounceEase = (function (_super) {
  16229. __extends(BounceEase, _super);
  16230. function BounceEase(bounces, bounciness) {
  16231. if (bounces === void 0) { bounces = 3; }
  16232. if (bounciness === void 0) { bounciness = 2; }
  16233. _super.call(this);
  16234. this.bounces = bounces;
  16235. this.bounciness = bounciness;
  16236. }
  16237. BounceEase.prototype.easeInCore = function (gradient) {
  16238. var y = Math.max(0.0, this.bounces);
  16239. var bounciness = this.bounciness;
  16240. if (bounciness <= 1.0) {
  16241. bounciness = 1.001;
  16242. }
  16243. var num9 = Math.pow(bounciness, y);
  16244. var num5 = 1.0 - bounciness;
  16245. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16246. var num15 = gradient * num4;
  16247. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16248. var num3 = Math.floor(num65);
  16249. var num13 = num3 + 1.0;
  16250. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16251. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16252. var num7 = (num8 + num12) * 0.5;
  16253. var num6 = gradient - num7;
  16254. var num2 = num7 - num8;
  16255. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16256. };
  16257. return BounceEase;
  16258. })(EasingFunction);
  16259. BABYLON.BounceEase = BounceEase;
  16260. var CubicEase = (function (_super) {
  16261. __extends(CubicEase, _super);
  16262. function CubicEase() {
  16263. _super.apply(this, arguments);
  16264. }
  16265. CubicEase.prototype.easeInCore = function (gradient) {
  16266. return (gradient * gradient * gradient);
  16267. };
  16268. return CubicEase;
  16269. })(EasingFunction);
  16270. BABYLON.CubicEase = CubicEase;
  16271. var ElasticEase = (function (_super) {
  16272. __extends(ElasticEase, _super);
  16273. function ElasticEase(oscillations, springiness) {
  16274. if (oscillations === void 0) { oscillations = 3; }
  16275. if (springiness === void 0) { springiness = 3; }
  16276. _super.call(this);
  16277. this.oscillations = oscillations;
  16278. this.springiness = springiness;
  16279. }
  16280. ElasticEase.prototype.easeInCore = function (gradient) {
  16281. var num2;
  16282. var num3 = Math.max(0.0, this.oscillations);
  16283. var num = Math.max(0.0, this.springiness);
  16284. if (num == 0) {
  16285. num2 = gradient;
  16286. }
  16287. else {
  16288. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16289. }
  16290. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16291. };
  16292. return ElasticEase;
  16293. })(EasingFunction);
  16294. BABYLON.ElasticEase = ElasticEase;
  16295. var ExponentialEase = (function (_super) {
  16296. __extends(ExponentialEase, _super);
  16297. function ExponentialEase(exponent) {
  16298. if (exponent === void 0) { exponent = 2; }
  16299. _super.call(this);
  16300. this.exponent = exponent;
  16301. }
  16302. ExponentialEase.prototype.easeInCore = function (gradient) {
  16303. if (this.exponent <= 0) {
  16304. return gradient;
  16305. }
  16306. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16307. };
  16308. return ExponentialEase;
  16309. })(EasingFunction);
  16310. BABYLON.ExponentialEase = ExponentialEase;
  16311. var PowerEase = (function (_super) {
  16312. __extends(PowerEase, _super);
  16313. function PowerEase(power) {
  16314. if (power === void 0) { power = 2; }
  16315. _super.call(this);
  16316. this.power = power;
  16317. }
  16318. PowerEase.prototype.easeInCore = function (gradient) {
  16319. var y = Math.max(0.0, this.power);
  16320. return Math.pow(gradient, y);
  16321. };
  16322. return PowerEase;
  16323. })(EasingFunction);
  16324. BABYLON.PowerEase = PowerEase;
  16325. var QuadraticEase = (function (_super) {
  16326. __extends(QuadraticEase, _super);
  16327. function QuadraticEase() {
  16328. _super.apply(this, arguments);
  16329. }
  16330. QuadraticEase.prototype.easeInCore = function (gradient) {
  16331. return (gradient * gradient);
  16332. };
  16333. return QuadraticEase;
  16334. })(EasingFunction);
  16335. BABYLON.QuadraticEase = QuadraticEase;
  16336. var QuarticEase = (function (_super) {
  16337. __extends(QuarticEase, _super);
  16338. function QuarticEase() {
  16339. _super.apply(this, arguments);
  16340. }
  16341. QuarticEase.prototype.easeInCore = function (gradient) {
  16342. return (gradient * gradient * gradient * gradient);
  16343. };
  16344. return QuarticEase;
  16345. })(EasingFunction);
  16346. BABYLON.QuarticEase = QuarticEase;
  16347. var QuinticEase = (function (_super) {
  16348. __extends(QuinticEase, _super);
  16349. function QuinticEase() {
  16350. _super.apply(this, arguments);
  16351. }
  16352. QuinticEase.prototype.easeInCore = function (gradient) {
  16353. return (gradient * gradient * gradient * gradient * gradient);
  16354. };
  16355. return QuinticEase;
  16356. })(EasingFunction);
  16357. BABYLON.QuinticEase = QuinticEase;
  16358. var SineEase = (function (_super) {
  16359. __extends(SineEase, _super);
  16360. function SineEase() {
  16361. _super.apply(this, arguments);
  16362. }
  16363. SineEase.prototype.easeInCore = function (gradient) {
  16364. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16365. };
  16366. return SineEase;
  16367. })(EasingFunction);
  16368. BABYLON.SineEase = SineEase;
  16369. var BezierCurveEase = (function (_super) {
  16370. __extends(BezierCurveEase, _super);
  16371. function BezierCurveEase(x1, y1, x2, y2) {
  16372. if (x1 === void 0) { x1 = 0; }
  16373. if (y1 === void 0) { y1 = 0; }
  16374. if (x2 === void 0) { x2 = 1; }
  16375. if (y2 === void 0) { y2 = 1; }
  16376. _super.call(this);
  16377. this.x1 = x1;
  16378. this.y1 = y1;
  16379. this.x2 = x2;
  16380. this.y2 = y2;
  16381. }
  16382. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16383. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16384. };
  16385. return BezierCurveEase;
  16386. })(EasingFunction);
  16387. BABYLON.BezierCurveEase = BezierCurveEase;
  16388. })(BABYLON || (BABYLON = {}));
  16389. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16390. (function (BABYLON) {
  16391. var Octree = (function () {
  16392. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16393. if (maxDepth === void 0) { maxDepth = 2; }
  16394. this.maxDepth = maxDepth;
  16395. this.dynamicContent = new Array();
  16396. this._maxBlockCapacity = maxBlockCapacity || 64;
  16397. this._selectionContent = new BABYLON.SmartArray(1024);
  16398. this._creationFunc = creationFunc;
  16399. }
  16400. // Methods
  16401. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16402. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16403. };
  16404. Octree.prototype.addMesh = function (entry) {
  16405. for (var index = 0; index < this.blocks.length; index++) {
  16406. var block = this.blocks[index];
  16407. block.addEntry(entry);
  16408. }
  16409. };
  16410. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16411. this._selectionContent.reset();
  16412. for (var index = 0; index < this.blocks.length; index++) {
  16413. var block = this.blocks[index];
  16414. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16415. }
  16416. if (allowDuplicate) {
  16417. this._selectionContent.concat(this.dynamicContent);
  16418. }
  16419. else {
  16420. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16421. }
  16422. return this._selectionContent;
  16423. };
  16424. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16425. this._selectionContent.reset();
  16426. for (var index = 0; index < this.blocks.length; index++) {
  16427. var block = this.blocks[index];
  16428. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16429. }
  16430. if (allowDuplicate) {
  16431. this._selectionContent.concat(this.dynamicContent);
  16432. }
  16433. else {
  16434. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16435. }
  16436. return this._selectionContent;
  16437. };
  16438. Octree.prototype.intersectsRay = function (ray) {
  16439. this._selectionContent.reset();
  16440. for (var index = 0; index < this.blocks.length; index++) {
  16441. var block = this.blocks[index];
  16442. block.intersectsRay(ray, this._selectionContent);
  16443. }
  16444. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16445. return this._selectionContent;
  16446. };
  16447. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16448. target.blocks = new Array();
  16449. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16450. for (var x = 0; x < 2; x++) {
  16451. for (var y = 0; y < 2; y++) {
  16452. for (var z = 0; z < 2; z++) {
  16453. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16454. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16455. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16456. block.addEntries(entries);
  16457. target.blocks.push(block);
  16458. }
  16459. }
  16460. }
  16461. };
  16462. Octree.CreationFuncForMeshes = function (entry, block) {
  16463. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16464. block.entries.push(entry);
  16465. }
  16466. };
  16467. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16468. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16469. block.entries.push(entry);
  16470. }
  16471. };
  16472. return Octree;
  16473. })();
  16474. BABYLON.Octree = Octree;
  16475. })(BABYLON || (BABYLON = {}));
  16476. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16477. (function (BABYLON) {
  16478. var OctreeBlock = (function () {
  16479. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16480. this.entries = new Array();
  16481. this._boundingVectors = new Array();
  16482. this._capacity = capacity;
  16483. this._depth = depth;
  16484. this._maxDepth = maxDepth;
  16485. this._creationFunc = creationFunc;
  16486. this._minPoint = minPoint;
  16487. this._maxPoint = maxPoint;
  16488. this._boundingVectors.push(minPoint.clone());
  16489. this._boundingVectors.push(maxPoint.clone());
  16490. this._boundingVectors.push(minPoint.clone());
  16491. this._boundingVectors[2].x = maxPoint.x;
  16492. this._boundingVectors.push(minPoint.clone());
  16493. this._boundingVectors[3].y = maxPoint.y;
  16494. this._boundingVectors.push(minPoint.clone());
  16495. this._boundingVectors[4].z = maxPoint.z;
  16496. this._boundingVectors.push(maxPoint.clone());
  16497. this._boundingVectors[5].z = minPoint.z;
  16498. this._boundingVectors.push(maxPoint.clone());
  16499. this._boundingVectors[6].x = minPoint.x;
  16500. this._boundingVectors.push(maxPoint.clone());
  16501. this._boundingVectors[7].y = minPoint.y;
  16502. }
  16503. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16504. // Property
  16505. get: function () {
  16506. return this._capacity;
  16507. },
  16508. enumerable: true,
  16509. configurable: true
  16510. });
  16511. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16512. get: function () {
  16513. return this._minPoint;
  16514. },
  16515. enumerable: true,
  16516. configurable: true
  16517. });
  16518. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16519. get: function () {
  16520. return this._maxPoint;
  16521. },
  16522. enumerable: true,
  16523. configurable: true
  16524. });
  16525. // Methods
  16526. OctreeBlock.prototype.addEntry = function (entry) {
  16527. if (this.blocks) {
  16528. for (var index = 0; index < this.blocks.length; index++) {
  16529. var block = this.blocks[index];
  16530. block.addEntry(entry);
  16531. }
  16532. return;
  16533. }
  16534. this._creationFunc(entry, this);
  16535. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16536. this.createInnerBlocks();
  16537. }
  16538. };
  16539. OctreeBlock.prototype.addEntries = function (entries) {
  16540. for (var index = 0; index < entries.length; index++) {
  16541. var mesh = entries[index];
  16542. this.addEntry(mesh);
  16543. }
  16544. };
  16545. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16546. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16547. if (this.blocks) {
  16548. for (var index = 0; index < this.blocks.length; index++) {
  16549. var block = this.blocks[index];
  16550. block.select(frustumPlanes, selection, allowDuplicate);
  16551. }
  16552. return;
  16553. }
  16554. if (allowDuplicate) {
  16555. selection.concat(this.entries);
  16556. }
  16557. else {
  16558. selection.concatWithNoDuplicate(this.entries);
  16559. }
  16560. }
  16561. };
  16562. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16563. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16564. if (this.blocks) {
  16565. for (var index = 0; index < this.blocks.length; index++) {
  16566. var block = this.blocks[index];
  16567. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16568. }
  16569. return;
  16570. }
  16571. if (allowDuplicate) {
  16572. selection.concat(this.entries);
  16573. }
  16574. else {
  16575. selection.concatWithNoDuplicate(this.entries);
  16576. }
  16577. }
  16578. };
  16579. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16580. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16581. if (this.blocks) {
  16582. for (var index = 0; index < this.blocks.length; index++) {
  16583. var block = this.blocks[index];
  16584. block.intersectsRay(ray, selection);
  16585. }
  16586. return;
  16587. }
  16588. selection.concatWithNoDuplicate(this.entries);
  16589. }
  16590. };
  16591. OctreeBlock.prototype.createInnerBlocks = function () {
  16592. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16593. };
  16594. return OctreeBlock;
  16595. })();
  16596. BABYLON.OctreeBlock = OctreeBlock;
  16597. })(BABYLON || (BABYLON = {}));
  16598. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16599. (function (BABYLON) {
  16600. var Bone = (function () {
  16601. function Bone(name, skeleton, parentBone, matrix) {
  16602. this.name = name;
  16603. this.children = new Array();
  16604. this.animations = new Array();
  16605. this._worldTransform = new BABYLON.Matrix();
  16606. this._absoluteTransform = new BABYLON.Matrix();
  16607. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16608. this._skeleton = skeleton;
  16609. this._matrix = matrix;
  16610. this._baseMatrix = matrix;
  16611. skeleton.bones.push(this);
  16612. if (parentBone) {
  16613. this._parent = parentBone;
  16614. parentBone.children.push(this);
  16615. }
  16616. else {
  16617. this._parent = null;
  16618. }
  16619. this._updateDifferenceMatrix();
  16620. }
  16621. // Members
  16622. Bone.prototype.getParent = function () {
  16623. return this._parent;
  16624. };
  16625. Bone.prototype.getLocalMatrix = function () {
  16626. return this._matrix;
  16627. };
  16628. Bone.prototype.getBaseMatrix = function () {
  16629. return this._baseMatrix;
  16630. };
  16631. Bone.prototype.getWorldMatrix = function () {
  16632. return this._worldTransform;
  16633. };
  16634. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16635. return this._invertedAbsoluteTransform;
  16636. };
  16637. Bone.prototype.getAbsoluteMatrix = function () {
  16638. var matrix = this._matrix.clone();
  16639. var parent = this._parent;
  16640. while (parent) {
  16641. matrix = matrix.multiply(parent.getLocalMatrix());
  16642. parent = parent.getParent();
  16643. }
  16644. return matrix;
  16645. };
  16646. // Methods
  16647. Bone.prototype.updateMatrix = function (matrix) {
  16648. this._matrix = matrix;
  16649. this._skeleton._markAsDirty();
  16650. this._updateDifferenceMatrix();
  16651. };
  16652. Bone.prototype._updateDifferenceMatrix = function () {
  16653. if (this._parent) {
  16654. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16655. }
  16656. else {
  16657. this._absoluteTransform.copyFrom(this._matrix);
  16658. }
  16659. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16660. for (var index = 0; index < this.children.length; index++) {
  16661. this.children[index]._updateDifferenceMatrix();
  16662. }
  16663. };
  16664. Bone.prototype.markAsDirty = function () {
  16665. this._skeleton._markAsDirty();
  16666. };
  16667. return Bone;
  16668. })();
  16669. BABYLON.Bone = Bone;
  16670. })(BABYLON || (BABYLON = {}));
  16671. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16672. (function (BABYLON) {
  16673. var Skeleton = (function () {
  16674. function Skeleton(name, id, scene) {
  16675. this.name = name;
  16676. this.id = id;
  16677. this.bones = new Array();
  16678. this._isDirty = true;
  16679. this._identity = BABYLON.Matrix.Identity();
  16680. this.bones = [];
  16681. this._scene = scene;
  16682. scene.skeletons.push(this);
  16683. }
  16684. // Members
  16685. Skeleton.prototype.getTransformMatrices = function () {
  16686. return this._transformMatrices;
  16687. };
  16688. // Methods
  16689. Skeleton.prototype._markAsDirty = function () {
  16690. this._isDirty = true;
  16691. };
  16692. Skeleton.prototype.prepare = function () {
  16693. if (!this._isDirty) {
  16694. return;
  16695. }
  16696. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16697. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16698. }
  16699. for (var index = 0; index < this.bones.length; index++) {
  16700. var bone = this.bones[index];
  16701. var parentBone = bone.getParent();
  16702. if (parentBone) {
  16703. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16704. }
  16705. else {
  16706. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16707. }
  16708. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16709. }
  16710. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16711. this._isDirty = false;
  16712. this._scene._activeBones += this.bones.length;
  16713. };
  16714. Skeleton.prototype.getAnimatables = function () {
  16715. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16716. this._animatables = [];
  16717. for (var index = 0; index < this.bones.length; index++) {
  16718. this._animatables.push(this.bones[index]);
  16719. }
  16720. }
  16721. return this._animatables;
  16722. };
  16723. Skeleton.prototype.clone = function (name, id) {
  16724. var result = new Skeleton(name, id || name, this._scene);
  16725. for (var index = 0; index < this.bones.length; index++) {
  16726. var source = this.bones[index];
  16727. var parentBone = null;
  16728. if (source.getParent()) {
  16729. var parentIndex = this.bones.indexOf(source.getParent());
  16730. parentBone = result.bones[parentIndex];
  16731. }
  16732. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16733. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16734. }
  16735. return result;
  16736. };
  16737. return Skeleton;
  16738. })();
  16739. BABYLON.Skeleton = Skeleton;
  16740. })(BABYLON || (BABYLON = {}));
  16741. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16742. (function (BABYLON) {
  16743. var PostProcess = (function () {
  16744. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  16746. this.name = name;
  16747. this.width = -1;
  16748. this.height = -1;
  16749. this._reusable = false;
  16750. this._textures = new BABYLON.SmartArray(2);
  16751. this._currentRenderTextureInd = 0;
  16752. if (camera != null) {
  16753. this._camera = camera;
  16754. this._scene = camera.getScene();
  16755. camera.attachPostProcess(this);
  16756. this._engine = this._scene.getEngine();
  16757. }
  16758. else {
  16759. this._engine = engine;
  16760. }
  16761. this._renderRatio = ratio;
  16762. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16763. this._reusable = reusable || false;
  16764. samplers = samplers || [];
  16765. samplers.push("textureSampler");
  16766. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16767. }
  16768. PostProcess.prototype.isReusable = function () {
  16769. return this._reusable;
  16770. };
  16771. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16772. camera = camera || this._camera;
  16773. var scene = camera.getScene();
  16774. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16775. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16776. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16777. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16778. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16779. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16780. if (this._textures.length > 0) {
  16781. for (var i = 0; i < this._textures.length; i++) {
  16782. this._engine._releaseTexture(this._textures.data[i]);
  16783. }
  16784. this._textures.reset();
  16785. }
  16786. this.width = desiredWidth;
  16787. this.height = desiredHeight;
  16788. 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 }));
  16789. if (this._reusable) {
  16790. 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 }));
  16791. }
  16792. if (this.onSizeChanged) {
  16793. this.onSizeChanged();
  16794. }
  16795. }
  16796. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16797. if (this.onActivate) {
  16798. this.onActivate(camera);
  16799. }
  16800. // Clear
  16801. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16802. if (this._reusable) {
  16803. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16804. }
  16805. };
  16806. PostProcess.prototype.apply = function () {
  16807. // Check
  16808. if (!this._effect.isReady())
  16809. return null;
  16810. // States
  16811. this._engine.enableEffect(this._effect);
  16812. this._engine.setState(false);
  16813. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16814. this._engine.setDepthBuffer(false);
  16815. this._engine.setDepthWrite(false);
  16816. // Texture
  16817. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16818. // Parameters
  16819. if (this.onApply) {
  16820. this.onApply(this._effect);
  16821. }
  16822. return this._effect;
  16823. };
  16824. PostProcess.prototype.dispose = function (camera) {
  16825. camera = camera || this._camera;
  16826. if (this._textures.length > 0) {
  16827. for (var i = 0; i < this._textures.length; i++) {
  16828. this._engine._releaseTexture(this._textures.data[i]);
  16829. }
  16830. this._textures.reset();
  16831. }
  16832. if (!camera) {
  16833. return;
  16834. }
  16835. camera.detachPostProcess(this);
  16836. var index = camera._postProcesses.indexOf(this);
  16837. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16838. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16839. }
  16840. };
  16841. return PostProcess;
  16842. })();
  16843. BABYLON.PostProcess = PostProcess;
  16844. })(BABYLON || (BABYLON = {}));
  16845. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16846. (function (BABYLON) {
  16847. var PostProcessManager = (function () {
  16848. function PostProcessManager(scene) {
  16849. this._vertexDeclaration = [2];
  16850. this._vertexStrideSize = 2 * 4;
  16851. this._scene = scene;
  16852. // VBO
  16853. var vertices = [];
  16854. vertices.push(1, 1);
  16855. vertices.push(-1, 1);
  16856. vertices.push(-1, -1);
  16857. vertices.push(1, -1);
  16858. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16859. // Indices
  16860. var indices = [];
  16861. indices.push(0);
  16862. indices.push(1);
  16863. indices.push(2);
  16864. indices.push(0);
  16865. indices.push(2);
  16866. indices.push(3);
  16867. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16868. }
  16869. // Methods
  16870. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16871. var postProcesses = this._scene.activeCamera._postProcesses;
  16872. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16873. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16874. return false;
  16875. }
  16876. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16877. return true;
  16878. };
  16879. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  16880. var engine = this._scene.getEngine();
  16881. for (var index = 0; index < postProcesses.length; index++) {
  16882. if (index < postProcesses.length - 1) {
  16883. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  16884. }
  16885. else {
  16886. if (targetTexture) {
  16887. engine.bindFramebuffer(targetTexture);
  16888. }
  16889. else {
  16890. engine.restoreDefaultFramebuffer();
  16891. }
  16892. }
  16893. var pp = postProcesses[index];
  16894. var effect = pp.apply();
  16895. if (effect) {
  16896. if (pp.onBeforeRender) {
  16897. pp.onBeforeRender(effect);
  16898. }
  16899. // VBOs
  16900. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16901. // Draw order
  16902. engine.draw(true, 0, 6);
  16903. }
  16904. }
  16905. // Restore depth buffer
  16906. engine.setDepthBuffer(true);
  16907. engine.setDepthWrite(true);
  16908. };
  16909. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  16910. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  16911. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16912. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16913. return;
  16914. }
  16915. var engine = this._scene.getEngine();
  16916. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16917. if (index < postProcessesTakenIndices.length - 1) {
  16918. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16919. }
  16920. else {
  16921. if (targetTexture) {
  16922. engine.bindFramebuffer(targetTexture);
  16923. }
  16924. else {
  16925. engine.restoreDefaultFramebuffer();
  16926. }
  16927. }
  16928. if (doNotPresent) {
  16929. break;
  16930. }
  16931. var pp = postProcesses[postProcessesTakenIndices[index]];
  16932. var effect = pp.apply();
  16933. if (effect) {
  16934. if (pp.onBeforeRender) {
  16935. pp.onBeforeRender(effect);
  16936. }
  16937. // VBOs
  16938. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16939. // Draw order
  16940. engine.draw(true, 0, 6);
  16941. }
  16942. }
  16943. // Restore depth buffer
  16944. engine.setDepthBuffer(true);
  16945. engine.setDepthWrite(true);
  16946. };
  16947. PostProcessManager.prototype.dispose = function () {
  16948. if (this._vertexBuffer) {
  16949. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16950. this._vertexBuffer = null;
  16951. }
  16952. if (this._indexBuffer) {
  16953. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16954. this._indexBuffer = null;
  16955. }
  16956. };
  16957. return PostProcessManager;
  16958. })();
  16959. BABYLON.PostProcessManager = PostProcessManager;
  16960. })(BABYLON || (BABYLON = {}));
  16961. //# sourceMappingURL=babylon.postProcessManager.js.map
  16962. var BABYLON;
  16963. (function (BABYLON) {
  16964. var PassPostProcess = (function (_super) {
  16965. __extends(PassPostProcess, _super);
  16966. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16967. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16968. }
  16969. return PassPostProcess;
  16970. })(BABYLON.PostProcess);
  16971. BABYLON.PassPostProcess = PassPostProcess;
  16972. })(BABYLON || (BABYLON = {}));
  16973. //# sourceMappingURL=babylon.passPostProcess.js.map
  16974. var BABYLON;
  16975. (function (BABYLON) {
  16976. var BlurPostProcess = (function (_super) {
  16977. __extends(BlurPostProcess, _super);
  16978. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16979. var _this = this;
  16980. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16981. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16982. this.direction = direction;
  16983. this.blurWidth = blurWidth;
  16984. this.onApply = function (effect) {
  16985. effect.setFloat2("screenSize", _this.width, _this.height);
  16986. effect.setVector2("direction", _this.direction);
  16987. effect.setFloat("blurWidth", _this.blurWidth);
  16988. };
  16989. }
  16990. return BlurPostProcess;
  16991. })(BABYLON.PostProcess);
  16992. BABYLON.BlurPostProcess = BlurPostProcess;
  16993. })(BABYLON || (BABYLON = {}));
  16994. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16995. var BABYLON;
  16996. (function (BABYLON) {
  16997. var FilterPostProcess = (function (_super) {
  16998. __extends(FilterPostProcess, _super);
  16999. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17000. var _this = this;
  17001. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17002. this.kernelMatrix = kernelMatrix;
  17003. this.onApply = function (effect) {
  17004. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17005. };
  17006. }
  17007. return FilterPostProcess;
  17008. })(BABYLON.PostProcess);
  17009. BABYLON.FilterPostProcess = FilterPostProcess;
  17010. })(BABYLON || (BABYLON = {}));
  17011. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17012. var BABYLON;
  17013. (function (BABYLON) {
  17014. var RefractionPostProcess = (function (_super) {
  17015. __extends(RefractionPostProcess, _super);
  17016. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17017. var _this = this;
  17018. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17019. this.color = color;
  17020. this.depth = depth;
  17021. this.colorLevel = colorLevel;
  17022. this.onActivate = function (cam) {
  17023. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17024. };
  17025. this.onApply = function (effect) {
  17026. effect.setColor3("baseColor", _this.color);
  17027. effect.setFloat("depth", _this.depth);
  17028. effect.setFloat("colorLevel", _this.colorLevel);
  17029. effect.setTexture("refractionSampler", _this._refRexture);
  17030. };
  17031. }
  17032. // Methods
  17033. RefractionPostProcess.prototype.dispose = function (camera) {
  17034. if (this._refRexture) {
  17035. this._refRexture.dispose();
  17036. }
  17037. _super.prototype.dispose.call(this, camera);
  17038. };
  17039. return RefractionPostProcess;
  17040. })(BABYLON.PostProcess);
  17041. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17042. })(BABYLON || (BABYLON = {}));
  17043. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17044. var BABYLON;
  17045. (function (BABYLON) {
  17046. var BlackAndWhitePostProcess = (function (_super) {
  17047. __extends(BlackAndWhitePostProcess, _super);
  17048. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17049. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17050. }
  17051. return BlackAndWhitePostProcess;
  17052. })(BABYLON.PostProcess);
  17053. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17054. })(BABYLON || (BABYLON = {}));
  17055. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17056. var BABYLON;
  17057. (function (BABYLON) {
  17058. var ConvolutionPostProcess = (function (_super) {
  17059. __extends(ConvolutionPostProcess, _super);
  17060. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17061. var _this = this;
  17062. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17063. this.kernel = kernel;
  17064. this.onApply = function (effect) {
  17065. effect.setFloat2("screenSize", _this.width, _this.height);
  17066. effect.setArray("kernel", _this.kernel);
  17067. };
  17068. }
  17069. // Statics
  17070. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17071. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17072. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17073. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17074. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17075. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17076. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17077. return ConvolutionPostProcess;
  17078. })(BABYLON.PostProcess);
  17079. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17080. })(BABYLON || (BABYLON = {}));
  17081. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17082. var BABYLON;
  17083. (function (BABYLON) {
  17084. var FxaaPostProcess = (function (_super) {
  17085. __extends(FxaaPostProcess, _super);
  17086. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17087. var _this = this;
  17088. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17089. this.onSizeChanged = function () {
  17090. _this.texelWidth = 1.0 / _this.width;
  17091. _this.texelHeight = 1.0 / _this.height;
  17092. };
  17093. this.onApply = function (effect) {
  17094. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17095. };
  17096. }
  17097. return FxaaPostProcess;
  17098. })(BABYLON.PostProcess);
  17099. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17100. })(BABYLON || (BABYLON = {}));
  17101. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17102. (function (BABYLON) {
  17103. var LensFlare = (function () {
  17104. function LensFlare(size, position, color, imgUrl, system) {
  17105. this.size = size;
  17106. this.position = position;
  17107. this.dispose = function () {
  17108. if (this.texture) {
  17109. this.texture.dispose();
  17110. }
  17111. // Remove from scene
  17112. var index = this._system.lensFlares.indexOf(this);
  17113. this._system.lensFlares.splice(index, 1);
  17114. };
  17115. this.color = color || new BABYLON.Color3(1, 1, 1);
  17116. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17117. this._system = system;
  17118. system.lensFlares.push(this);
  17119. }
  17120. return LensFlare;
  17121. })();
  17122. BABYLON.LensFlare = LensFlare;
  17123. })(BABYLON || (BABYLON = {}));
  17124. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17125. (function (BABYLON) {
  17126. var LensFlareSystem = (function () {
  17127. function LensFlareSystem(name, emitter, scene) {
  17128. this.name = name;
  17129. this.lensFlares = new Array();
  17130. this.borderLimit = 300;
  17131. this._vertexDeclaration = [2];
  17132. this._vertexStrideSize = 2 * 4;
  17133. this._isEnabled = true;
  17134. this._scene = scene;
  17135. this._emitter = emitter;
  17136. scene.lensFlareSystems.push(this);
  17137. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17138. // VBO
  17139. var vertices = [];
  17140. vertices.push(1, 1);
  17141. vertices.push(-1, 1);
  17142. vertices.push(-1, -1);
  17143. vertices.push(1, -1);
  17144. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17145. // Indices
  17146. var indices = [];
  17147. indices.push(0);
  17148. indices.push(1);
  17149. indices.push(2);
  17150. indices.push(0);
  17151. indices.push(2);
  17152. indices.push(3);
  17153. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17154. // Effects
  17155. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17156. }
  17157. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17158. get: function () {
  17159. return this._isEnabled;
  17160. },
  17161. set: function (value) {
  17162. this._isEnabled = value;
  17163. },
  17164. enumerable: true,
  17165. configurable: true
  17166. });
  17167. LensFlareSystem.prototype.getScene = function () {
  17168. return this._scene;
  17169. };
  17170. LensFlareSystem.prototype.getEmitter = function () {
  17171. return this._emitter;
  17172. };
  17173. LensFlareSystem.prototype.getEmitterPosition = function () {
  17174. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17175. };
  17176. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17177. var position = this.getEmitterPosition();
  17178. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17179. this._positionX = position.x;
  17180. this._positionY = position.y;
  17181. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17182. if (position.z > 0) {
  17183. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17184. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17185. return true;
  17186. }
  17187. }
  17188. return false;
  17189. };
  17190. LensFlareSystem.prototype._isVisible = function () {
  17191. if (!this._isEnabled) {
  17192. return false;
  17193. }
  17194. var emitterPosition = this.getEmitterPosition();
  17195. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17196. var distance = direction.length();
  17197. direction.normalize();
  17198. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17199. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17200. return !pickInfo.hit || pickInfo.distance > distance;
  17201. };
  17202. LensFlareSystem.prototype.render = function () {
  17203. if (!this._effect.isReady())
  17204. return false;
  17205. var engine = this._scene.getEngine();
  17206. var viewport = this._scene.activeCamera.viewport;
  17207. var globalViewport = viewport.toGlobal(engine);
  17208. // Position
  17209. if (!this.computeEffectivePosition(globalViewport)) {
  17210. return false;
  17211. }
  17212. // Visibility
  17213. if (!this._isVisible()) {
  17214. return false;
  17215. }
  17216. // Intensity
  17217. var awayX;
  17218. var awayY;
  17219. if (this._positionX < this.borderLimit + globalViewport.x) {
  17220. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17221. }
  17222. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17223. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17224. }
  17225. else {
  17226. awayX = 0;
  17227. }
  17228. if (this._positionY < this.borderLimit + globalViewport.y) {
  17229. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17230. }
  17231. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17232. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17233. }
  17234. else {
  17235. awayY = 0;
  17236. }
  17237. var away = (awayX > awayY) ? awayX : awayY;
  17238. if (away > this.borderLimit) {
  17239. away = this.borderLimit;
  17240. }
  17241. var intensity = 1.0 - (away / this.borderLimit);
  17242. if (intensity < 0) {
  17243. return false;
  17244. }
  17245. if (intensity > 1.0) {
  17246. intensity = 1.0;
  17247. }
  17248. // Position
  17249. var centerX = globalViewport.x + globalViewport.width / 2;
  17250. var centerY = globalViewport.y + globalViewport.height / 2;
  17251. var distX = centerX - this._positionX;
  17252. var distY = centerY - this._positionY;
  17253. // Effects
  17254. engine.enableEffect(this._effect);
  17255. engine.setState(false);
  17256. engine.setDepthBuffer(false);
  17257. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17258. // VBOs
  17259. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17260. for (var index = 0; index < this.lensFlares.length; index++) {
  17261. var flare = this.lensFlares[index];
  17262. var x = centerX - (distX * flare.position);
  17263. var y = centerY - (distY * flare.position);
  17264. var cw = flare.size;
  17265. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17266. var cx = 2 * (x / globalViewport.width) - 1.0;
  17267. var cy = 1.0 - 2 * (y / globalViewport.height);
  17268. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17269. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17270. // Texture
  17271. this._effect.setTexture("textureSampler", flare.texture);
  17272. // Color
  17273. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17274. // Draw order
  17275. engine.draw(true, 0, 6);
  17276. }
  17277. engine.setDepthBuffer(true);
  17278. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17279. return true;
  17280. };
  17281. LensFlareSystem.prototype.dispose = function () {
  17282. if (this._vertexBuffer) {
  17283. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17284. this._vertexBuffer = null;
  17285. }
  17286. if (this._indexBuffer) {
  17287. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17288. this._indexBuffer = null;
  17289. }
  17290. while (this.lensFlares.length) {
  17291. this.lensFlares[0].dispose();
  17292. }
  17293. // Remove from scene
  17294. var index = this._scene.lensFlareSystems.indexOf(this);
  17295. this._scene.lensFlareSystems.splice(index, 1);
  17296. };
  17297. return LensFlareSystem;
  17298. })();
  17299. BABYLON.LensFlareSystem = LensFlareSystem;
  17300. })(BABYLON || (BABYLON = {}));
  17301. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17302. (function (BABYLON) {
  17303. var IntersectionInfo = (function () {
  17304. function IntersectionInfo(bu, bv, distance) {
  17305. this.bu = bu;
  17306. this.bv = bv;
  17307. this.distance = distance;
  17308. this.faceId = 0;
  17309. this.subMeshId = 0;
  17310. }
  17311. return IntersectionInfo;
  17312. })();
  17313. BABYLON.IntersectionInfo = IntersectionInfo;
  17314. var PickingInfo = (function () {
  17315. function PickingInfo() {
  17316. this.hit = false;
  17317. this.distance = 0;
  17318. this.pickedPoint = null;
  17319. this.pickedMesh = null;
  17320. this.bu = 0;
  17321. this.bv = 0;
  17322. this.faceId = -1;
  17323. this.subMeshId = 0;
  17324. }
  17325. // Methods
  17326. PickingInfo.prototype.getNormal = function () {
  17327. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17328. return null;
  17329. }
  17330. var indices = this.pickedMesh.getIndices();
  17331. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17332. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17333. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17334. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17335. normal0 = normal0.scale(this.bu);
  17336. normal1 = normal1.scale(this.bv);
  17337. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17338. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17339. };
  17340. PickingInfo.prototype.getTextureCoordinates = function () {
  17341. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17342. return null;
  17343. }
  17344. var indices = this.pickedMesh.getIndices();
  17345. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17346. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17347. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17348. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17349. uv0 = uv0.scale(this.bu);
  17350. uv1 = uv1.scale(this.bv);
  17351. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17352. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17353. };
  17354. return PickingInfo;
  17355. })();
  17356. BABYLON.PickingInfo = PickingInfo;
  17357. })(BABYLON || (BABYLON = {}));
  17358. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17359. (function (BABYLON) {
  17360. var FilesInput = (function () {
  17361. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17362. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17363. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17364. this._engine = p_engine;
  17365. this._canvas = p_canvas;
  17366. this._currentScene = p_scene;
  17367. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17368. this._progressCallback = p_progressCallback;
  17369. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17370. this._textureLoadingCallback = p_textureLoadingCallback;
  17371. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17372. }
  17373. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17374. var _this = this;
  17375. if (p_elementToMonitor) {
  17376. this._elementToMonitor = p_elementToMonitor;
  17377. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17378. _this.drag(e);
  17379. }, false);
  17380. this._elementToMonitor.addEventListener("dragover", function (e) {
  17381. _this.drag(e);
  17382. }, false);
  17383. this._elementToMonitor.addEventListener("drop", function (e) {
  17384. _this.drop(e);
  17385. }, false);
  17386. }
  17387. };
  17388. FilesInput.prototype.renderFunction = function () {
  17389. if (this._additionnalRenderLoopLogicCallback) {
  17390. this._additionnalRenderLoopLogicCallback();
  17391. }
  17392. if (this._currentScene) {
  17393. if (this._textureLoadingCallback) {
  17394. var remaining = this._currentScene.getWaitingItemsCount();
  17395. if (remaining > 0) {
  17396. this._textureLoadingCallback(remaining);
  17397. }
  17398. }
  17399. this._currentScene.render();
  17400. }
  17401. };
  17402. FilesInput.prototype.drag = function (e) {
  17403. e.stopPropagation();
  17404. e.preventDefault();
  17405. };
  17406. FilesInput.prototype.drop = function (eventDrop) {
  17407. eventDrop.stopPropagation();
  17408. eventDrop.preventDefault();
  17409. this.loadFiles(eventDrop);
  17410. };
  17411. FilesInput.prototype.loadFiles = function (event) {
  17412. if (this._startingProcessingFilesCallback)
  17413. this._startingProcessingFilesCallback();
  17414. // Handling data transfer via drag'n'drop
  17415. if (event && event.dataTransfer && event.dataTransfer.files) {
  17416. this._filesToLoad = event.dataTransfer.files;
  17417. }
  17418. // Handling files from input files
  17419. if (event && event.target && event.target.files) {
  17420. this._filesToLoad = event.target.files;
  17421. }
  17422. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17423. for (var i = 0; i < this._filesToLoad.length; i++) {
  17424. switch (this._filesToLoad[i].type) {
  17425. case "image/jpeg":
  17426. case "image/png":
  17427. case "image/bmp":
  17428. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17429. break;
  17430. case "image/targa":
  17431. case "image/vnd.ms-dds":
  17432. case "audio/wav":
  17433. case "audio/x-wav":
  17434. case "audio/mp3":
  17435. case "audio/mpeg":
  17436. case "audio/mpeg3":
  17437. case "audio/x-mpeg-3":
  17438. case "audio/ogg":
  17439. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17440. break;
  17441. default:
  17442. 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) {
  17443. this._sceneFileToLoad = this._filesToLoad[i];
  17444. }
  17445. break;
  17446. }
  17447. }
  17448. this.reload();
  17449. }
  17450. };
  17451. FilesInput.prototype.reload = function () {
  17452. var _this = this;
  17453. var that = this;
  17454. // If a ".babylon" file has been provided
  17455. if (this._sceneFileToLoad) {
  17456. if (this._currentScene) {
  17457. this._engine.stopRenderLoop();
  17458. this._currentScene.dispose();
  17459. }
  17460. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17461. that._currentScene = newScene;
  17462. // Wait for textures and shaders to be ready
  17463. that._currentScene.executeWhenReady(function () {
  17464. // Attach camera to canvas inputs
  17465. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17466. that._currentScene.createDefaultCameraOrLight();
  17467. }
  17468. that._currentScene.activeCamera.attachControl(that._canvas);
  17469. if (that._sceneLoadedCallback) {
  17470. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17471. }
  17472. that._engine.runRenderLoop(function () {
  17473. that.renderFunction();
  17474. });
  17475. });
  17476. }, function (progress) {
  17477. if (_this._progressCallback) {
  17478. _this._progressCallback(progress);
  17479. }
  17480. });
  17481. }
  17482. else {
  17483. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17484. }
  17485. };
  17486. FilesInput.FilesTextures = new Array();
  17487. FilesInput.FilesToLoad = new Array();
  17488. return FilesInput;
  17489. })();
  17490. BABYLON.FilesInput = FilesInput;
  17491. })(BABYLON || (BABYLON = {}));
  17492. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17493. (function (BABYLON) {
  17494. var OimoJSPlugin = (function () {
  17495. function OimoJSPlugin() {
  17496. this._registeredMeshes = [];
  17497. /**
  17498. * Update the body position according to the mesh position
  17499. * @param mesh
  17500. */
  17501. this.updateBodyPosition = function (mesh) {
  17502. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17503. var registeredMesh = this._registeredMeshes[index];
  17504. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17505. var body = registeredMesh.body.body;
  17506. mesh.computeWorldMatrix(true);
  17507. var center = mesh.getBoundingInfo().boundingBox.center;
  17508. body.setPosition(center.x, center.y, center.z);
  17509. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17510. return;
  17511. }
  17512. // Case where the parent has been updated
  17513. if (registeredMesh.mesh.parent === mesh) {
  17514. mesh.computeWorldMatrix(true);
  17515. registeredMesh.mesh.computeWorldMatrix(true);
  17516. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17517. var absoluteRotation = mesh.rotation;
  17518. body = registeredMesh.body.body;
  17519. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17520. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17521. return;
  17522. }
  17523. }
  17524. };
  17525. }
  17526. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17527. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17528. };
  17529. OimoJSPlugin.prototype.initialize = function (iterations) {
  17530. this._world = new OIMO.World();
  17531. this._world.clear();
  17532. };
  17533. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17534. this._world.gravity = gravity;
  17535. };
  17536. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17537. var body = null;
  17538. this.unregisterMesh(mesh);
  17539. mesh.computeWorldMatrix(true);
  17540. var initialRotation = null;
  17541. if (mesh.rotationQuaternion) {
  17542. initialRotation = mesh.rotationQuaternion.clone();
  17543. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17544. mesh.computeWorldMatrix(true);
  17545. }
  17546. var bbox = mesh.getBoundingInfo().boundingBox;
  17547. // The delta between the mesh position and the mesh bounding box center
  17548. var deltaPosition = mesh.position.subtract(bbox.center);
  17549. // Transform delta position with the rotation
  17550. if (initialRotation) {
  17551. var m = new BABYLON.Matrix();
  17552. initialRotation.toRotationMatrix(m);
  17553. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17554. }
  17555. switch (impostor) {
  17556. case BABYLON.PhysicsEngine.SphereImpostor:
  17557. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17558. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17559. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17560. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17561. body = new OIMO.Body({
  17562. type: 'sphere',
  17563. size: [size],
  17564. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17565. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17566. move: options.mass != 0,
  17567. config: [options.mass, options.friction, options.restitution],
  17568. world: this._world
  17569. });
  17570. break;
  17571. case BABYLON.PhysicsEngine.PlaneImpostor:
  17572. case BABYLON.PhysicsEngine.CylinderImpostor:
  17573. case BABYLON.PhysicsEngine.BoxImpostor:
  17574. var min = bbox.minimumWorld;
  17575. var max = bbox.maximumWorld;
  17576. var box = max.subtract(min);
  17577. var sizeX = this._checkWithEpsilon(box.x);
  17578. var sizeY = this._checkWithEpsilon(box.y);
  17579. var sizeZ = this._checkWithEpsilon(box.z);
  17580. body = new OIMO.Body({
  17581. type: 'box',
  17582. size: [sizeX, sizeY, sizeZ],
  17583. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17584. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17585. move: options.mass != 0,
  17586. config: [options.mass, options.friction, options.restitution],
  17587. world: this._world
  17588. });
  17589. break;
  17590. }
  17591. //If quaternion was set as the rotation of the object
  17592. if (initialRotation) {
  17593. //We have to access the rigid body's properties to set the quaternion.
  17594. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17595. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17596. //update the internal rotation matrix
  17597. body.body.syncShapes();
  17598. }
  17599. this._registeredMeshes.push({
  17600. mesh: mesh,
  17601. body: body,
  17602. delta: deltaPosition
  17603. });
  17604. return body;
  17605. };
  17606. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17607. var types = [], sizes = [], positions = [], rotations = [];
  17608. var initialMesh = parts[0].mesh;
  17609. for (var index = 0; index < parts.length; index++) {
  17610. var part = parts[index];
  17611. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17612. types.push(bodyParameters.type);
  17613. sizes.push.apply(sizes, bodyParameters.size);
  17614. positions.push.apply(positions, bodyParameters.pos);
  17615. rotations.push.apply(rotations, bodyParameters.rot);
  17616. }
  17617. var body = new OIMO.Body({
  17618. type: types,
  17619. size: sizes,
  17620. pos: positions,
  17621. rot: rotations,
  17622. move: options.mass != 0,
  17623. config: [options.mass, options.friction, options.restitution],
  17624. world: this._world
  17625. });
  17626. this._registeredMeshes.push({
  17627. mesh: initialMesh,
  17628. body: body
  17629. });
  17630. return body;
  17631. };
  17632. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17633. var bodyParameters = null;
  17634. var mesh = part.mesh;
  17635. // We need the bounding box/sphere info to compute the physics body
  17636. mesh.computeWorldMatrix();
  17637. switch (part.impostor) {
  17638. case BABYLON.PhysicsEngine.SphereImpostor:
  17639. var bbox = mesh.getBoundingInfo().boundingBox;
  17640. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17641. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17642. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17643. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17644. bodyParameters = {
  17645. type: 'sphere',
  17646. /* bug with oimo : sphere needs 3 sizes in this case */
  17647. size: [size, -1, -1],
  17648. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17649. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17650. };
  17651. break;
  17652. case BABYLON.PhysicsEngine.PlaneImpostor:
  17653. case BABYLON.PhysicsEngine.BoxImpostor:
  17654. bbox = mesh.getBoundingInfo().boundingBox;
  17655. var min = bbox.minimumWorld;
  17656. var max = bbox.maximumWorld;
  17657. var box = max.subtract(min);
  17658. var sizeX = this._checkWithEpsilon(box.x);
  17659. var sizeY = this._checkWithEpsilon(box.y);
  17660. var sizeZ = this._checkWithEpsilon(box.z);
  17661. var relativePosition = mesh.position;
  17662. bodyParameters = {
  17663. type: 'box',
  17664. size: [sizeX, sizeY, sizeZ],
  17665. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17666. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17667. };
  17668. break;
  17669. }
  17670. return bodyParameters;
  17671. };
  17672. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17673. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17674. var registeredMesh = this._registeredMeshes[index];
  17675. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17676. if (registeredMesh.body) {
  17677. this._world.removeRigidBody(registeredMesh.body.body);
  17678. this._unbindBody(registeredMesh.body);
  17679. }
  17680. this._registeredMeshes.splice(index, 1);
  17681. return;
  17682. }
  17683. }
  17684. };
  17685. OimoJSPlugin.prototype._unbindBody = function (body) {
  17686. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17687. var registeredMesh = this._registeredMeshes[index];
  17688. if (registeredMesh.body === body) {
  17689. registeredMesh.body = null;
  17690. }
  17691. }
  17692. };
  17693. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17694. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17695. var registeredMesh = this._registeredMeshes[index];
  17696. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17697. // Get object mass to have a behaviour similar to cannon.js
  17698. var mass = registeredMesh.body.body.massInfo.mass;
  17699. // The force is scaled with the mass of object
  17700. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17701. return;
  17702. }
  17703. }
  17704. };
  17705. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17706. var body1 = null, body2 = null;
  17707. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17708. var registeredMesh = this._registeredMeshes[index];
  17709. if (registeredMesh.mesh === mesh1) {
  17710. body1 = registeredMesh.body.body;
  17711. }
  17712. else if (registeredMesh.mesh === mesh2) {
  17713. body2 = registeredMesh.body.body;
  17714. }
  17715. }
  17716. if (!body1 || !body2) {
  17717. return false;
  17718. }
  17719. if (!options) {
  17720. options = {};
  17721. }
  17722. new OIMO.Link({
  17723. type: options.type,
  17724. body1: body1,
  17725. body2: body2,
  17726. min: options.min,
  17727. max: options.max,
  17728. axe1: options.axe1,
  17729. axe2: options.axe2,
  17730. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17731. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17732. collision: options.collision,
  17733. spring: options.spring,
  17734. world: this._world
  17735. });
  17736. return true;
  17737. };
  17738. OimoJSPlugin.prototype.dispose = function () {
  17739. this._world.clear();
  17740. while (this._registeredMeshes.length) {
  17741. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17742. }
  17743. };
  17744. OimoJSPlugin.prototype.isSupported = function () {
  17745. return OIMO !== undefined;
  17746. };
  17747. OimoJSPlugin.prototype._getLastShape = function (body) {
  17748. var lastShape = body.shapes;
  17749. while (lastShape.next) {
  17750. lastShape = lastShape.next;
  17751. }
  17752. return lastShape;
  17753. };
  17754. OimoJSPlugin.prototype.runOneStep = function (time) {
  17755. this._world.step();
  17756. // Update the position of all registered meshes
  17757. var i = this._registeredMeshes.length;
  17758. var m;
  17759. while (i--) {
  17760. var body = this._registeredMeshes[i].body.body;
  17761. var mesh = this._registeredMeshes[i].mesh;
  17762. var delta = this._registeredMeshes[i].delta;
  17763. if (!body.sleeping) {
  17764. if (body.shapes.next) {
  17765. var parentShape = this._getLastShape(body);
  17766. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17767. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17768. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17769. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17770. if (!mesh.rotationQuaternion) {
  17771. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17772. }
  17773. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17774. mesh.computeWorldMatrix();
  17775. }
  17776. else {
  17777. m = body.getMatrix();
  17778. mtx = BABYLON.Matrix.FromArray(m);
  17779. // Body position
  17780. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17781. if (!delta) {
  17782. mesh.position.x = bodyX;
  17783. mesh.position.y = bodyY;
  17784. mesh.position.z = bodyZ;
  17785. }
  17786. else {
  17787. mesh.position.x = bodyX + delta.x;
  17788. mesh.position.y = bodyY + delta.y;
  17789. mesh.position.z = bodyZ + delta.z;
  17790. }
  17791. if (!mesh.rotationQuaternion) {
  17792. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17793. }
  17794. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17795. mesh.computeWorldMatrix();
  17796. }
  17797. }
  17798. }
  17799. };
  17800. return OimoJSPlugin;
  17801. })();
  17802. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17803. })(BABYLON || (BABYLON = {}));
  17804. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17805. (function (BABYLON) {
  17806. var PhysicsEngine = (function () {
  17807. function PhysicsEngine(plugin) {
  17808. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17809. }
  17810. PhysicsEngine.prototype._initialize = function (gravity) {
  17811. this._currentPlugin.initialize();
  17812. this._setGravity(gravity);
  17813. };
  17814. PhysicsEngine.prototype._runOneStep = function (delta) {
  17815. if (delta > 0.1) {
  17816. delta = 0.1;
  17817. }
  17818. else if (delta <= 0) {
  17819. delta = 1.0 / 60.0;
  17820. }
  17821. this._currentPlugin.runOneStep(delta);
  17822. };
  17823. PhysicsEngine.prototype._setGravity = function (gravity) {
  17824. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17825. this._currentPlugin.setGravity(this.gravity);
  17826. };
  17827. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17828. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17829. };
  17830. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17831. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17832. };
  17833. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17834. this._currentPlugin.unregisterMesh(mesh);
  17835. };
  17836. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17837. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17838. };
  17839. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17840. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17841. };
  17842. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17843. this._currentPlugin.updateBodyPosition(mesh);
  17844. };
  17845. PhysicsEngine.prototype.dispose = function () {
  17846. this._currentPlugin.dispose();
  17847. };
  17848. PhysicsEngine.prototype.isSupported = function () {
  17849. return this._currentPlugin.isSupported();
  17850. };
  17851. // Statics
  17852. PhysicsEngine.NoImpostor = 0;
  17853. PhysicsEngine.SphereImpostor = 1;
  17854. PhysicsEngine.BoxImpostor = 2;
  17855. PhysicsEngine.PlaneImpostor = 3;
  17856. PhysicsEngine.MeshImpostor = 4;
  17857. PhysicsEngine.CapsuleImpostor = 5;
  17858. PhysicsEngine.ConeImpostor = 6;
  17859. PhysicsEngine.CylinderImpostor = 7;
  17860. PhysicsEngine.ConvexHullImpostor = 8;
  17861. PhysicsEngine.Epsilon = 0.001;
  17862. return PhysicsEngine;
  17863. })();
  17864. BABYLON.PhysicsEngine = PhysicsEngine;
  17865. })(BABYLON || (BABYLON = {}));
  17866. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17867. (function (BABYLON) {
  17868. var serializeLight = function (light) {
  17869. var serializationObject = {};
  17870. serializationObject.name = light.name;
  17871. serializationObject.id = light.id;
  17872. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17873. if (light instanceof BABYLON.PointLight) {
  17874. serializationObject.type = 0;
  17875. serializationObject.position = light.position.asArray();
  17876. }
  17877. else if (light instanceof BABYLON.DirectionalLight) {
  17878. serializationObject.type = 1;
  17879. var directionalLight = light;
  17880. serializationObject.position = directionalLight.position.asArray();
  17881. serializationObject.direction = directionalLight.direction.asArray();
  17882. }
  17883. else if (light instanceof BABYLON.SpotLight) {
  17884. serializationObject.type = 2;
  17885. var spotLight = light;
  17886. serializationObject.position = spotLight.position.asArray();
  17887. serializationObject.direction = spotLight.position.asArray();
  17888. serializationObject.angle = spotLight.angle;
  17889. serializationObject.exponent = spotLight.exponent;
  17890. }
  17891. else if (light instanceof BABYLON.HemisphericLight) {
  17892. serializationObject.type = 3;
  17893. var hemisphericLight = light;
  17894. serializationObject.direction = hemisphericLight.direction.asArray();
  17895. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17896. }
  17897. if (light.intensity) {
  17898. serializationObject.intensity = light.intensity;
  17899. }
  17900. serializationObject.range = light.range;
  17901. serializationObject.diffuse = light.diffuse.asArray();
  17902. serializationObject.specular = light.specular.asArray();
  17903. return serializationObject;
  17904. };
  17905. var serializeFresnelParameter = function (fresnelParameter) {
  17906. var serializationObject = {};
  17907. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17908. serializationObject.leftColor = fresnelParameter.leftColor;
  17909. serializationObject.rightColor = fresnelParameter.rightColor;
  17910. serializationObject.bias = fresnelParameter.bias;
  17911. serializationObject.power = fresnelParameter.power;
  17912. return serializationObject;
  17913. };
  17914. var serializeCamera = function (camera) {
  17915. var serializationObject = {};
  17916. serializationObject.name = camera.name;
  17917. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17918. serializationObject.id = camera.id;
  17919. serializationObject.position = camera.position.asArray();
  17920. // Parent
  17921. if (camera.parent) {
  17922. serializationObject.parentId = camera.parent.id;
  17923. }
  17924. // Target
  17925. serializationObject.rotation = camera.rotation.asArray();
  17926. // Locked target
  17927. if (camera.lockedTarget && camera.lockedTarget.id) {
  17928. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17929. }
  17930. serializationObject.fov = camera.fov;
  17931. serializationObject.minZ = camera.minZ;
  17932. serializationObject.maxZ = camera.maxZ;
  17933. serializationObject.speed = camera.speed;
  17934. serializationObject.inertia = camera.inertia;
  17935. serializationObject.checkCollisions = camera.checkCollisions;
  17936. serializationObject.applyGravity = camera.applyGravity;
  17937. if (camera.ellipsoid) {
  17938. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17939. }
  17940. // Animations
  17941. appendAnimations(camera, serializationObject);
  17942. // Layer mask
  17943. serializationObject.layerMask = camera.layerMask;
  17944. return serializationObject;
  17945. };
  17946. var appendAnimations = function (source, destination) {
  17947. if (source.animations) {
  17948. destination.animations = [];
  17949. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17950. var animation = source.animations[animationIndex];
  17951. destination.animations.push(serializeAnimation(animation));
  17952. }
  17953. }
  17954. };
  17955. var serializeAnimation = function (animation) {
  17956. var serializationObject = {};
  17957. serializationObject.name = animation.name;
  17958. serializationObject.property = animation.targetProperty;
  17959. serializationObject.framePerSecond = animation.framePerSecond;
  17960. serializationObject.dataType = animation.dataType;
  17961. serializationObject.loopBehavior = animation.loopMode;
  17962. var dataType = animation.dataType;
  17963. serializationObject.keys = [];
  17964. var keys = animation.getKeys();
  17965. for (var index = 0; index < keys.length; index++) {
  17966. var animationKey = keys[index];
  17967. var key = {};
  17968. key.frame = animationKey.frame;
  17969. switch (dataType) {
  17970. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17971. key.values = [animationKey.value];
  17972. break;
  17973. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17974. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17975. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17976. key.values = animationKey.value.asArray();
  17977. break;
  17978. }
  17979. serializationObject.keys.push(key);
  17980. }
  17981. return serializationObject;
  17982. };
  17983. var serializeMultiMaterial = function (material) {
  17984. var serializationObject = {};
  17985. serializationObject.name = material.name;
  17986. serializationObject.id = material.id;
  17987. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17988. serializationObject.materials = [];
  17989. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17990. var subMat = material.subMaterials[matIndex];
  17991. if (subMat) {
  17992. serializationObject.materials.push(subMat.id);
  17993. }
  17994. else {
  17995. serializationObject.materials.push(null);
  17996. }
  17997. }
  17998. return serializationObject;
  17999. };
  18000. var serializeMaterial = function (material) {
  18001. var serializationObject = {};
  18002. serializationObject.name = material.name;
  18003. serializationObject.ambient = material.ambientColor.asArray();
  18004. serializationObject.diffuse = material.diffuseColor.asArray();
  18005. serializationObject.specular = material.specularColor.asArray();
  18006. serializationObject.specularPower = material.specularPower;
  18007. serializationObject.emissive = material.emissiveColor.asArray();
  18008. serializationObject.alpha = material.alpha;
  18009. serializationObject.id = material.id;
  18010. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18011. serializationObject.backFaceCulling = material.backFaceCulling;
  18012. if (material.diffuseTexture) {
  18013. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18014. }
  18015. if (material.diffuseFresnelParameters) {
  18016. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18017. }
  18018. if (material.ambientTexture) {
  18019. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18020. }
  18021. if (material.opacityTexture) {
  18022. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18023. }
  18024. if (material.opacityFresnelParameters) {
  18025. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18026. }
  18027. if (material.reflectionTexture) {
  18028. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18029. }
  18030. if (material.reflectionFresnelParameters) {
  18031. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18032. }
  18033. if (material.emissiveTexture) {
  18034. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18035. }
  18036. if (material.emissiveFresnelParameters) {
  18037. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18038. }
  18039. if (material.specularTexture) {
  18040. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18041. }
  18042. if (material.bumpTexture) {
  18043. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18044. }
  18045. return serializationObject;
  18046. };
  18047. var serializeTexture = function (texture) {
  18048. var serializationObject = {};
  18049. if (!texture.name) {
  18050. return null;
  18051. }
  18052. if (texture instanceof BABYLON.CubeTexture) {
  18053. serializationObject.name = texture.name;
  18054. serializationObject.hasAlpha = texture.hasAlpha;
  18055. serializationObject.level = texture.level;
  18056. serializationObject.coordinatesMode = texture.coordinatesMode;
  18057. return serializationObject;
  18058. }
  18059. if (texture instanceof BABYLON.MirrorTexture) {
  18060. var mirrorTexture = texture;
  18061. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18062. serializationObject.renderList = [];
  18063. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18064. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18065. }
  18066. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18067. }
  18068. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18069. var renderTargetTexture = texture;
  18070. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18071. serializationObject.renderList = [];
  18072. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18073. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18074. }
  18075. }
  18076. var regularTexture = texture;
  18077. serializationObject.name = texture.name;
  18078. serializationObject.hasAlpha = texture.hasAlpha;
  18079. serializationObject.level = texture.level;
  18080. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18081. serializationObject.coordinatesMode = texture.coordinatesMode;
  18082. serializationObject.uOffset = regularTexture.uOffset;
  18083. serializationObject.vOffset = regularTexture.vOffset;
  18084. serializationObject.uScale = regularTexture.uScale;
  18085. serializationObject.vScale = regularTexture.vScale;
  18086. serializationObject.uAng = regularTexture.uAng;
  18087. serializationObject.vAng = regularTexture.vAng;
  18088. serializationObject.wAng = regularTexture.wAng;
  18089. serializationObject.wrapU = texture.wrapU;
  18090. serializationObject.wrapV = texture.wrapV;
  18091. // Animations
  18092. appendAnimations(texture, serializationObject);
  18093. return serializationObject;
  18094. };
  18095. var serializeSkeleton = function (skeleton) {
  18096. var serializationObject = {};
  18097. serializationObject.name = skeleton.name;
  18098. serializationObject.id = skeleton.id;
  18099. serializationObject.bones = [];
  18100. for (var index = 0; index < skeleton.bones.length; index++) {
  18101. var bone = skeleton.bones[index];
  18102. var serializedBone = {
  18103. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18104. name: bone.name,
  18105. matrix: bone.getLocalMatrix().toArray()
  18106. };
  18107. serializationObject.bones.push(serializedBone);
  18108. if (bone.animations && bone.animations.length > 0) {
  18109. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18110. }
  18111. }
  18112. return serializationObject;
  18113. };
  18114. var serializeParticleSystem = function (particleSystem) {
  18115. var serializationObject = {};
  18116. serializationObject.emitterId = particleSystem.emitter.id;
  18117. serializationObject.capacity = particleSystem.getCapacity();
  18118. if (particleSystem.particleTexture) {
  18119. serializationObject.textureName = particleSystem.particleTexture.name;
  18120. }
  18121. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18122. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18123. serializationObject.minSize = particleSystem.minSize;
  18124. serializationObject.maxSize = particleSystem.maxSize;
  18125. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18126. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18127. serializationObject.emitRate = particleSystem.emitRate;
  18128. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18129. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18130. serializationObject.gravity = particleSystem.gravity.asArray();
  18131. serializationObject.direction1 = particleSystem.direction1.asArray();
  18132. serializationObject.direction2 = particleSystem.direction2.asArray();
  18133. serializationObject.color1 = particleSystem.color1.asArray();
  18134. serializationObject.color2 = particleSystem.color2.asArray();
  18135. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18136. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18137. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18138. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18139. serializationObject.blendMode = particleSystem.blendMode;
  18140. return serializationObject;
  18141. };
  18142. var serializeLensFlareSystem = function (lensFlareSystem) {
  18143. var serializationObject = {};
  18144. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18145. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18146. serializationObject.flares = [];
  18147. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18148. var flare = lensFlareSystem.lensFlares[index];
  18149. serializationObject.flares.push({
  18150. size: flare.size,
  18151. position: flare.position,
  18152. color: flare.color.asArray(),
  18153. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18154. });
  18155. }
  18156. return serializationObject;
  18157. };
  18158. var serializeShadowGenerator = function (light) {
  18159. var serializationObject = {};
  18160. var shadowGenerator = light.getShadowGenerator();
  18161. serializationObject.lightId = light.id;
  18162. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18163. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18164. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18165. serializationObject.renderList = [];
  18166. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18167. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18168. serializationObject.renderList.push(mesh.id);
  18169. }
  18170. return serializationObject;
  18171. };
  18172. var serializedGeometries = [];
  18173. var serializeGeometry = function (geometry, serializationGeometries) {
  18174. if (serializedGeometries[geometry.id]) {
  18175. return;
  18176. }
  18177. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18178. serializationGeometries.boxes.push(serializeBox(geometry));
  18179. }
  18180. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18181. serializationGeometries.spheres.push(serializeSphere(geometry));
  18182. }
  18183. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18184. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18185. }
  18186. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18187. serializationGeometries.toruses.push(serializeTorus(geometry));
  18188. }
  18189. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18190. serializationGeometries.grounds.push(serializeGround(geometry));
  18191. }
  18192. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18193. serializationGeometries.planes.push(serializePlane(geometry));
  18194. }
  18195. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18196. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18197. }
  18198. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18199. throw new Error("Unknow primitive type");
  18200. }
  18201. else {
  18202. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18203. }
  18204. serializedGeometries[geometry.id] = true;
  18205. };
  18206. var serializeGeometryBase = function (geometry) {
  18207. var serializationObject = {};
  18208. serializationObject.id = geometry.id;
  18209. if (BABYLON.Tags.HasTags(geometry)) {
  18210. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18211. }
  18212. return serializationObject;
  18213. };
  18214. var serializeVertexData = function (vertexData) {
  18215. var serializationObject = serializeGeometryBase(vertexData);
  18216. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18217. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18218. }
  18219. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18220. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18221. }
  18222. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18223. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18224. }
  18225. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18226. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18227. }
  18228. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18229. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18230. }
  18231. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18232. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18233. serializationObject.matricesIndices._isExpanded = true;
  18234. }
  18235. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18236. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18237. }
  18238. serializationObject.indices = vertexData.getIndices();
  18239. return serializationObject;
  18240. };
  18241. var serializePrimitive = function (primitive) {
  18242. var serializationObject = serializeGeometryBase(primitive);
  18243. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18244. return serializationObject;
  18245. };
  18246. var serializeBox = function (box) {
  18247. var serializationObject = serializePrimitive(box);
  18248. serializationObject.size = box.size;
  18249. return serializationObject;
  18250. };
  18251. var serializeSphere = function (sphere) {
  18252. var serializationObject = serializePrimitive(sphere);
  18253. serializationObject.segments = sphere.segments;
  18254. serializationObject.diameter = sphere.diameter;
  18255. return serializationObject;
  18256. };
  18257. var serializeCylinder = function (cylinder) {
  18258. var serializationObject = serializePrimitive(cylinder);
  18259. serializationObject.height = cylinder.height;
  18260. serializationObject.diameterTop = cylinder.diameterTop;
  18261. serializationObject.diameterBottom = cylinder.diameterBottom;
  18262. serializationObject.tessellation = cylinder.tessellation;
  18263. return serializationObject;
  18264. };
  18265. var serializeTorus = function (torus) {
  18266. var serializationObject = serializePrimitive(torus);
  18267. serializationObject.diameter = torus.diameter;
  18268. serializationObject.thickness = torus.thickness;
  18269. serializationObject.tessellation = torus.tessellation;
  18270. return serializationObject;
  18271. };
  18272. var serializeGround = function (ground) {
  18273. var serializationObject = serializePrimitive(ground);
  18274. serializationObject.width = ground.width;
  18275. serializationObject.height = ground.height;
  18276. serializationObject.subdivisions = ground.subdivisions;
  18277. return serializationObject;
  18278. };
  18279. var serializePlane = function (plane) {
  18280. var serializationObject = serializePrimitive(plane);
  18281. serializationObject.size = plane.size;
  18282. return serializationObject;
  18283. };
  18284. var serializeTorusKnot = function (torusKnot) {
  18285. var serializationObject = serializePrimitive(torusKnot);
  18286. serializationObject.radius = torusKnot.radius;
  18287. serializationObject.tube = torusKnot.tube;
  18288. serializationObject.radialSegments = torusKnot.radialSegments;
  18289. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18290. serializationObject.p = torusKnot.p;
  18291. serializationObject.q = torusKnot.q;
  18292. return serializationObject;
  18293. };
  18294. var serializeMesh = function (mesh, serializationScene) {
  18295. var serializationObject = {};
  18296. serializationObject.name = mesh.name;
  18297. serializationObject.id = mesh.id;
  18298. if (BABYLON.Tags.HasTags(mesh)) {
  18299. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18300. }
  18301. serializationObject.position = mesh.position.asArray();
  18302. if (mesh.rotationQuaternion) {
  18303. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18304. }
  18305. else if (mesh.rotation) {
  18306. serializationObject.rotation = mesh.rotation.asArray();
  18307. }
  18308. serializationObject.scaling = mesh.scaling.asArray();
  18309. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18310. serializationObject.isEnabled = mesh.isEnabled();
  18311. serializationObject.isVisible = mesh.isVisible;
  18312. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18313. serializationObject.pickable = mesh.isPickable;
  18314. serializationObject.receiveShadows = mesh.receiveShadows;
  18315. serializationObject.billboardMode = mesh.billboardMode;
  18316. serializationObject.visibility = mesh.visibility;
  18317. serializationObject.checkCollisions = mesh.checkCollisions;
  18318. // Parent
  18319. if (mesh.parent) {
  18320. serializationObject.parentId = mesh.parent.id;
  18321. }
  18322. // Geometry
  18323. var geometry = mesh._geometry;
  18324. if (geometry) {
  18325. var geometryId = geometry.id;
  18326. serializationObject.geometryId = geometryId;
  18327. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18328. // 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
  18329. serializeGeometry(geometry, serializationScene.geometries);
  18330. }
  18331. // SubMeshes
  18332. serializationObject.subMeshes = [];
  18333. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18334. var subMesh = mesh.subMeshes[subIndex];
  18335. serializationObject.subMeshes.push({
  18336. materialIndex: subMesh.materialIndex,
  18337. verticesStart: subMesh.verticesStart,
  18338. verticesCount: subMesh.verticesCount,
  18339. indexStart: subMesh.indexStart,
  18340. indexCount: subMesh.indexCount
  18341. });
  18342. }
  18343. }
  18344. // Material
  18345. if (mesh.material) {
  18346. serializationObject.materialId = mesh.material.id;
  18347. }
  18348. else {
  18349. mesh.material = null;
  18350. }
  18351. // Skeleton
  18352. if (mesh.skeleton) {
  18353. serializationObject.skeletonId = mesh.skeleton.id;
  18354. }
  18355. // Physics
  18356. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18357. serializationObject.physicsMass = mesh.getPhysicsMass();
  18358. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18359. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18360. switch (mesh.getPhysicsImpostor()) {
  18361. case BABYLON.PhysicsEngine.BoxImpostor:
  18362. serializationObject.physicsImpostor = 1;
  18363. break;
  18364. case BABYLON.PhysicsEngine.SphereImpostor:
  18365. serializationObject.physicsImpostor = 2;
  18366. break;
  18367. }
  18368. }
  18369. // Instances
  18370. serializationObject.instances = [];
  18371. for (var index = 0; index < mesh.instances.length; index++) {
  18372. var instance = mesh.instances[index];
  18373. var serializationInstance = {
  18374. name: instance.name,
  18375. position: instance.position,
  18376. rotation: instance.rotation,
  18377. rotationQuaternion: instance.rotationQuaternion,
  18378. scaling: instance.scaling
  18379. };
  18380. serializationObject.instances.push(serializationInstance);
  18381. // Animations
  18382. appendAnimations(instance, serializationInstance);
  18383. }
  18384. // Animations
  18385. appendAnimations(mesh, serializationObject);
  18386. // Layer mask
  18387. serializationObject.layerMask = mesh.layerMask;
  18388. return serializationObject;
  18389. };
  18390. var SceneSerializer = (function () {
  18391. function SceneSerializer() {
  18392. }
  18393. SceneSerializer.Serialize = function (scene) {
  18394. var serializationObject = {};
  18395. // Scene
  18396. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18397. serializationObject.autoClear = scene.autoClear;
  18398. serializationObject.clearColor = scene.clearColor.asArray();
  18399. serializationObject.ambientColor = scene.ambientColor.asArray();
  18400. serializationObject.gravity = scene.gravity.asArray();
  18401. // Fog
  18402. if (scene.fogMode && scene.fogMode !== 0) {
  18403. serializationObject.fogMode = scene.fogMode;
  18404. serializationObject.fogColor = scene.fogColor.asArray();
  18405. serializationObject.fogStart = scene.fogStart;
  18406. serializationObject.fogEnd = scene.fogEnd;
  18407. serializationObject.fogDensity = scene.fogDensity;
  18408. }
  18409. // Lights
  18410. serializationObject.lights = [];
  18411. for (var index = 0; index < scene.lights.length; index++) {
  18412. var light = scene.lights[index];
  18413. serializationObject.lights.push(serializeLight(light));
  18414. }
  18415. // Cameras
  18416. serializationObject.cameras = [];
  18417. for (index = 0; index < scene.cameras.length; index++) {
  18418. var camera = scene.cameras[index];
  18419. if (camera instanceof BABYLON.FreeCamera) {
  18420. serializationObject.cameras.push(serializeCamera(camera));
  18421. }
  18422. }
  18423. if (scene.activeCamera) {
  18424. serializationObject.activeCameraID = scene.activeCamera.id;
  18425. }
  18426. // Materials
  18427. serializationObject.materials = [];
  18428. serializationObject.multiMaterials = [];
  18429. for (index = 0; index < scene.materials.length; index++) {
  18430. var material = scene.materials[index];
  18431. if (material instanceof BABYLON.StandardMaterial) {
  18432. serializationObject.materials.push(serializeMaterial(material));
  18433. }
  18434. else if (material instanceof BABYLON.MultiMaterial) {
  18435. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18436. }
  18437. }
  18438. // Skeletons
  18439. serializationObject.skeletons = [];
  18440. for (index = 0; index < scene.skeletons.length; index++) {
  18441. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18442. }
  18443. // Geometries
  18444. serializationObject.geometries = {};
  18445. serializationObject.geometries.boxes = [];
  18446. serializationObject.geometries.spheres = [];
  18447. serializationObject.geometries.cylinders = [];
  18448. serializationObject.geometries.toruses = [];
  18449. serializationObject.geometries.grounds = [];
  18450. serializationObject.geometries.planes = [];
  18451. serializationObject.geometries.torusKnots = [];
  18452. serializationObject.geometries.vertexData = [];
  18453. serializedGeometries = [];
  18454. var geometries = scene.getGeometries();
  18455. for (var index = 0; index < geometries.length; index++) {
  18456. var geometry = geometries[index];
  18457. if (geometry.isReady()) {
  18458. serializeGeometry(geometry, serializationObject.geometries);
  18459. }
  18460. }
  18461. // Meshes
  18462. serializationObject.meshes = [];
  18463. for (index = 0; index < scene.meshes.length; index++) {
  18464. var abstractMesh = scene.meshes[index];
  18465. if (abstractMesh instanceof BABYLON.Mesh) {
  18466. var mesh = abstractMesh;
  18467. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18468. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18469. }
  18470. }
  18471. }
  18472. // Particles Systems
  18473. serializationObject.particleSystems = [];
  18474. for (index = 0; index < scene.particleSystems.length; index++) {
  18475. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18476. }
  18477. // Lens flares
  18478. serializationObject.lensFlareSystems = [];
  18479. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18480. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18481. }
  18482. // Shadows
  18483. serializationObject.shadowGenerators = [];
  18484. for (index = 0; index < scene.lights.length; index++) {
  18485. light = scene.lights[index];
  18486. if (light.getShadowGenerator()) {
  18487. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18488. }
  18489. }
  18490. return serializationObject;
  18491. };
  18492. return SceneSerializer;
  18493. })();
  18494. BABYLON.SceneSerializer = SceneSerializer;
  18495. })(BABYLON || (BABYLON = {}));
  18496. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18497. (function (BABYLON) {
  18498. var SceneLoader = (function () {
  18499. function SceneLoader() {
  18500. }
  18501. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18502. get: function () {
  18503. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18504. },
  18505. set: function (value) {
  18506. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18507. },
  18508. enumerable: true,
  18509. configurable: true
  18510. });
  18511. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18512. get: function () {
  18513. return SceneLoader._ShowLoadingScreen;
  18514. },
  18515. set: function (value) {
  18516. SceneLoader._ShowLoadingScreen = value;
  18517. },
  18518. enumerable: true,
  18519. configurable: true
  18520. });
  18521. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18522. var dotPosition = sceneFilename.lastIndexOf(".");
  18523. var queryStringPosition = sceneFilename.indexOf("?");
  18524. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18525. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18526. var plugin = this._registeredPlugins[index];
  18527. if (plugin.extensions.indexOf(extension) !== -1) {
  18528. return plugin;
  18529. }
  18530. }
  18531. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18532. };
  18533. // Public functions
  18534. SceneLoader.RegisterPlugin = function (plugin) {
  18535. plugin.extensions = plugin.extensions.toLowerCase();
  18536. SceneLoader._registeredPlugins.push(plugin);
  18537. };
  18538. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18539. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18540. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18541. return;
  18542. }
  18543. var manifestChecked = function (success) {
  18544. scene.database = database;
  18545. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18546. var importMeshFromData = function (data) {
  18547. var meshes = [];
  18548. var particleSystems = [];
  18549. var skeletons = [];
  18550. try {
  18551. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18552. if (onerror) {
  18553. onerror(scene, 'unable to load the scene');
  18554. }
  18555. return;
  18556. }
  18557. }
  18558. catch (e) {
  18559. if (onerror) {
  18560. onerror(scene, e);
  18561. }
  18562. return;
  18563. }
  18564. if (onsuccess) {
  18565. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18566. onsuccess(meshes, particleSystems, skeletons);
  18567. }
  18568. };
  18569. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18570. // Direct load
  18571. importMeshFromData(sceneFilename.substr(5));
  18572. return;
  18573. }
  18574. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18575. importMeshFromData(data);
  18576. }, progressCallBack, database);
  18577. };
  18578. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18579. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18580. };
  18581. /**
  18582. * Load a scene
  18583. * @param rootUrl a string that defines the root url for scene and resources
  18584. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18585. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18586. */
  18587. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18588. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18589. };
  18590. /**
  18591. * Append a scene
  18592. * @param rootUrl a string that defines the root url for scene and resources
  18593. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18594. * @param scene is the instance of BABYLON.Scene to append to
  18595. */
  18596. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18597. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18598. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18599. return;
  18600. }
  18601. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18602. var database;
  18603. if (SceneLoader.ShowLoadingScreen) {
  18604. scene.getEngine().displayLoadingUI();
  18605. }
  18606. var loadSceneFromData = function (data) {
  18607. scene.database = database;
  18608. if (!plugin.load(scene, data, rootUrl)) {
  18609. if (onerror) {
  18610. onerror(scene);
  18611. }
  18612. scene.getEngine().hideLoadingUI();
  18613. return;
  18614. }
  18615. if (onsuccess) {
  18616. onsuccess(scene);
  18617. }
  18618. if (SceneLoader.ShowLoadingScreen) {
  18619. scene.executeWhenReady(function () {
  18620. scene.getEngine().hideLoadingUI();
  18621. });
  18622. }
  18623. };
  18624. var manifestChecked = function (success) {
  18625. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18626. };
  18627. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18628. // Direct load
  18629. loadSceneFromData(sceneFilename.substr(5));
  18630. return;
  18631. }
  18632. if (rootUrl.indexOf("file:") === -1) {
  18633. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18634. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18635. }
  18636. else {
  18637. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18638. }
  18639. };
  18640. // Flags
  18641. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18642. SceneLoader._ShowLoadingScreen = true;
  18643. // Members
  18644. SceneLoader._registeredPlugins = new Array();
  18645. return SceneLoader;
  18646. })();
  18647. BABYLON.SceneLoader = SceneLoader;
  18648. ;
  18649. })(BABYLON || (BABYLON = {}));
  18650. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18651. (function (BABYLON) {
  18652. var Internals;
  18653. (function (Internals) {
  18654. var checkColors4 = function (colors, count) {
  18655. // Check if color3 was used
  18656. if (colors.length === count * 3) {
  18657. var colors4 = [];
  18658. for (var index = 0; index < colors.length; index += 3) {
  18659. var newIndex = (index / 3) * 4;
  18660. colors4[newIndex] = colors[index];
  18661. colors4[newIndex + 1] = colors[index + 1];
  18662. colors4[newIndex + 2] = colors[index + 2];
  18663. colors4[newIndex + 3] = 1.0;
  18664. }
  18665. return colors4;
  18666. }
  18667. return colors;
  18668. };
  18669. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18670. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18671. texture.name = parsedTexture.name;
  18672. texture.hasAlpha = parsedTexture.hasAlpha;
  18673. texture.level = parsedTexture.level;
  18674. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18675. return texture;
  18676. };
  18677. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18678. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18679. return null;
  18680. }
  18681. if (parsedTexture.isCube) {
  18682. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18683. }
  18684. var texture;
  18685. if (parsedTexture.mirrorPlane) {
  18686. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18687. texture._waitingRenderList = parsedTexture.renderList;
  18688. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18689. }
  18690. else if (parsedTexture.isRenderTarget) {
  18691. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18692. texture._waitingRenderList = parsedTexture.renderList;
  18693. }
  18694. else {
  18695. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18696. }
  18697. texture.name = parsedTexture.name;
  18698. texture.hasAlpha = parsedTexture.hasAlpha;
  18699. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18700. texture.level = parsedTexture.level;
  18701. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18702. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18703. texture.uOffset = parsedTexture.uOffset;
  18704. texture.vOffset = parsedTexture.vOffset;
  18705. texture.uScale = parsedTexture.uScale;
  18706. texture.vScale = parsedTexture.vScale;
  18707. texture.uAng = parsedTexture.uAng;
  18708. texture.vAng = parsedTexture.vAng;
  18709. texture.wAng = parsedTexture.wAng;
  18710. texture.wrapU = parsedTexture.wrapU;
  18711. texture.wrapV = parsedTexture.wrapV;
  18712. // Animations
  18713. if (parsedTexture.animations) {
  18714. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18715. var parsedAnimation = parsedTexture.animations[animationIndex];
  18716. texture.animations.push(parseAnimation(parsedAnimation));
  18717. }
  18718. }
  18719. return texture;
  18720. };
  18721. var parseSkeleton = function (parsedSkeleton, scene) {
  18722. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18723. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18724. var parsedBone = parsedSkeleton.bones[index];
  18725. var parentBone = null;
  18726. if (parsedBone.parentBoneIndex > -1) {
  18727. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18728. }
  18729. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18730. if (parsedBone.animation) {
  18731. bone.animations.push(parseAnimation(parsedBone.animation));
  18732. }
  18733. }
  18734. return skeleton;
  18735. };
  18736. var parseFresnelParameters = function (parsedFresnelParameters) {
  18737. var fresnelParameters = new BABYLON.FresnelParameters();
  18738. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18739. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18740. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18741. fresnelParameters.bias = parsedFresnelParameters.bias;
  18742. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18743. return fresnelParameters;
  18744. };
  18745. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18746. var material;
  18747. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18748. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18749. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18750. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18751. material.specularPower = parsedMaterial.specularPower;
  18752. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18753. material.alpha = parsedMaterial.alpha;
  18754. material.id = parsedMaterial.id;
  18755. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18756. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18757. material.wireframe = parsedMaterial.wireframe;
  18758. if (parsedMaterial.diffuseTexture) {
  18759. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18760. }
  18761. if (parsedMaterial.diffuseFresnelParameters) {
  18762. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18763. }
  18764. if (parsedMaterial.ambientTexture) {
  18765. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18766. }
  18767. if (parsedMaterial.opacityTexture) {
  18768. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18769. }
  18770. if (parsedMaterial.opacityFresnelParameters) {
  18771. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18772. }
  18773. if (parsedMaterial.reflectionTexture) {
  18774. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18775. }
  18776. if (parsedMaterial.reflectionFresnelParameters) {
  18777. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18778. }
  18779. if (parsedMaterial.emissiveTexture) {
  18780. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18781. }
  18782. if (parsedMaterial.emissiveFresnelParameters) {
  18783. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18784. }
  18785. if (parsedMaterial.specularTexture) {
  18786. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18787. }
  18788. if (parsedMaterial.bumpTexture) {
  18789. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18790. }
  18791. return material;
  18792. };
  18793. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18794. for (var index = 0; index < parsedData.materials.length; index++) {
  18795. var parsedMaterial = parsedData.materials[index];
  18796. if (parsedMaterial.id === id) {
  18797. return parseMaterial(parsedMaterial, scene, rootUrl);
  18798. }
  18799. }
  18800. return null;
  18801. };
  18802. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18803. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18804. multiMaterial.id = parsedMultiMaterial.id;
  18805. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18806. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18807. var subMatId = parsedMultiMaterial.materials[matIndex];
  18808. if (subMatId) {
  18809. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18810. }
  18811. else {
  18812. multiMaterial.subMaterials.push(null);
  18813. }
  18814. }
  18815. return multiMaterial;
  18816. };
  18817. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18818. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18819. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18820. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18821. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18822. var parsedFlare = parsedLensFlareSystem.flares[index];
  18823. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18824. }
  18825. return lensFlareSystem;
  18826. };
  18827. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18828. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18829. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18830. if (parsedParticleSystem.textureName) {
  18831. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18832. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18833. }
  18834. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18835. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18836. particleSystem.minSize = parsedParticleSystem.minSize;
  18837. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18838. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18839. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18840. particleSystem.emitter = emitter;
  18841. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18842. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18843. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18844. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18845. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18846. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18847. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18848. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18849. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18850. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18851. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18852. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18853. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18854. particleSystem.start();
  18855. return particleSystem;
  18856. };
  18857. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18858. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18859. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18860. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18861. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18862. shadowGenerator.getShadowMap().renderList.push(mesh);
  18863. }
  18864. if (parsedShadowGenerator.usePoissonSampling) {
  18865. shadowGenerator.usePoissonSampling = true;
  18866. }
  18867. else if (parsedShadowGenerator.useVarianceShadowMap) {
  18868. shadowGenerator.useVarianceShadowMap = true;
  18869. }
  18870. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  18871. shadowGenerator.useBlurVarianceShadowMap = true;
  18872. }
  18873. if (parsedShadowGenerator.bias) {
  18874. shadowGenerator.setBias(parsedShadowGenerator.bias);
  18875. }
  18876. return shadowGenerator;
  18877. };
  18878. var parseAnimation = function (parsedAnimation) {
  18879. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18880. var dataType = parsedAnimation.dataType;
  18881. var keys = [];
  18882. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18883. var key = parsedAnimation.keys[index];
  18884. var data;
  18885. switch (dataType) {
  18886. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18887. data = key.values[0];
  18888. break;
  18889. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18890. data = BABYLON.Quaternion.FromArray(key.values);
  18891. break;
  18892. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18893. data = BABYLON.Matrix.FromArray(key.values);
  18894. break;
  18895. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18896. default:
  18897. data = BABYLON.Vector3.FromArray(key.values);
  18898. break;
  18899. }
  18900. keys.push({
  18901. frame: key.frame,
  18902. value: data
  18903. });
  18904. }
  18905. animation.setKeys(keys);
  18906. return animation;
  18907. };
  18908. var parseLight = function (parsedLight, scene) {
  18909. var light;
  18910. switch (parsedLight.type) {
  18911. case 0:
  18912. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18913. break;
  18914. case 1:
  18915. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18916. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18917. break;
  18918. case 2:
  18919. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18920. break;
  18921. case 3:
  18922. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18923. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18924. break;
  18925. }
  18926. light.id = parsedLight.id;
  18927. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18928. if (parsedLight.intensity !== undefined) {
  18929. light.intensity = parsedLight.intensity;
  18930. }
  18931. if (parsedLight.range) {
  18932. light.range = parsedLight.range;
  18933. }
  18934. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18935. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18936. if (parsedLight.excludedMeshesIds) {
  18937. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18938. }
  18939. // Parent
  18940. if (parsedLight.parentId) {
  18941. light._waitingParentId = parsedLight.parentId;
  18942. }
  18943. if (parsedLight.includedOnlyMeshesIds) {
  18944. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18945. }
  18946. // Animations
  18947. if (parsedLight.animations) {
  18948. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18949. var parsedAnimation = parsedLight.animations[animationIndex];
  18950. light.animations.push(parseAnimation(parsedAnimation));
  18951. }
  18952. }
  18953. if (parsedLight.autoAnimate) {
  18954. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18955. }
  18956. };
  18957. var parseCamera = function (parsedCamera, scene) {
  18958. var camera;
  18959. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18960. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18961. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18962. var alpha = parsedCamera.alpha;
  18963. var beta = parsedCamera.beta;
  18964. var radius = parsedCamera.radius;
  18965. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18966. var eye_space = parsedCamera.eye_space;
  18967. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18968. }
  18969. else {
  18970. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18971. }
  18972. }
  18973. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18974. eye_space = parsedCamera.eye_space;
  18975. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18976. }
  18977. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18978. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18979. }
  18980. else if (parsedCamera.type === "FollowCamera") {
  18981. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18982. camera.heightOffset = parsedCamera.heightOffset;
  18983. camera.radius = parsedCamera.radius;
  18984. camera.rotationOffset = parsedCamera.rotationOffset;
  18985. if (lockedTargetMesh)
  18986. camera.target = lockedTargetMesh;
  18987. }
  18988. else if (parsedCamera.type === "GamepadCamera") {
  18989. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18990. }
  18991. else if (parsedCamera.type === "OculusCamera") {
  18992. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18993. }
  18994. else if (parsedCamera.type === "OculusGamepadCamera") {
  18995. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18996. }
  18997. else if (parsedCamera.type === "TouchCamera") {
  18998. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18999. }
  19000. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19001. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19002. }
  19003. else if (parsedCamera.type === "WebVRCamera") {
  19004. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19005. }
  19006. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19007. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19008. }
  19009. else {
  19010. // Free Camera is the default value
  19011. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19012. }
  19013. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19014. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19015. camera.lockedTarget = lockedTargetMesh;
  19016. }
  19017. camera.id = parsedCamera.id;
  19018. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19019. // Parent
  19020. if (parsedCamera.parentId) {
  19021. camera._waitingParentId = parsedCamera.parentId;
  19022. }
  19023. // Target
  19024. if (parsedCamera.target) {
  19025. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19026. }
  19027. else {
  19028. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19029. }
  19030. camera.fov = parsedCamera.fov;
  19031. camera.minZ = parsedCamera.minZ;
  19032. camera.maxZ = parsedCamera.maxZ;
  19033. camera.speed = parsedCamera.speed;
  19034. camera.inertia = parsedCamera.inertia;
  19035. camera.checkCollisions = parsedCamera.checkCollisions;
  19036. camera.applyGravity = parsedCamera.applyGravity;
  19037. if (parsedCamera.ellipsoid) {
  19038. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19039. }
  19040. // Animations
  19041. if (parsedCamera.animations) {
  19042. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19043. var parsedAnimation = parsedCamera.animations[animationIndex];
  19044. camera.animations.push(parseAnimation(parsedAnimation));
  19045. }
  19046. }
  19047. if (parsedCamera.autoAnimate) {
  19048. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19049. }
  19050. // Layer Mask
  19051. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19052. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19053. }
  19054. else {
  19055. camera.layerMask = 0xFFFFFFFF;
  19056. }
  19057. return camera;
  19058. };
  19059. var parseGeometry = function (parsedGeometry, scene) {
  19060. var id = parsedGeometry.id;
  19061. return scene.getGeometryByID(id);
  19062. };
  19063. var parseBox = function (parsedBox, scene) {
  19064. if (parseGeometry(parsedBox, scene)) {
  19065. return null; // null since geometry could be something else than a box...
  19066. }
  19067. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19068. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19069. scene.pushGeometry(box, true);
  19070. return box;
  19071. };
  19072. var parseSphere = function (parsedSphere, scene) {
  19073. if (parseGeometry(parsedSphere, scene)) {
  19074. return null; // null since geometry could be something else than a sphere...
  19075. }
  19076. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19077. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19078. scene.pushGeometry(sphere, true);
  19079. return sphere;
  19080. };
  19081. var parseCylinder = function (parsedCylinder, scene) {
  19082. if (parseGeometry(parsedCylinder, scene)) {
  19083. return null; // null since geometry could be something else than a cylinder...
  19084. }
  19085. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19086. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19087. scene.pushGeometry(cylinder, true);
  19088. return cylinder;
  19089. };
  19090. var parseTorus = function (parsedTorus, scene) {
  19091. if (parseGeometry(parsedTorus, scene)) {
  19092. return null; // null since geometry could be something else than a torus...
  19093. }
  19094. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19095. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19096. scene.pushGeometry(torus, true);
  19097. return torus;
  19098. };
  19099. var parseGround = function (parsedGround, scene) {
  19100. if (parseGeometry(parsedGround, scene)) {
  19101. return null; // null since geometry could be something else than a ground...
  19102. }
  19103. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19104. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19105. scene.pushGeometry(ground, true);
  19106. return ground;
  19107. };
  19108. var parsePlane = function (parsedPlane, scene) {
  19109. if (parseGeometry(parsedPlane, scene)) {
  19110. return null; // null since geometry could be something else than a plane...
  19111. }
  19112. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19113. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19114. scene.pushGeometry(plane, true);
  19115. return plane;
  19116. };
  19117. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19118. if (parseGeometry(parsedTorusKnot, scene)) {
  19119. return null; // null since geometry could be something else than a torusKnot...
  19120. }
  19121. 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);
  19122. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19123. scene.pushGeometry(torusKnot, true);
  19124. return torusKnot;
  19125. };
  19126. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19127. if (parseGeometry(parsedVertexData, scene)) {
  19128. return null; // null since geometry could be a primitive
  19129. }
  19130. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19131. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19132. if (parsedVertexData.delayLoadingFile) {
  19133. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19134. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19135. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19136. geometry._delayInfo = [];
  19137. if (parsedVertexData.hasUVs) {
  19138. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19139. }
  19140. if (parsedVertexData.hasUVs2) {
  19141. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19142. }
  19143. if (parsedVertexData.hasColors) {
  19144. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19145. }
  19146. if (parsedVertexData.hasMatricesIndices) {
  19147. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19148. }
  19149. if (parsedVertexData.hasMatricesWeights) {
  19150. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19151. }
  19152. geometry._delayLoadingFunction = importVertexData;
  19153. }
  19154. else {
  19155. importVertexData(parsedVertexData, geometry);
  19156. }
  19157. scene.pushGeometry(geometry, true);
  19158. return geometry;
  19159. };
  19160. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19161. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19162. mesh.id = parsedMesh.id;
  19163. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19164. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19165. if (parsedMesh.rotationQuaternion) {
  19166. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19167. }
  19168. else if (parsedMesh.rotation) {
  19169. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19170. }
  19171. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19172. if (parsedMesh.localMatrix) {
  19173. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19174. }
  19175. else if (parsedMesh.pivotMatrix) {
  19176. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19177. }
  19178. mesh.setEnabled(parsedMesh.isEnabled);
  19179. mesh.isVisible = parsedMesh.isVisible;
  19180. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19181. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19182. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19183. if (parsedMesh.applyFog !== undefined) {
  19184. mesh.applyFog = parsedMesh.applyFog;
  19185. }
  19186. if (parsedMesh.pickable !== undefined) {
  19187. mesh.isPickable = parsedMesh.pickable;
  19188. }
  19189. if (parsedMesh.alphaIndex !== undefined) {
  19190. mesh.alphaIndex = parsedMesh.alphaIndex;
  19191. }
  19192. mesh.receiveShadows = parsedMesh.receiveShadows;
  19193. mesh.billboardMode = parsedMesh.billboardMode;
  19194. if (parsedMesh.visibility !== undefined) {
  19195. mesh.visibility = parsedMesh.visibility;
  19196. }
  19197. mesh.checkCollisions = parsedMesh.checkCollisions;
  19198. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19199. // Parent
  19200. if (parsedMesh.parentId) {
  19201. mesh._waitingParentId = parsedMesh.parentId;
  19202. }
  19203. // Actions
  19204. if (parsedMesh.actions !== undefined) {
  19205. mesh._waitingActions = parsedMesh.actions;
  19206. }
  19207. // Geometry
  19208. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19209. if (parsedMesh.delayLoadingFile) {
  19210. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19211. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19212. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19213. if (parsedMesh._binaryInfo) {
  19214. mesh._binaryInfo = parsedMesh._binaryInfo;
  19215. }
  19216. mesh._delayInfo = [];
  19217. if (parsedMesh.hasUVs) {
  19218. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19219. }
  19220. if (parsedMesh.hasUVs2) {
  19221. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19222. }
  19223. if (parsedMesh.hasColors) {
  19224. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19225. }
  19226. if (parsedMesh.hasMatricesIndices) {
  19227. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19228. }
  19229. if (parsedMesh.hasMatricesWeights) {
  19230. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19231. }
  19232. mesh._delayLoadingFunction = importGeometry;
  19233. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19234. mesh._checkDelayState();
  19235. }
  19236. }
  19237. else {
  19238. importGeometry(parsedMesh, mesh);
  19239. }
  19240. // Material
  19241. if (parsedMesh.materialId) {
  19242. mesh.setMaterialByID(parsedMesh.materialId);
  19243. }
  19244. else {
  19245. mesh.material = null;
  19246. }
  19247. // Skeleton
  19248. if (parsedMesh.skeletonId > -1) {
  19249. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19250. }
  19251. // Physics
  19252. if (parsedMesh.physicsImpostor) {
  19253. if (!scene.isPhysicsEnabled()) {
  19254. scene.enablePhysics();
  19255. }
  19256. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19257. }
  19258. // Animations
  19259. if (parsedMesh.animations) {
  19260. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19261. var parsedAnimation = parsedMesh.animations[animationIndex];
  19262. mesh.animations.push(parseAnimation(parsedAnimation));
  19263. }
  19264. }
  19265. if (parsedMesh.autoAnimate) {
  19266. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19267. }
  19268. // Layer Mask
  19269. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19270. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19271. }
  19272. else {
  19273. mesh.layerMask = 0xFFFFFFFF;
  19274. }
  19275. // Instances
  19276. if (parsedMesh.instances) {
  19277. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19278. var parsedInstance = parsedMesh.instances[index];
  19279. var instance = mesh.createInstance(parsedInstance.name);
  19280. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19281. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19282. if (parsedInstance.rotationQuaternion) {
  19283. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19284. }
  19285. else if (parsedInstance.rotation) {
  19286. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19287. }
  19288. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19289. instance.checkCollisions = mesh.checkCollisions;
  19290. if (parsedMesh.animations) {
  19291. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19292. parsedAnimation = parsedMesh.animations[animationIndex];
  19293. instance.animations.push(parseAnimation(parsedAnimation));
  19294. }
  19295. }
  19296. }
  19297. }
  19298. return mesh;
  19299. };
  19300. var parseActions = function (parsedActions, object, scene) {
  19301. var actionManager = new BABYLON.ActionManager(scene);
  19302. if (object === null)
  19303. scene.actionManager = actionManager;
  19304. else
  19305. object.actionManager = actionManager;
  19306. // instanciate a new object
  19307. var instanciate = function (name, params) {
  19308. var newInstance = Object.create(BABYLON[name].prototype);
  19309. newInstance.constructor.apply(newInstance, params);
  19310. return newInstance;
  19311. };
  19312. var parseParameter = function (name, value, target, propertyPath) {
  19313. if (propertyPath === null) {
  19314. // String, boolean or float
  19315. var floatValue = parseFloat(value);
  19316. if (value === "true" || value === "false")
  19317. return value === "true";
  19318. else
  19319. return isNaN(floatValue) ? value : floatValue;
  19320. }
  19321. var effectiveTarget = propertyPath.split(".");
  19322. var values = value.split(",");
  19323. for (var i = 0; i < effectiveTarget.length; i++) {
  19324. target = target[effectiveTarget[i]];
  19325. }
  19326. // Return appropriate value with its type
  19327. if (target instanceof Boolean)
  19328. return values[0] === "true";
  19329. if (target instanceof String)
  19330. return values[0];
  19331. // Parameters with multiple values such as Vector3 etc.
  19332. var split = new Array();
  19333. for (var i = 0; i < values.length; i++)
  19334. split.push(parseFloat(values[i]));
  19335. if (target instanceof BABYLON.Vector3)
  19336. return BABYLON.Vector3.FromArray(split);
  19337. if (target instanceof BABYLON.Vector4)
  19338. return BABYLON.Vector4.FromArray(split);
  19339. if (target instanceof BABYLON.Color3)
  19340. return BABYLON.Color3.FromArray(split);
  19341. if (target instanceof BABYLON.Color4)
  19342. return BABYLON.Color4.FromArray(split);
  19343. return parseFloat(values[0]);
  19344. };
  19345. // traverse graph per trigger
  19346. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19347. if (combineArray === void 0) { combineArray = null; }
  19348. if (parsedAction.detached)
  19349. return;
  19350. var parameters = new Array();
  19351. var target = null;
  19352. var propertyPath = null;
  19353. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19354. // Parameters
  19355. if (parsedAction.type === 2)
  19356. parameters.push(actionManager);
  19357. else
  19358. parameters.push(trigger);
  19359. if (combine) {
  19360. var actions = new Array();
  19361. for (var j = 0; j < parsedAction.combine.length; j++) {
  19362. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19363. }
  19364. parameters.push(actions);
  19365. }
  19366. else {
  19367. for (var i = 0; i < parsedAction.properties.length; i++) {
  19368. var value = parsedAction.properties[i].value;
  19369. var name = parsedAction.properties[i].name;
  19370. if (name === "target")
  19371. value = target = scene.getNodeByName(value);
  19372. else if (name === "parent")
  19373. value = scene.getNodeByName(value);
  19374. else if (name === "sound")
  19375. value = scene.getSoundByName(value);
  19376. else if (name !== "propertyPath") {
  19377. if (parsedAction.type === 2 && name === "operator")
  19378. value = BABYLON.ValueCondition[value];
  19379. else
  19380. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19381. }
  19382. else {
  19383. propertyPath = value;
  19384. }
  19385. parameters.push(value);
  19386. }
  19387. }
  19388. parameters.push(condition);
  19389. // If interpolate value action
  19390. if (parsedAction.name === "InterpolateValueAction") {
  19391. var param = parameters[parameters.length - 2];
  19392. parameters[parameters.length - 1] = param;
  19393. parameters[parameters.length - 2] = condition;
  19394. }
  19395. // Action or condition(s) and not CombineAction
  19396. var newAction = instanciate(parsedAction.name, parameters);
  19397. if (combineArray === null) {
  19398. if (newAction instanceof BABYLON.Condition) {
  19399. condition = newAction;
  19400. newAction = action;
  19401. }
  19402. else {
  19403. condition = null;
  19404. if (action)
  19405. action.then(newAction);
  19406. else
  19407. actionManager.registerAction(newAction);
  19408. }
  19409. }
  19410. else {
  19411. if (combineArray !== null)
  19412. combineArray.push(newAction);
  19413. }
  19414. for (var i = 0; i < parsedAction.children.length; i++)
  19415. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19416. };
  19417. for (var i = 0; i < parsedActions.children.length; i++) {
  19418. var triggerParams;
  19419. var trigger = parsedActions.children[i];
  19420. if (trigger.properties.length > 0) {
  19421. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19422. }
  19423. else
  19424. triggerParams = BABYLON.ActionManager[trigger.name];
  19425. for (var j = 0; j < trigger.children.length; j++)
  19426. traverse(trigger.children[j], triggerParams, null, null);
  19427. }
  19428. };
  19429. var parseSound = function (parsedSound, scene, rootUrl) {
  19430. var soundName = parsedSound.name;
  19431. var soundUrl = rootUrl + soundName;
  19432. var options = {
  19433. autoplay: parsedSound.autoplay,
  19434. loop: parsedSound.loop,
  19435. volume: parsedSound.volume,
  19436. spatialSound: parsedSound.spatialSound,
  19437. maxDistance: parsedSound.maxDistance,
  19438. rolloffFactor: parsedSound.rolloffFactor,
  19439. refDistance: parsedSound.refDistance,
  19440. distanceModel: parsedSound.distanceModel,
  19441. panningModel: parsedSound.panningModel,
  19442. playbackRate: parsedSound.playbackRate
  19443. };
  19444. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19445. scene._removePendingData(newSound);
  19446. }, options);
  19447. scene._addPendingData(newSound);
  19448. if (parsedSound.position) {
  19449. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19450. newSound.setPosition(soundPosition);
  19451. }
  19452. if (parsedSound.isDirectional) {
  19453. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19454. if (parsedSound.localDirectionToMesh) {
  19455. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19456. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19457. }
  19458. }
  19459. if (parsedSound.connectedMeshId) {
  19460. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19461. if (connectedMesh) {
  19462. newSound.attachToMesh(connectedMesh);
  19463. }
  19464. }
  19465. };
  19466. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19467. names = (names instanceof Array) ? names : [names];
  19468. for (var i in names) {
  19469. if (mesh.name === names[i]) {
  19470. hierarchyIds.push(mesh.id);
  19471. return true;
  19472. }
  19473. }
  19474. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19475. hierarchyIds.push(mesh.id);
  19476. return true;
  19477. }
  19478. return false;
  19479. };
  19480. var importVertexData = function (parsedVertexData, geometry) {
  19481. var vertexData = new BABYLON.VertexData();
  19482. // positions
  19483. var positions = parsedVertexData.positions;
  19484. if (positions) {
  19485. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19486. }
  19487. // normals
  19488. var normals = parsedVertexData.normals;
  19489. if (normals) {
  19490. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19491. }
  19492. // uvs
  19493. var uvs = parsedVertexData.uvs;
  19494. if (uvs) {
  19495. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19496. }
  19497. // uv2s
  19498. var uv2s = parsedVertexData.uv2s;
  19499. if (uv2s) {
  19500. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19501. }
  19502. // colors
  19503. var colors = parsedVertexData.colors;
  19504. if (colors) {
  19505. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19506. }
  19507. // matricesIndices
  19508. var matricesIndices = parsedVertexData.matricesIndices;
  19509. if (matricesIndices) {
  19510. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19511. }
  19512. // matricesWeights
  19513. var matricesWeights = parsedVertexData.matricesWeights;
  19514. if (matricesWeights) {
  19515. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19516. }
  19517. // indices
  19518. var indices = parsedVertexData.indices;
  19519. if (indices) {
  19520. vertexData.indices = indices;
  19521. }
  19522. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19523. };
  19524. var importGeometry = function (parsedGeometry, mesh) {
  19525. var scene = mesh.getScene();
  19526. // Geometry
  19527. var geometryId = parsedGeometry.geometryId;
  19528. if (geometryId) {
  19529. var geometry = scene.getGeometryByID(geometryId);
  19530. if (geometry) {
  19531. geometry.applyToMesh(mesh);
  19532. }
  19533. }
  19534. else if (parsedGeometry instanceof ArrayBuffer) {
  19535. var binaryInfo = mesh._binaryInfo;
  19536. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19537. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19538. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19539. }
  19540. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19541. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19542. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19543. }
  19544. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19545. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19546. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19547. }
  19548. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19549. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19550. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19551. }
  19552. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19553. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19554. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19555. }
  19556. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19557. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19558. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19559. }
  19560. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19561. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19562. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19563. }
  19564. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19565. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19566. mesh.setIndices(indicesData);
  19567. }
  19568. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19569. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19570. mesh.subMeshes = [];
  19571. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19572. var materialIndex = subMeshesData[(i * 5) + 0];
  19573. var verticesStart = subMeshesData[(i * 5) + 1];
  19574. var verticesCount = subMeshesData[(i * 5) + 2];
  19575. var indexStart = subMeshesData[(i * 5) + 3];
  19576. var indexCount = subMeshesData[(i * 5) + 4];
  19577. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19578. }
  19579. }
  19580. }
  19581. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19582. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19583. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19584. if (parsedGeometry.uvs) {
  19585. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19586. }
  19587. if (parsedGeometry.uvs2) {
  19588. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19589. }
  19590. if (parsedGeometry.colors) {
  19591. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19592. }
  19593. if (parsedGeometry.matricesIndices) {
  19594. if (!parsedGeometry.matricesIndices._isExpanded) {
  19595. var floatIndices = [];
  19596. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19597. var matricesIndex = parsedGeometry.matricesIndices[i];
  19598. floatIndices.push(matricesIndex & 0x000000FF);
  19599. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19600. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19601. floatIndices.push(matricesIndex >> 24);
  19602. }
  19603. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19604. }
  19605. else {
  19606. delete parsedGeometry.matricesIndices._isExpanded;
  19607. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19608. }
  19609. }
  19610. if (parsedGeometry.matricesWeights) {
  19611. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19612. }
  19613. mesh.setIndices(parsedGeometry.indices);
  19614. // SubMeshes
  19615. if (parsedGeometry.subMeshes) {
  19616. mesh.subMeshes = [];
  19617. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19618. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19619. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19620. }
  19621. }
  19622. }
  19623. // Flat shading
  19624. if (mesh._shouldGenerateFlatShading) {
  19625. mesh.convertToFlatShadedMesh();
  19626. delete mesh._shouldGenerateFlatShading;
  19627. }
  19628. // Update
  19629. mesh.computeWorldMatrix(true);
  19630. // Octree
  19631. if (scene._selectionOctree) {
  19632. scene._selectionOctree.addMesh(mesh);
  19633. }
  19634. };
  19635. BABYLON.SceneLoader.RegisterPlugin({
  19636. extensions: ".babylon",
  19637. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19638. var parsedData = JSON.parse(data);
  19639. var loadedSkeletonsIds = [];
  19640. var loadedMaterialsIds = [];
  19641. var hierarchyIds = [];
  19642. for (var index = 0; index < parsedData.meshes.length; index++) {
  19643. var parsedMesh = parsedData.meshes[index];
  19644. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19645. if (meshesNames instanceof Array) {
  19646. // Remove found mesh name from list.
  19647. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19648. }
  19649. // Material ?
  19650. if (parsedMesh.materialId) {
  19651. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19652. if (!materialFound) {
  19653. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19654. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19655. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19656. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19657. var subMatId = parsedMultiMaterial.materials[matIndex];
  19658. loadedMaterialsIds.push(subMatId);
  19659. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19660. }
  19661. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19662. parseMultiMaterial(parsedMultiMaterial, scene);
  19663. materialFound = true;
  19664. break;
  19665. }
  19666. }
  19667. }
  19668. if (!materialFound) {
  19669. loadedMaterialsIds.push(parsedMesh.materialId);
  19670. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19671. }
  19672. }
  19673. // Skeleton ?
  19674. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19675. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19676. if (!skeletonAlreadyLoaded) {
  19677. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19678. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19679. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19680. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19681. loadedSkeletonsIds.push(parsedSkeleton.id);
  19682. }
  19683. }
  19684. }
  19685. }
  19686. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19687. meshes.push(mesh);
  19688. }
  19689. }
  19690. for (index = 0; index < scene.meshes.length; index++) {
  19691. var currentMesh = scene.meshes[index];
  19692. if (currentMesh._waitingParentId) {
  19693. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19694. currentMesh._waitingParentId = undefined;
  19695. }
  19696. }
  19697. // Particles
  19698. if (parsedData.particleSystems) {
  19699. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19700. var parsedParticleSystem = parsedData.particleSystems[index];
  19701. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19702. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19703. }
  19704. }
  19705. }
  19706. return true;
  19707. },
  19708. load: function (scene, data, rootUrl) {
  19709. var parsedData = JSON.parse(data);
  19710. // Scene
  19711. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19712. scene.autoClear = parsedData.autoClear;
  19713. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19714. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19715. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19716. // Fog
  19717. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19718. scene.fogMode = parsedData.fogMode;
  19719. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19720. scene.fogStart = parsedData.fogStart;
  19721. scene.fogEnd = parsedData.fogEnd;
  19722. scene.fogDensity = parsedData.fogDensity;
  19723. }
  19724. for (var index = 0; index < parsedData.lights.length; index++) {
  19725. var parsedLight = parsedData.lights[index];
  19726. parseLight(parsedLight, scene);
  19727. }
  19728. // Materials
  19729. if (parsedData.materials) {
  19730. for (index = 0; index < parsedData.materials.length; index++) {
  19731. var parsedMaterial = parsedData.materials[index];
  19732. parseMaterial(parsedMaterial, scene, rootUrl);
  19733. }
  19734. }
  19735. if (parsedData.multiMaterials) {
  19736. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19737. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19738. parseMultiMaterial(parsedMultiMaterial, scene);
  19739. }
  19740. }
  19741. // Skeletons
  19742. if (parsedData.skeletons) {
  19743. for (index = 0; index < parsedData.skeletons.length; index++) {
  19744. var parsedSkeleton = parsedData.skeletons[index];
  19745. parseSkeleton(parsedSkeleton, scene);
  19746. }
  19747. }
  19748. // Geometries
  19749. var geometries = parsedData.geometries;
  19750. if (geometries) {
  19751. // Boxes
  19752. var boxes = geometries.boxes;
  19753. if (boxes) {
  19754. for (index = 0; index < boxes.length; index++) {
  19755. var parsedBox = boxes[index];
  19756. parseBox(parsedBox, scene);
  19757. }
  19758. }
  19759. // Spheres
  19760. var spheres = geometries.spheres;
  19761. if (spheres) {
  19762. for (index = 0; index < spheres.length; index++) {
  19763. var parsedSphere = spheres[index];
  19764. parseSphere(parsedSphere, scene);
  19765. }
  19766. }
  19767. // Cylinders
  19768. var cylinders = geometries.cylinders;
  19769. if (cylinders) {
  19770. for (index = 0; index < cylinders.length; index++) {
  19771. var parsedCylinder = cylinders[index];
  19772. parseCylinder(parsedCylinder, scene);
  19773. }
  19774. }
  19775. // Toruses
  19776. var toruses = geometries.toruses;
  19777. if (toruses) {
  19778. for (index = 0; index < toruses.length; index++) {
  19779. var parsedTorus = toruses[index];
  19780. parseTorus(parsedTorus, scene);
  19781. }
  19782. }
  19783. // Grounds
  19784. var grounds = geometries.grounds;
  19785. if (grounds) {
  19786. for (index = 0; index < grounds.length; index++) {
  19787. var parsedGround = grounds[index];
  19788. parseGround(parsedGround, scene);
  19789. }
  19790. }
  19791. // Planes
  19792. var planes = geometries.planes;
  19793. if (planes) {
  19794. for (index = 0; index < planes.length; index++) {
  19795. var parsedPlane = planes[index];
  19796. parsePlane(parsedPlane, scene);
  19797. }
  19798. }
  19799. // TorusKnots
  19800. var torusKnots = geometries.torusKnots;
  19801. if (torusKnots) {
  19802. for (index = 0; index < torusKnots.length; index++) {
  19803. var parsedTorusKnot = torusKnots[index];
  19804. parseTorusKnot(parsedTorusKnot, scene);
  19805. }
  19806. }
  19807. // VertexData
  19808. var vertexData = geometries.vertexData;
  19809. if (vertexData) {
  19810. for (index = 0; index < vertexData.length; index++) {
  19811. var parsedVertexData = vertexData[index];
  19812. parseVertexData(parsedVertexData, scene, rootUrl);
  19813. }
  19814. }
  19815. }
  19816. for (index = 0; index < parsedData.meshes.length; index++) {
  19817. var parsedMesh = parsedData.meshes[index];
  19818. parseMesh(parsedMesh, scene, rootUrl);
  19819. }
  19820. for (index = 0; index < parsedData.cameras.length; index++) {
  19821. var parsedCamera = parsedData.cameras[index];
  19822. parseCamera(parsedCamera, scene);
  19823. }
  19824. if (parsedData.activeCameraID) {
  19825. scene.setActiveCameraByID(parsedData.activeCameraID);
  19826. }
  19827. for (index = 0; index < scene.cameras.length; index++) {
  19828. var camera = scene.cameras[index];
  19829. if (camera._waitingParentId) {
  19830. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19831. camera._waitingParentId = undefined;
  19832. }
  19833. }
  19834. for (index = 0; index < scene.lights.length; index++) {
  19835. var light = scene.lights[index];
  19836. if (light._waitingParentId) {
  19837. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19838. light._waitingParentId = undefined;
  19839. }
  19840. }
  19841. // Sounds
  19842. if (parsedData.sounds) {
  19843. for (index = 0; index < parsedData.sounds.length; index++) {
  19844. var parsedSound = parsedData.sounds[index];
  19845. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19846. parseSound(parsedSound, scene, rootUrl);
  19847. }
  19848. else {
  19849. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19850. }
  19851. }
  19852. }
  19853. for (index = 0; index < scene.meshes.length; index++) {
  19854. var mesh = scene.meshes[index];
  19855. if (mesh._waitingParentId) {
  19856. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19857. mesh._waitingParentId = undefined;
  19858. }
  19859. if (mesh._waitingActions) {
  19860. parseActions(mesh._waitingActions, mesh, scene);
  19861. mesh._waitingActions = undefined;
  19862. }
  19863. }
  19864. // Particles Systems
  19865. if (parsedData.particleSystems) {
  19866. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19867. var parsedParticleSystem = parsedData.particleSystems[index];
  19868. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19869. }
  19870. }
  19871. // Lens flares
  19872. if (parsedData.lensFlareSystems) {
  19873. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19874. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19875. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19876. }
  19877. }
  19878. // Shadows
  19879. if (parsedData.shadowGenerators) {
  19880. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19881. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19882. parseShadowGenerator(parsedShadowGenerator, scene);
  19883. }
  19884. }
  19885. // Actions (scene)
  19886. if (parsedData.actions) {
  19887. parseActions(parsedData.actions, null, scene);
  19888. }
  19889. // Finish
  19890. return true;
  19891. }
  19892. });
  19893. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19894. })(BABYLON || (BABYLON = {}));
  19895. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19896. (function (BABYLON) {
  19897. // Unique ID when we import meshes from Babylon to CSG
  19898. var currentCSGMeshId = 0;
  19899. // # class Vertex
  19900. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19901. // one to provide additional features like texture coordinates and vertex
  19902. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19903. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19904. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19905. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19906. // is not used anywhere else.
  19907. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19908. var Vertex = (function () {
  19909. function Vertex(pos, normal, uv) {
  19910. this.pos = pos;
  19911. this.normal = normal;
  19912. this.uv = uv;
  19913. }
  19914. Vertex.prototype.clone = function () {
  19915. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19916. };
  19917. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19918. // orientation of a polygon is flipped.
  19919. Vertex.prototype.flip = function () {
  19920. this.normal = this.normal.scale(-1);
  19921. };
  19922. // Create a new vertex between this vertex and `other` by linearly
  19923. // interpolating all properties using a parameter of `t`. Subclasses should
  19924. // override this to interpolate additional properties.
  19925. Vertex.prototype.interpolate = function (other, t) {
  19926. 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));
  19927. };
  19928. return Vertex;
  19929. })();
  19930. // # class Plane
  19931. // Represents a plane in 3D space.
  19932. var Plane = (function () {
  19933. function Plane(normal, w) {
  19934. this.normal = normal;
  19935. this.w = w;
  19936. }
  19937. Plane.FromPoints = function (a, b, c) {
  19938. var v0 = c.subtract(a);
  19939. var v1 = b.subtract(a);
  19940. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19941. return null;
  19942. }
  19943. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19944. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19945. };
  19946. Plane.prototype.clone = function () {
  19947. return new Plane(this.normal.clone(), this.w);
  19948. };
  19949. Plane.prototype.flip = function () {
  19950. this.normal.scaleInPlace(-1);
  19951. this.w = -this.w;
  19952. };
  19953. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19954. // fragments in the appropriate lists. Coplanar polygons go into either
  19955. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19956. // respect to this plane. Polygons in front or in back of this plane go into
  19957. // either `front` or `back`.
  19958. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19959. var COPLANAR = 0;
  19960. var FRONT = 1;
  19961. var BACK = 2;
  19962. var SPANNING = 3;
  19963. // Classify each point as well as the entire polygon into one of the above
  19964. // four classes.
  19965. var polygonType = 0;
  19966. var types = [];
  19967. for (var i = 0; i < polygon.vertices.length; i++) {
  19968. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19969. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19970. polygonType |= type;
  19971. types.push(type);
  19972. }
  19973. switch (polygonType) {
  19974. case COPLANAR:
  19975. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19976. break;
  19977. case FRONT:
  19978. front.push(polygon);
  19979. break;
  19980. case BACK:
  19981. back.push(polygon);
  19982. break;
  19983. case SPANNING:
  19984. var f = [], b = [];
  19985. for (i = 0; i < polygon.vertices.length; i++) {
  19986. var j = (i + 1) % polygon.vertices.length;
  19987. var ti = types[i], tj = types[j];
  19988. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19989. if (ti != BACK)
  19990. f.push(vi);
  19991. if (ti != FRONT)
  19992. b.push(ti != BACK ? vi.clone() : vi);
  19993. if ((ti | tj) == SPANNING) {
  19994. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19995. var v = vi.interpolate(vj, t);
  19996. f.push(v);
  19997. b.push(v.clone());
  19998. }
  19999. }
  20000. if (f.length >= 3) {
  20001. var poly = new Polygon(f, polygon.shared);
  20002. if (poly.plane)
  20003. front.push(poly);
  20004. }
  20005. if (b.length >= 3) {
  20006. poly = new Polygon(b, polygon.shared);
  20007. if (poly.plane)
  20008. back.push(poly);
  20009. }
  20010. break;
  20011. }
  20012. };
  20013. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20014. // point is on the plane.
  20015. Plane.EPSILON = 1e-5;
  20016. return Plane;
  20017. })();
  20018. // # class Polygon
  20019. // Represents a convex polygon. The vertices used to initialize a polygon must
  20020. // be coplanar and form a convex loop.
  20021. //
  20022. // Each convex polygon has a `shared` property, which is shared between all
  20023. // polygons that are clones of each other or were split from the same polygon.
  20024. // This can be used to define per-polygon properties (such as surface color).
  20025. var Polygon = (function () {
  20026. function Polygon(vertices, shared) {
  20027. this.vertices = vertices;
  20028. this.shared = shared;
  20029. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20030. }
  20031. Polygon.prototype.clone = function () {
  20032. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20033. return new Polygon(vertices, this.shared);
  20034. };
  20035. Polygon.prototype.flip = function () {
  20036. this.vertices.reverse().map(function (v) {
  20037. v.flip();
  20038. });
  20039. this.plane.flip();
  20040. };
  20041. return Polygon;
  20042. })();
  20043. // # class Node
  20044. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20045. // by picking a polygon to split along. That polygon (and all other coplanar
  20046. // polygons) are added directly to that node and the other polygons are added to
  20047. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20048. // no distinction between internal and leaf nodes.
  20049. var Node = (function () {
  20050. function Node(polygons) {
  20051. this.plane = null;
  20052. this.front = null;
  20053. this.back = null;
  20054. this.polygons = [];
  20055. if (polygons) {
  20056. this.build(polygons);
  20057. }
  20058. }
  20059. Node.prototype.clone = function () {
  20060. var node = new Node();
  20061. node.plane = this.plane && this.plane.clone();
  20062. node.front = this.front && this.front.clone();
  20063. node.back = this.back && this.back.clone();
  20064. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20065. return node;
  20066. };
  20067. // Convert solid space to empty space and empty space to solid space.
  20068. Node.prototype.invert = function () {
  20069. for (var i = 0; i < this.polygons.length; i++) {
  20070. this.polygons[i].flip();
  20071. }
  20072. if (this.plane) {
  20073. this.plane.flip();
  20074. }
  20075. if (this.front) {
  20076. this.front.invert();
  20077. }
  20078. if (this.back) {
  20079. this.back.invert();
  20080. }
  20081. var temp = this.front;
  20082. this.front = this.back;
  20083. this.back = temp;
  20084. };
  20085. // Recursively remove all polygons in `polygons` that are inside this BSP
  20086. // tree.
  20087. Node.prototype.clipPolygons = function (polygons) {
  20088. if (!this.plane)
  20089. return polygons.slice();
  20090. var front = [], back = [];
  20091. for (var i = 0; i < polygons.length; i++) {
  20092. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20093. }
  20094. if (this.front) {
  20095. front = this.front.clipPolygons(front);
  20096. }
  20097. if (this.back) {
  20098. back = this.back.clipPolygons(back);
  20099. }
  20100. else {
  20101. back = [];
  20102. }
  20103. return front.concat(back);
  20104. };
  20105. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20106. // `bsp`.
  20107. Node.prototype.clipTo = function (bsp) {
  20108. this.polygons = bsp.clipPolygons(this.polygons);
  20109. if (this.front)
  20110. this.front.clipTo(bsp);
  20111. if (this.back)
  20112. this.back.clipTo(bsp);
  20113. };
  20114. // Return a list of all polygons in this BSP tree.
  20115. Node.prototype.allPolygons = function () {
  20116. var polygons = this.polygons.slice();
  20117. if (this.front)
  20118. polygons = polygons.concat(this.front.allPolygons());
  20119. if (this.back)
  20120. polygons = polygons.concat(this.back.allPolygons());
  20121. return polygons;
  20122. };
  20123. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20124. // new polygons are filtered down to the bottom of the tree and become new
  20125. // nodes there. Each set of polygons is partitioned using the first polygon
  20126. // (no heuristic is used to pick a good split).
  20127. Node.prototype.build = function (polygons) {
  20128. if (!polygons.length)
  20129. return;
  20130. if (!this.plane)
  20131. this.plane = polygons[0].plane.clone();
  20132. var front = [], back = [];
  20133. for (var i = 0; i < polygons.length; i++) {
  20134. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20135. }
  20136. if (front.length) {
  20137. if (!this.front)
  20138. this.front = new Node();
  20139. this.front.build(front);
  20140. }
  20141. if (back.length) {
  20142. if (!this.back)
  20143. this.back = new Node();
  20144. this.back.build(back);
  20145. }
  20146. };
  20147. return Node;
  20148. })();
  20149. var CSG = (function () {
  20150. function CSG() {
  20151. this.polygons = new Array();
  20152. }
  20153. // Convert BABYLON.Mesh to BABYLON.CSG
  20154. CSG.FromMesh = function (mesh) {
  20155. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20156. if (mesh instanceof BABYLON.Mesh) {
  20157. mesh.computeWorldMatrix(true);
  20158. var matrix = mesh.getWorldMatrix();
  20159. var meshPosition = mesh.position.clone();
  20160. var meshRotation = mesh.rotation.clone();
  20161. var meshScaling = mesh.scaling.clone();
  20162. }
  20163. else {
  20164. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20165. }
  20166. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20167. var subMeshes = mesh.subMeshes;
  20168. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20169. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20170. vertices = [];
  20171. for (var j = 0; j < 3; j++) {
  20172. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20173. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20174. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20175. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20176. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20177. vertex = new Vertex(position, normal, uv);
  20178. vertices.push(vertex);
  20179. }
  20180. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20181. // To handle the case of degenerated triangle
  20182. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20183. if (polygon.plane)
  20184. polygons.push(polygon);
  20185. }
  20186. }
  20187. var csg = CSG.FromPolygons(polygons);
  20188. csg.matrix = matrix;
  20189. csg.position = meshPosition;
  20190. csg.rotation = meshRotation;
  20191. csg.scaling = meshScaling;
  20192. currentCSGMeshId++;
  20193. return csg;
  20194. };
  20195. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20196. CSG.FromPolygons = function (polygons) {
  20197. var csg = new BABYLON.CSG();
  20198. csg.polygons = polygons;
  20199. return csg;
  20200. };
  20201. CSG.prototype.clone = function () {
  20202. var csg = new BABYLON.CSG();
  20203. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20204. csg.copyTransformAttributes(this);
  20205. return csg;
  20206. };
  20207. CSG.prototype.toPolygons = function () {
  20208. return this.polygons;
  20209. };
  20210. CSG.prototype.union = function (csg) {
  20211. var a = new Node(this.clone().polygons);
  20212. var b = new Node(csg.clone().polygons);
  20213. a.clipTo(b);
  20214. b.clipTo(a);
  20215. b.invert();
  20216. b.clipTo(a);
  20217. b.invert();
  20218. a.build(b.allPolygons());
  20219. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20220. };
  20221. CSG.prototype.unionInPlace = function (csg) {
  20222. var a = new Node(this.polygons);
  20223. var b = new Node(csg.polygons);
  20224. a.clipTo(b);
  20225. b.clipTo(a);
  20226. b.invert();
  20227. b.clipTo(a);
  20228. b.invert();
  20229. a.build(b.allPolygons());
  20230. this.polygons = a.allPolygons();
  20231. };
  20232. CSG.prototype.subtract = function (csg) {
  20233. var a = new Node(this.clone().polygons);
  20234. var b = new Node(csg.clone().polygons);
  20235. a.invert();
  20236. a.clipTo(b);
  20237. b.clipTo(a);
  20238. b.invert();
  20239. b.clipTo(a);
  20240. b.invert();
  20241. a.build(b.allPolygons());
  20242. a.invert();
  20243. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20244. };
  20245. CSG.prototype.subtractInPlace = function (csg) {
  20246. var a = new Node(this.polygons);
  20247. var b = new Node(csg.polygons);
  20248. a.invert();
  20249. a.clipTo(b);
  20250. b.clipTo(a);
  20251. b.invert();
  20252. b.clipTo(a);
  20253. b.invert();
  20254. a.build(b.allPolygons());
  20255. a.invert();
  20256. this.polygons = a.allPolygons();
  20257. };
  20258. CSG.prototype.intersect = function (csg) {
  20259. var a = new Node(this.clone().polygons);
  20260. var b = new Node(csg.clone().polygons);
  20261. a.invert();
  20262. b.clipTo(a);
  20263. b.invert();
  20264. a.clipTo(b);
  20265. b.clipTo(a);
  20266. a.build(b.allPolygons());
  20267. a.invert();
  20268. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20269. };
  20270. CSG.prototype.intersectInPlace = function (csg) {
  20271. var a = new Node(this.polygons);
  20272. var b = new Node(csg.polygons);
  20273. a.invert();
  20274. b.clipTo(a);
  20275. b.invert();
  20276. a.clipTo(b);
  20277. b.clipTo(a);
  20278. a.build(b.allPolygons());
  20279. a.invert();
  20280. this.polygons = a.allPolygons();
  20281. };
  20282. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20283. // not modified.
  20284. CSG.prototype.inverse = function () {
  20285. var csg = this.clone();
  20286. csg.inverseInPlace();
  20287. return csg;
  20288. };
  20289. CSG.prototype.inverseInPlace = function () {
  20290. this.polygons.map(function (p) {
  20291. p.flip();
  20292. });
  20293. };
  20294. // This is used to keep meshes transformations so they can be restored
  20295. // when we build back a Babylon Mesh
  20296. // NB : All CSG operations are performed in world coordinates
  20297. CSG.prototype.copyTransformAttributes = function (csg) {
  20298. this.matrix = csg.matrix;
  20299. this.position = csg.position;
  20300. this.rotation = csg.rotation;
  20301. this.scaling = csg.scaling;
  20302. return this;
  20303. };
  20304. // Build Raw mesh from CSG
  20305. // Coordinates here are in world space
  20306. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20307. var matrix = this.matrix.clone();
  20308. matrix.invert();
  20309. 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;
  20310. if (keepSubMeshes) {
  20311. // Sort Polygons, since subMeshes are indices range
  20312. polygons.sort(function (a, b) {
  20313. if (a.shared.meshId === b.shared.meshId) {
  20314. return a.shared.subMeshId - b.shared.subMeshId;
  20315. }
  20316. else {
  20317. return a.shared.meshId - b.shared.meshId;
  20318. }
  20319. });
  20320. }
  20321. for (var i = 0, il = polygons.length; i < il; i++) {
  20322. polygon = polygons[i];
  20323. // Building SubMeshes
  20324. if (!subMesh_dict[polygon.shared.meshId]) {
  20325. subMesh_dict[polygon.shared.meshId] = {};
  20326. }
  20327. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20328. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20329. indexStart: +Infinity,
  20330. indexEnd: -Infinity,
  20331. materialIndex: polygon.shared.materialIndex
  20332. };
  20333. }
  20334. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20335. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20336. polygonIndices[0] = 0;
  20337. polygonIndices[1] = j - 1;
  20338. polygonIndices[2] = j;
  20339. for (var k = 0; k < 3; k++) {
  20340. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20341. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20342. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20343. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20344. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20345. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20346. // Check if 2 points can be merged
  20347. 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)) {
  20348. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20349. uvs.push(uv.x, uv.y);
  20350. normals.push(normal.x, normal.y, normal.z);
  20351. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20352. }
  20353. indices.push(vertex_idx);
  20354. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20355. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20356. currentIndex++;
  20357. }
  20358. }
  20359. }
  20360. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20361. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20362. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20363. mesh.setIndices(indices);
  20364. if (keepSubMeshes) {
  20365. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20366. var materialIndexOffset = 0, materialMaxIndex;
  20367. mesh.subMeshes.length = 0;
  20368. for (var m in subMesh_dict) {
  20369. materialMaxIndex = -1;
  20370. for (var sm in subMesh_dict[m]) {
  20371. subMesh_obj = subMesh_dict[m][sm];
  20372. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20373. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20374. }
  20375. materialIndexOffset += ++materialMaxIndex;
  20376. }
  20377. }
  20378. return mesh;
  20379. };
  20380. // Build Mesh from CSG taking material and transforms into account
  20381. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20382. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20383. mesh.material = material;
  20384. mesh.position.copyFrom(this.position);
  20385. mesh.rotation.copyFrom(this.rotation);
  20386. mesh.scaling.copyFrom(this.scaling);
  20387. mesh.computeWorldMatrix(true);
  20388. return mesh;
  20389. };
  20390. return CSG;
  20391. })();
  20392. BABYLON.CSG = CSG;
  20393. })(BABYLON || (BABYLON = {}));
  20394. //# sourceMappingURL=babylon.csg.js.map
  20395. var BABYLON;
  20396. (function (BABYLON) {
  20397. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20398. __extends(OculusDistortionCorrectionPostProcess, _super);
  20399. //ANY
  20400. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20401. var _this = this;
  20402. _super.call(this, name, "oculusDistortionCorrection", [
  20403. 'LensCenter',
  20404. 'Scale',
  20405. 'ScaleIn',
  20406. 'HmdWarpParam'
  20407. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20408. this._isRightEye = isRightEye;
  20409. this._distortionFactors = cameraSettings.DistortionK;
  20410. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20411. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20412. this.onSizeChanged = function () {
  20413. _this.aspectRatio = _this.width * .5 / _this.height;
  20414. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20415. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20416. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20417. };
  20418. this.onApply = function (effect) {
  20419. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20420. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20421. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20422. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20423. };
  20424. }
  20425. return OculusDistortionCorrectionPostProcess;
  20426. })(BABYLON.PostProcess);
  20427. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20428. })(BABYLON || (BABYLON = {}));
  20429. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20430. // 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
  20431. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20432. var BABYLON;
  20433. (function (BABYLON) {
  20434. (function (JoystickAxis) {
  20435. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20436. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20437. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20438. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20439. var JoystickAxis = BABYLON.JoystickAxis;
  20440. var VirtualJoystick = (function () {
  20441. function VirtualJoystick(leftJoystick) {
  20442. var _this = this;
  20443. if (leftJoystick) {
  20444. this._leftJoystick = true;
  20445. }
  20446. else {
  20447. this._leftJoystick = false;
  20448. }
  20449. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20450. VirtualJoystick._globalJoystickIndex++;
  20451. // By default left & right arrow keys are moving the X
  20452. // and up & down keys are moving the Y
  20453. this._axisTargetedByLeftAndRight = 0 /* X */;
  20454. this._axisTargetedByUpAndDown = 1 /* Y */;
  20455. this.reverseLeftRight = false;
  20456. this.reverseUpDown = false;
  20457. // collections of pointers
  20458. this._touches = new BABYLON.VirtualJoystick.Collection();
  20459. this.deltaPosition = BABYLON.Vector3.Zero();
  20460. this._joystickSensibility = 25;
  20461. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20462. this._rotationSpeed = 25;
  20463. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20464. this._rotateOnAxisRelativeToMesh = false;
  20465. // injecting a canvas element on top of the canvas 3D game
  20466. if (!VirtualJoystick.vjCanvas) {
  20467. window.addEventListener("resize", function () {
  20468. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20469. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20470. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20471. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20472. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20473. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20474. }, false);
  20475. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20476. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20477. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20478. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20479. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20480. VirtualJoystick.vjCanvas.style.width = "100%";
  20481. VirtualJoystick.vjCanvas.style.height = "100%";
  20482. VirtualJoystick.vjCanvas.style.position = "absolute";
  20483. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20484. VirtualJoystick.vjCanvas.style.top = "0px";
  20485. VirtualJoystick.vjCanvas.style.left = "0px";
  20486. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20487. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20488. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20489. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20490. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20491. document.body.appendChild(VirtualJoystick.vjCanvas);
  20492. }
  20493. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20494. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20495. this.pressed = false;
  20496. // default joystick color
  20497. this._joystickColor = "cyan";
  20498. this._joystickPointerID = -1;
  20499. // current joystick position
  20500. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20501. // origin joystick position
  20502. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20503. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20504. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20505. _this._onPointerDown(evt);
  20506. }, false);
  20507. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20508. _this._onPointerMove(evt);
  20509. }, false);
  20510. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20511. _this._onPointerUp(evt);
  20512. }, false);
  20513. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20514. _this._onPointerUp(evt);
  20515. }, false);
  20516. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20517. evt.preventDefault(); // Disables system menu
  20518. }, false);
  20519. requestAnimationFrame(function () {
  20520. _this._drawVirtualJoystick();
  20521. });
  20522. }
  20523. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20524. this._joystickSensibility = newJoystickSensibility;
  20525. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20526. };
  20527. VirtualJoystick.prototype._onPointerDown = function (e) {
  20528. var positionOnScreenCondition;
  20529. e.preventDefault();
  20530. if (this._leftJoystick === true) {
  20531. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20532. }
  20533. else {
  20534. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20535. }
  20536. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20537. // First contact will be dedicated to the virtual joystick
  20538. this._joystickPointerID = e.pointerId;
  20539. this._joystickPointerStartPos.x = e.clientX;
  20540. this._joystickPointerStartPos.y = e.clientY;
  20541. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20542. this._deltaJoystickVector.x = 0;
  20543. this._deltaJoystickVector.y = 0;
  20544. this.pressed = true;
  20545. this._touches.add(e.pointerId.toString(), e);
  20546. }
  20547. else {
  20548. // You can only trigger the action buttons with a joystick declared
  20549. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20550. this._action();
  20551. this._touches.add(e.pointerId.toString(), e);
  20552. }
  20553. }
  20554. };
  20555. VirtualJoystick.prototype._onPointerMove = function (e) {
  20556. // If the current pointer is the one associated to the joystick (first touch contact)
  20557. if (this._joystickPointerID == e.pointerId) {
  20558. this._joystickPointerPos.x = e.clientX;
  20559. this._joystickPointerPos.y = e.clientY;
  20560. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20561. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20562. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20563. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20564. switch (this._axisTargetedByLeftAndRight) {
  20565. case 0 /* X */:
  20566. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20567. break;
  20568. case 1 /* Y */:
  20569. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20570. break;
  20571. case 2 /* Z */:
  20572. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20573. break;
  20574. }
  20575. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20576. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20577. switch (this._axisTargetedByUpAndDown) {
  20578. case 0 /* X */:
  20579. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20580. break;
  20581. case 1 /* Y */:
  20582. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20583. break;
  20584. case 2 /* Z */:
  20585. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20586. break;
  20587. }
  20588. }
  20589. else {
  20590. if (this._touches.item(e.pointerId.toString())) {
  20591. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20592. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20593. }
  20594. }
  20595. };
  20596. VirtualJoystick.prototype._onPointerUp = function (e) {
  20597. this._clearCanvas();
  20598. if (this._joystickPointerID == e.pointerId) {
  20599. this._joystickPointerID = -1;
  20600. this.pressed = false;
  20601. }
  20602. this._deltaJoystickVector.x = 0;
  20603. this._deltaJoystickVector.y = 0;
  20604. this._touches.remove(e.pointerId.toString());
  20605. };
  20606. /**
  20607. * Change the color of the virtual joystick
  20608. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20609. */
  20610. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20611. this._joystickColor = newColor;
  20612. };
  20613. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20614. this._action = action;
  20615. };
  20616. // Define which axis you'd like to control for left & right
  20617. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20618. switch (axis) {
  20619. case 0 /* X */:
  20620. case 1 /* Y */:
  20621. case 2 /* Z */:
  20622. this._axisTargetedByLeftAndRight = axis;
  20623. break;
  20624. default:
  20625. this._axisTargetedByLeftAndRight = 0 /* X */;
  20626. break;
  20627. }
  20628. };
  20629. // Define which axis you'd like to control for up & down
  20630. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20631. switch (axis) {
  20632. case 0 /* X */:
  20633. case 1 /* Y */:
  20634. case 2 /* Z */:
  20635. this._axisTargetedByUpAndDown = axis;
  20636. break;
  20637. default:
  20638. this._axisTargetedByUpAndDown = 1 /* Y */;
  20639. break;
  20640. }
  20641. };
  20642. VirtualJoystick.prototype._clearCanvas = function () {
  20643. if (this._leftJoystick) {
  20644. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20645. }
  20646. else {
  20647. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20648. }
  20649. };
  20650. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20651. var _this = this;
  20652. if (this.pressed) {
  20653. this._clearCanvas();
  20654. this._touches.forEach(function (touch) {
  20655. if (touch.pointerId === _this._joystickPointerID) {
  20656. VirtualJoystick.vjCanvasContext.beginPath();
  20657. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20658. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20659. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20660. VirtualJoystick.vjCanvasContext.stroke();
  20661. VirtualJoystick.vjCanvasContext.beginPath();
  20662. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20663. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20664. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20665. VirtualJoystick.vjCanvasContext.stroke();
  20666. VirtualJoystick.vjCanvasContext.beginPath();
  20667. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20668. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20669. VirtualJoystick.vjCanvasContext.stroke();
  20670. }
  20671. else {
  20672. VirtualJoystick.vjCanvasContext.beginPath();
  20673. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20674. VirtualJoystick.vjCanvasContext.beginPath();
  20675. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20676. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20677. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20678. VirtualJoystick.vjCanvasContext.stroke();
  20679. }
  20680. ;
  20681. });
  20682. }
  20683. requestAnimationFrame(function () {
  20684. _this._drawVirtualJoystick();
  20685. });
  20686. };
  20687. VirtualJoystick.prototype.releaseCanvas = function () {
  20688. if (VirtualJoystick.vjCanvas) {
  20689. document.body.removeChild(VirtualJoystick.vjCanvas);
  20690. VirtualJoystick.vjCanvas = null;
  20691. }
  20692. };
  20693. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20694. VirtualJoystick._globalJoystickIndex = 0;
  20695. return VirtualJoystick;
  20696. })();
  20697. BABYLON.VirtualJoystick = VirtualJoystick;
  20698. })(BABYLON || (BABYLON = {}));
  20699. var BABYLON;
  20700. (function (BABYLON) {
  20701. var VirtualJoystick;
  20702. (function (VirtualJoystick) {
  20703. var Collection = (function () {
  20704. function Collection() {
  20705. this._count = 0;
  20706. this._collection = new Array();
  20707. }
  20708. Collection.prototype.Count = function () {
  20709. return this._count;
  20710. };
  20711. Collection.prototype.add = function (key, item) {
  20712. if (this._collection[key] != undefined) {
  20713. return undefined;
  20714. }
  20715. this._collection[key] = item;
  20716. return ++this._count;
  20717. };
  20718. Collection.prototype.remove = function (key) {
  20719. if (this._collection[key] == undefined) {
  20720. return undefined;
  20721. }
  20722. delete this._collection[key];
  20723. return --this._count;
  20724. };
  20725. Collection.prototype.item = function (key) {
  20726. return this._collection[key];
  20727. };
  20728. Collection.prototype.forEach = function (block) {
  20729. var key;
  20730. for (key in this._collection) {
  20731. if (this._collection.hasOwnProperty(key)) {
  20732. block(this._collection[key]);
  20733. }
  20734. }
  20735. };
  20736. return Collection;
  20737. })();
  20738. VirtualJoystick.Collection = Collection;
  20739. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20740. })(BABYLON || (BABYLON = {}));
  20741. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20742. var BABYLON;
  20743. (function (BABYLON) {
  20744. var OculusRiftDevKit2013_Metric = {
  20745. HResolution: 1280,
  20746. VResolution: 800,
  20747. HScreenSize: 0.149759993,
  20748. VScreenSize: 0.0935999975,
  20749. VScreenCenter: 0.0467999987,
  20750. EyeToScreenDistance: 0.0410000011,
  20751. LensSeparationDistance: 0.0635000020,
  20752. InterpupillaryDistance: 0.0640000030,
  20753. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20754. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20755. PostProcessScaleFactor: 1.714605507808412,
  20756. LensCenterOffset: 0.151976421
  20757. };
  20758. var _OculusInnerCamera = (function (_super) {
  20759. __extends(_OculusInnerCamera, _super);
  20760. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20761. _super.call(this, name, position, scene);
  20762. this._workMatrix = new BABYLON.Matrix();
  20763. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20764. // Constants
  20765. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20766. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20767. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20768. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20769. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20770. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20771. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20772. // Postprocess
  20773. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20774. }
  20775. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20776. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20777. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20778. return this._projectionMatrix;
  20779. };
  20780. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20781. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20782. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20783. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20784. // Computing target and final matrix
  20785. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20786. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20787. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20788. return this._viewMatrix;
  20789. };
  20790. return _OculusInnerCamera;
  20791. })(BABYLON.FreeCamera);
  20792. var OculusCamera = (function (_super) {
  20793. __extends(OculusCamera, _super);
  20794. function OculusCamera(name, position, scene) {
  20795. _super.call(this, name, position, scene);
  20796. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20797. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20798. this.subCameras.push(this._leftCamera);
  20799. this.subCameras.push(this._rightCamera);
  20800. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20801. }
  20802. OculusCamera.prototype._update = function () {
  20803. this._leftCamera.position.copyFrom(this.position);
  20804. this._rightCamera.position.copyFrom(this.position);
  20805. this._updateCamera(this._leftCamera);
  20806. this._updateCamera(this._rightCamera);
  20807. _super.prototype._update.call(this);
  20808. };
  20809. OculusCamera.prototype._updateCamera = function (camera) {
  20810. camera.minZ = this.minZ;
  20811. camera.maxZ = this.maxZ;
  20812. camera.rotation.x = this.rotation.x;
  20813. camera.rotation.y = this.rotation.y;
  20814. camera.rotation.z = this.rotation.z;
  20815. };
  20816. // Oculus events
  20817. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20818. var yaw = evt.alpha / 180 * Math.PI;
  20819. var pitch = evt.beta / 180 * Math.PI;
  20820. var roll = evt.gamma / 180 * Math.PI;
  20821. if (!this._offsetOrientation) {
  20822. this._offsetOrientation = {
  20823. yaw: yaw,
  20824. pitch: pitch,
  20825. roll: roll
  20826. };
  20827. return;
  20828. }
  20829. else {
  20830. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20831. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20832. this.rotation.z += this._offsetOrientation.roll - roll;
  20833. this._offsetOrientation.yaw = yaw;
  20834. this._offsetOrientation.pitch = pitch;
  20835. this._offsetOrientation.roll = roll;
  20836. }
  20837. };
  20838. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20839. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20840. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20841. };
  20842. OculusCamera.prototype.detachControl = function (element) {
  20843. _super.prototype.detachControl.call(this, element);
  20844. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20845. };
  20846. return OculusCamera;
  20847. })(BABYLON.FreeCamera);
  20848. BABYLON.OculusCamera = OculusCamera;
  20849. })(BABYLON || (BABYLON = {}));
  20850. //# sourceMappingURL=babylon.oculusCamera.js.map
  20851. var BABYLON;
  20852. (function (BABYLON) {
  20853. var OculusRiftDevKit2013_Metric = {
  20854. HResolution: 1280,
  20855. VResolution: 800,
  20856. HScreenSize: 0.149759993,
  20857. VScreenSize: 0.0935999975,
  20858. VScreenCenter: 0.0467999987,
  20859. EyeToScreenDistance: 0.0410000011,
  20860. LensSeparationDistance: 0.0635000020,
  20861. InterpupillaryDistance: 0.0640000030,
  20862. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20863. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20864. PostProcessScaleFactor: 1.714605507808412,
  20865. LensCenterOffset: 0.151976421
  20866. };
  20867. var _OculusInnerGamepadCamera = (function (_super) {
  20868. __extends(_OculusInnerGamepadCamera, _super);
  20869. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20870. _super.call(this, name, position, scene);
  20871. this._workMatrix = new BABYLON.Matrix();
  20872. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20873. // Constants
  20874. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20875. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20876. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20877. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20878. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20879. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20880. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20881. // Postprocess
  20882. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20883. }
  20884. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20885. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20886. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20887. return this._projectionMatrix;
  20888. };
  20889. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20890. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20891. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20892. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20893. // Computing target and final matrix
  20894. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20895. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20896. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20897. return this._viewMatrix;
  20898. };
  20899. return _OculusInnerGamepadCamera;
  20900. })(BABYLON.FreeCamera);
  20901. var OculusGamepadCamera = (function (_super) {
  20902. __extends(OculusGamepadCamera, _super);
  20903. function OculusGamepadCamera(name, position, scene) {
  20904. var _this = this;
  20905. _super.call(this, name, position, scene);
  20906. this.angularSensibility = 200;
  20907. this.moveSensibility = 75;
  20908. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20909. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20910. this.subCameras.push(this._leftCamera);
  20911. this.subCameras.push(this._rightCamera);
  20912. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20913. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20914. _this._onNewGameConnected(gamepad);
  20915. });
  20916. }
  20917. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20918. // Only the first gamepad can control the camera
  20919. if (gamepad.index === 0) {
  20920. this._gamepad = gamepad;
  20921. }
  20922. };
  20923. OculusGamepadCamera.prototype._update = function () {
  20924. this._leftCamera.position.copyFrom(this.position);
  20925. this._rightCamera.position.copyFrom(this.position);
  20926. this._updateCamera(this._leftCamera);
  20927. this._updateCamera(this._rightCamera);
  20928. _super.prototype._update.call(this);
  20929. };
  20930. OculusGamepadCamera.prototype._checkInputs = function () {
  20931. if (!this._gamepad) {
  20932. return;
  20933. }
  20934. var LSValues = this._gamepad.leftStick;
  20935. var normalizedLX = LSValues.x / this.moveSensibility;
  20936. var normalizedLY = LSValues.y / this.moveSensibility;
  20937. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20938. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20939. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20940. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20941. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20942. };
  20943. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20944. camera.minZ = this.minZ;
  20945. camera.maxZ = this.maxZ;
  20946. camera.rotation.x = this.rotation.x;
  20947. camera.rotation.y = this.rotation.y;
  20948. camera.rotation.z = this.rotation.z;
  20949. };
  20950. // Oculus events
  20951. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20952. var yaw = evt.alpha / 180 * Math.PI;
  20953. var pitch = evt.beta / 180 * Math.PI;
  20954. var roll = evt.gamma / 180 * Math.PI;
  20955. if (!this._offsetOrientation) {
  20956. this._offsetOrientation = {
  20957. yaw: yaw,
  20958. pitch: pitch,
  20959. roll: roll
  20960. };
  20961. return;
  20962. }
  20963. else {
  20964. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20965. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20966. this.rotation.z += this._offsetOrientation.roll - roll;
  20967. this._offsetOrientation.yaw = yaw;
  20968. this._offsetOrientation.pitch = pitch;
  20969. this._offsetOrientation.roll = roll;
  20970. }
  20971. };
  20972. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20973. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20974. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20975. };
  20976. OculusGamepadCamera.prototype.detachControl = function (element) {
  20977. _super.prototype.detachControl.call(this, element);
  20978. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20979. };
  20980. OculusGamepadCamera.prototype.dispose = function () {
  20981. this._gamepads.dispose();
  20982. _super.prototype.dispose.call(this);
  20983. };
  20984. return OculusGamepadCamera;
  20985. })(BABYLON.FreeCamera);
  20986. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20987. })(BABYLON || (BABYLON = {}));
  20988. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20989. var BABYLON;
  20990. (function (BABYLON) {
  20991. // We're mainly based on the logic defined into the FreeCamera code
  20992. var VirtualJoysticksCamera = (function (_super) {
  20993. __extends(VirtualJoysticksCamera, _super);
  20994. function VirtualJoysticksCamera(name, position, scene) {
  20995. _super.call(this, name, position, scene);
  20996. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20997. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20998. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20999. this._leftjoystick.setJoystickSensibility(0.15);
  21000. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21001. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21002. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21003. this._rightjoystick.reverseUpDown = true;
  21004. this._rightjoystick.setJoystickSensibility(0.05);
  21005. this._rightjoystick.setJoystickColor("yellow");
  21006. }
  21007. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21008. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21009. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21010. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21011. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21012. if (!this._leftjoystick.pressed) {
  21013. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21014. }
  21015. if (!this._rightjoystick.pressed) {
  21016. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21017. }
  21018. };
  21019. VirtualJoysticksCamera.prototype.dispose = function () {
  21020. this._leftjoystick.releaseCanvas();
  21021. _super.prototype.dispose.call(this);
  21022. };
  21023. return VirtualJoysticksCamera;
  21024. })(BABYLON.FreeCamera);
  21025. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21026. })(BABYLON || (BABYLON = {}));
  21027. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21028. var BABYLON;
  21029. (function (BABYLON) {
  21030. var ShaderMaterial = (function (_super) {
  21031. __extends(ShaderMaterial, _super);
  21032. function ShaderMaterial(name, scene, shaderPath, options) {
  21033. _super.call(this, name, scene);
  21034. this._textures = new Array();
  21035. this._floats = new Array();
  21036. this._floatsArrays = {};
  21037. this._colors3 = new Array();
  21038. this._colors4 = new Array();
  21039. this._vectors2 = new Array();
  21040. this._vectors3 = new Array();
  21041. this._matrices = new Array();
  21042. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21043. this._shaderPath = shaderPath;
  21044. options.needAlphaBlending = options.needAlphaBlending || false;
  21045. options.needAlphaTesting = options.needAlphaTesting || false;
  21046. options.attributes = options.attributes || ["position", "normal", "uv"];
  21047. options.uniforms = options.uniforms || ["worldViewProjection"];
  21048. options.samplers = options.samplers || [];
  21049. this._options = options;
  21050. }
  21051. ShaderMaterial.prototype.needAlphaBlending = function () {
  21052. return this._options.needAlphaBlending;
  21053. };
  21054. ShaderMaterial.prototype.needAlphaTesting = function () {
  21055. return this._options.needAlphaTesting;
  21056. };
  21057. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21058. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21059. this._options.uniforms.push(uniformName);
  21060. }
  21061. };
  21062. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21063. if (this._options.samplers.indexOf(name) === -1) {
  21064. this._options.samplers.push(name);
  21065. }
  21066. this._textures[name] = texture;
  21067. return this;
  21068. };
  21069. ShaderMaterial.prototype.setFloat = function (name, value) {
  21070. this._checkUniform(name);
  21071. this._floats[name] = value;
  21072. return this;
  21073. };
  21074. ShaderMaterial.prototype.setFloats = function (name, value) {
  21075. this._checkUniform(name);
  21076. this._floatsArrays[name] = value;
  21077. return this;
  21078. };
  21079. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21080. this._checkUniform(name);
  21081. this._colors3[name] = value;
  21082. return this;
  21083. };
  21084. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21085. this._checkUniform(name);
  21086. this._colors4[name] = value;
  21087. return this;
  21088. };
  21089. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21090. this._checkUniform(name);
  21091. this._vectors2[name] = value;
  21092. return this;
  21093. };
  21094. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21095. this._checkUniform(name);
  21096. this._vectors3[name] = value;
  21097. return this;
  21098. };
  21099. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21100. this._checkUniform(name);
  21101. this._matrices[name] = value;
  21102. return this;
  21103. };
  21104. ShaderMaterial.prototype.isReady = function () {
  21105. var scene = this.getScene();
  21106. var engine = scene.getEngine();
  21107. if (!this.checkReadyOnEveryCall) {
  21108. if (this._renderId === scene.getRenderId()) {
  21109. return true;
  21110. }
  21111. }
  21112. var previousEffect = this._effect;
  21113. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21114. if (!this._effect.isReady()) {
  21115. return false;
  21116. }
  21117. if (previousEffect !== this._effect) {
  21118. scene.resetCachedMaterial();
  21119. }
  21120. this._renderId = scene.getRenderId();
  21121. return true;
  21122. };
  21123. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21124. var scene = this.getScene();
  21125. if (this._options.uniforms.indexOf("world") !== -1) {
  21126. this._effect.setMatrix("world", world);
  21127. }
  21128. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21129. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21130. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21131. }
  21132. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21133. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21134. }
  21135. };
  21136. ShaderMaterial.prototype.bind = function (world) {
  21137. // Std values
  21138. this.bindOnlyWorldMatrix(world);
  21139. if (this.getScene().getCachedMaterial() !== this) {
  21140. if (this._options.uniforms.indexOf("view") !== -1) {
  21141. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21142. }
  21143. if (this._options.uniforms.indexOf("projection") !== -1) {
  21144. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21145. }
  21146. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21147. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21148. }
  21149. for (var name in this._textures) {
  21150. this._effect.setTexture(name, this._textures[name]);
  21151. }
  21152. for (name in this._floats) {
  21153. this._effect.setFloat(name, this._floats[name]);
  21154. }
  21155. for (name in this._floatsArrays) {
  21156. this._effect.setArray(name, this._floatsArrays[name]);
  21157. }
  21158. for (name in this._colors3) {
  21159. this._effect.setColor3(name, this._colors3[name]);
  21160. }
  21161. for (name in this._colors4) {
  21162. var color = this._colors4[name];
  21163. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21164. }
  21165. for (name in this._vectors2) {
  21166. this._effect.setVector2(name, this._vectors2[name]);
  21167. }
  21168. for (name in this._vectors3) {
  21169. this._effect.setVector3(name, this._vectors3[name]);
  21170. }
  21171. for (name in this._matrices) {
  21172. this._effect.setMatrix(name, this._matrices[name]);
  21173. }
  21174. }
  21175. _super.prototype.bind.call(this, world, null);
  21176. };
  21177. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21178. for (var name in this._textures) {
  21179. this._textures[name].dispose();
  21180. }
  21181. this._textures = [];
  21182. _super.prototype.dispose.call(this, forceDisposeEffect);
  21183. };
  21184. return ShaderMaterial;
  21185. })(BABYLON.Material);
  21186. BABYLON.ShaderMaterial = ShaderMaterial;
  21187. })(BABYLON || (BABYLON = {}));
  21188. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21189. (function (BABYLON) {
  21190. var VertexData = (function () {
  21191. function VertexData() {
  21192. }
  21193. VertexData.prototype.set = function (data, kind) {
  21194. switch (kind) {
  21195. case BABYLON.VertexBuffer.PositionKind:
  21196. this.positions = data;
  21197. break;
  21198. case BABYLON.VertexBuffer.NormalKind:
  21199. this.normals = data;
  21200. break;
  21201. case BABYLON.VertexBuffer.UVKind:
  21202. this.uvs = data;
  21203. break;
  21204. case BABYLON.VertexBuffer.UV2Kind:
  21205. this.uv2s = data;
  21206. break;
  21207. case BABYLON.VertexBuffer.ColorKind:
  21208. this.colors = data;
  21209. break;
  21210. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21211. this.matricesIndices = data;
  21212. break;
  21213. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21214. this.matricesWeights = data;
  21215. break;
  21216. }
  21217. };
  21218. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21219. this._applyTo(mesh, updatable);
  21220. };
  21221. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21222. this._applyTo(geometry, updatable);
  21223. };
  21224. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21225. this._update(mesh);
  21226. };
  21227. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21228. this._update(geometry);
  21229. };
  21230. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21231. if (this.positions) {
  21232. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21233. }
  21234. if (this.normals) {
  21235. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21236. }
  21237. if (this.uvs) {
  21238. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21239. }
  21240. if (this.uv2s) {
  21241. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21242. }
  21243. if (this.colors) {
  21244. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21245. }
  21246. if (this.matricesIndices) {
  21247. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21248. }
  21249. if (this.matricesWeights) {
  21250. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21251. }
  21252. if (this.indices) {
  21253. meshOrGeometry.setIndices(this.indices);
  21254. }
  21255. };
  21256. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21257. if (this.positions) {
  21258. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21259. }
  21260. if (this.normals) {
  21261. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21262. }
  21263. if (this.uvs) {
  21264. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21265. }
  21266. if (this.uv2s) {
  21267. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21268. }
  21269. if (this.colors) {
  21270. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21271. }
  21272. if (this.matricesIndices) {
  21273. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21274. }
  21275. if (this.matricesWeights) {
  21276. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21277. }
  21278. if (this.indices) {
  21279. meshOrGeometry.setIndices(this.indices);
  21280. }
  21281. };
  21282. VertexData.prototype.transform = function (matrix) {
  21283. var transformed = BABYLON.Vector3.Zero();
  21284. if (this.positions) {
  21285. var position = BABYLON.Vector3.Zero();
  21286. for (var index = 0; index < this.positions.length; index += 3) {
  21287. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21288. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21289. this.positions[index] = transformed.x;
  21290. this.positions[index + 1] = transformed.y;
  21291. this.positions[index + 2] = transformed.z;
  21292. }
  21293. }
  21294. if (this.normals) {
  21295. var normal = BABYLON.Vector3.Zero();
  21296. for (index = 0; index < this.normals.length; index += 3) {
  21297. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21298. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21299. this.normals[index] = transformed.x;
  21300. this.normals[index + 1] = transformed.y;
  21301. this.normals[index + 2] = transformed.z;
  21302. }
  21303. }
  21304. };
  21305. VertexData.prototype.merge = function (other) {
  21306. if (other.indices) {
  21307. if (!this.indices) {
  21308. this.indices = [];
  21309. }
  21310. var offset = this.positions ? this.positions.length / 3 : 0;
  21311. for (var index = 0; index < other.indices.length; index++) {
  21312. this.indices.push(other.indices[index] + offset);
  21313. }
  21314. }
  21315. if (other.positions) {
  21316. if (!this.positions) {
  21317. this.positions = [];
  21318. }
  21319. for (index = 0; index < other.positions.length; index++) {
  21320. this.positions.push(other.positions[index]);
  21321. }
  21322. }
  21323. if (other.normals) {
  21324. if (!this.normals) {
  21325. this.normals = [];
  21326. }
  21327. for (index = 0; index < other.normals.length; index++) {
  21328. this.normals.push(other.normals[index]);
  21329. }
  21330. }
  21331. if (other.uvs) {
  21332. if (!this.uvs) {
  21333. this.uvs = [];
  21334. }
  21335. for (index = 0; index < other.uvs.length; index++) {
  21336. this.uvs.push(other.uvs[index]);
  21337. }
  21338. }
  21339. if (other.uv2s) {
  21340. if (!this.uv2s) {
  21341. this.uv2s = [];
  21342. }
  21343. for (index = 0; index < other.uv2s.length; index++) {
  21344. this.uv2s.push(other.uv2s[index]);
  21345. }
  21346. }
  21347. if (other.matricesIndices) {
  21348. if (!this.matricesIndices) {
  21349. this.matricesIndices = [];
  21350. }
  21351. for (index = 0; index < other.matricesIndices.length; index++) {
  21352. this.matricesIndices.push(other.matricesIndices[index]);
  21353. }
  21354. }
  21355. if (other.matricesWeights) {
  21356. if (!this.matricesWeights) {
  21357. this.matricesWeights = [];
  21358. }
  21359. for (index = 0; index < other.matricesWeights.length; index++) {
  21360. this.matricesWeights.push(other.matricesWeights[index]);
  21361. }
  21362. }
  21363. if (other.colors) {
  21364. if (!this.colors) {
  21365. this.colors = [];
  21366. }
  21367. for (index = 0; index < other.colors.length; index++) {
  21368. this.colors.push(other.colors[index]);
  21369. }
  21370. }
  21371. };
  21372. // Statics
  21373. VertexData.ExtractFromMesh = function (mesh) {
  21374. return VertexData._ExtractFrom(mesh);
  21375. };
  21376. VertexData.ExtractFromGeometry = function (geometry) {
  21377. return VertexData._ExtractFrom(geometry);
  21378. };
  21379. VertexData._ExtractFrom = function (meshOrGeometry) {
  21380. var result = new VertexData();
  21381. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21382. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21383. }
  21384. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21385. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21386. }
  21387. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21388. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21389. }
  21390. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21391. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21392. }
  21393. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21394. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21395. }
  21396. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21397. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21398. }
  21399. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21400. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21401. }
  21402. result.indices = meshOrGeometry.getIndices();
  21403. return result;
  21404. };
  21405. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21406. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21407. closeArray = closeArray || false;
  21408. closePath = closePath || false;
  21409. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21410. offset = offset || defaultOffset;
  21411. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21412. var positions = [];
  21413. var indices = [];
  21414. var normals = [];
  21415. var uvs = [];
  21416. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21417. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21418. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21419. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21420. var minlg; // minimal length among all paths from pathArray
  21421. var lg = []; // array of path lengths : nb of vertex per path
  21422. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21423. var p; // path iterator
  21424. var i; // point iterator
  21425. var j; // point iterator
  21426. // if single path in pathArray
  21427. if (pathArray.length < 2) {
  21428. var ar1 = [];
  21429. var ar2 = [];
  21430. for (i = 0; i < pathArray[0].length - offset; i++) {
  21431. ar1.push(pathArray[0][i]);
  21432. ar2.push(pathArray[0][i + offset]);
  21433. }
  21434. pathArray = [ar1, ar2];
  21435. }
  21436. // positions and horizontal distances (u)
  21437. var idc = 0;
  21438. minlg = pathArray[0].length;
  21439. for (p = 0; p < pathArray.length; p++) {
  21440. uTotalDistance[p] = 0;
  21441. us[p] = [0];
  21442. var path = pathArray[p];
  21443. var l = path.length;
  21444. minlg = (minlg < l) ? minlg : l;
  21445. lg[p] = l;
  21446. idx[p] = idc;
  21447. j = 0;
  21448. while (j < l) {
  21449. positions.push(path[j].x, path[j].y, path[j].z);
  21450. if (j > 0) {
  21451. var vectlg = path[j].subtract(path[j - 1]).length();
  21452. var dist = vectlg + uTotalDistance[p];
  21453. us[p].push(dist);
  21454. uTotalDistance[p] = dist;
  21455. }
  21456. j++;
  21457. }
  21458. if (closePath) {
  21459. vectlg = path[0].subtract(path[j - 1]).length();
  21460. dist = vectlg + uTotalDistance[p];
  21461. uTotalDistance[p] = dist;
  21462. }
  21463. idc += l;
  21464. }
  21465. for (i = 0; i < minlg; i++) {
  21466. vTotalDistance[i] = 0;
  21467. vs[i] = [0];
  21468. var path1;
  21469. var path2;
  21470. for (p = 0; p < pathArray.length - 1; p++) {
  21471. path1 = pathArray[p];
  21472. path2 = pathArray[p + 1];
  21473. vectlg = path2[i].subtract(path1[i]).length();
  21474. dist = vectlg + vTotalDistance[i];
  21475. vs[i].push(dist);
  21476. vTotalDistance[i] = dist;
  21477. }
  21478. if (closeArray) {
  21479. path1 = pathArray[p];
  21480. path2 = pathArray[0];
  21481. vectlg = path2[i].subtract(path1[i]).length();
  21482. dist = vectlg + vTotalDistance[i];
  21483. vTotalDistance[i] = dist;
  21484. }
  21485. }
  21486. // uvs
  21487. var u;
  21488. var v;
  21489. for (p = 0; p < pathArray.length; p++) {
  21490. for (i = 0; i < minlg; i++) {
  21491. u = us[p][i] / uTotalDistance[p];
  21492. v = vs[i][p] / vTotalDistance[i];
  21493. uvs.push(u, v);
  21494. }
  21495. }
  21496. // indices
  21497. p = 0; // path index
  21498. var pi = 0; // positions array index
  21499. var l1 = lg[p] - 1; // path1 length
  21500. var l2 = lg[p + 1] - 1; // path2 length
  21501. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21502. var shft = idx[1] - idx[0]; // shift
  21503. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21504. var t1; // two consecutive triangles, so 4 points : point1
  21505. var t2; // point2
  21506. var t3; // point3
  21507. var t4; // point4
  21508. while (pi <= min && p < path1nb) {
  21509. // 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
  21510. t1 = pi;
  21511. t2 = pi + shft;
  21512. t3 = pi + 1;
  21513. t4 = pi + shft + 1;
  21514. indices.push(pi, pi + shft, pi + 1);
  21515. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21516. pi += 1;
  21517. if (pi === min) {
  21518. if (closePath) {
  21519. indices.push(pi, pi + shft, idx[p]);
  21520. indices.push(idx[p] + shft, idx[p], pi + shft);
  21521. t3 = idx[p];
  21522. t4 = idx[p] + shft;
  21523. }
  21524. p++;
  21525. if (p === lg.length - 1) {
  21526. shft = idx[0] - idx[p];
  21527. l1 = lg[p] - 1;
  21528. l2 = lg[0] - 1;
  21529. }
  21530. else {
  21531. shft = idx[p + 1] - idx[p];
  21532. l1 = lg[p] - 1;
  21533. l2 = lg[p + 1] - 1;
  21534. }
  21535. pi = idx[p];
  21536. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21537. }
  21538. }
  21539. // normals
  21540. VertexData.ComputeNormals(positions, indices, normals);
  21541. // sides
  21542. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21543. // Result
  21544. var vertexData = new VertexData();
  21545. vertexData.indices = indices;
  21546. vertexData.positions = positions;
  21547. vertexData.normals = normals;
  21548. vertexData.uvs = uvs;
  21549. return vertexData;
  21550. };
  21551. VertexData.CreateBox = function (size, sideOrientation) {
  21552. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21553. var normalsSource = [
  21554. new BABYLON.Vector3(0, 0, 1),
  21555. new BABYLON.Vector3(0, 0, -1),
  21556. new BABYLON.Vector3(1, 0, 0),
  21557. new BABYLON.Vector3(-1, 0, 0),
  21558. new BABYLON.Vector3(0, 1, 0),
  21559. new BABYLON.Vector3(0, -1, 0)
  21560. ];
  21561. var indices = [];
  21562. var positions = [];
  21563. var normals = [];
  21564. var uvs = [];
  21565. size = size || 1;
  21566. for (var index = 0; index < normalsSource.length; index++) {
  21567. var normal = normalsSource[index];
  21568. // Get two vectors perpendicular to the face normal and to each other.
  21569. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21570. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21571. // Six indices (two triangles) per face.
  21572. var verticesLength = positions.length / 3;
  21573. indices.push(verticesLength);
  21574. indices.push(verticesLength + 1);
  21575. indices.push(verticesLength + 2);
  21576. indices.push(verticesLength);
  21577. indices.push(verticesLength + 2);
  21578. indices.push(verticesLength + 3);
  21579. // Four vertices per face.
  21580. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21581. positions.push(vertex.x, vertex.y, vertex.z);
  21582. normals.push(normal.x, normal.y, normal.z);
  21583. uvs.push(1.0, 1.0);
  21584. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21585. positions.push(vertex.x, vertex.y, vertex.z);
  21586. normals.push(normal.x, normal.y, normal.z);
  21587. uvs.push(0.0, 1.0);
  21588. vertex = normal.add(side1).add(side2).scale(size / 2);
  21589. positions.push(vertex.x, vertex.y, vertex.z);
  21590. normals.push(normal.x, normal.y, normal.z);
  21591. uvs.push(0.0, 0.0);
  21592. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21593. positions.push(vertex.x, vertex.y, vertex.z);
  21594. normals.push(normal.x, normal.y, normal.z);
  21595. uvs.push(1.0, 0.0);
  21596. }
  21597. // sides
  21598. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21599. // Result
  21600. var vertexData = new VertexData();
  21601. vertexData.indices = indices;
  21602. vertexData.positions = positions;
  21603. vertexData.normals = normals;
  21604. vertexData.uvs = uvs;
  21605. return vertexData;
  21606. };
  21607. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21608. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21609. segments = segments || 32;
  21610. diameter = diameter || 1;
  21611. var radius = diameter / 2;
  21612. var totalZRotationSteps = 2 + segments;
  21613. var totalYRotationSteps = 2 * totalZRotationSteps;
  21614. var indices = [];
  21615. var positions = [];
  21616. var normals = [];
  21617. var uvs = [];
  21618. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21619. var normalizedZ = zRotationStep / totalZRotationSteps;
  21620. var angleZ = (normalizedZ * Math.PI);
  21621. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21622. var normalizedY = yRotationStep / totalYRotationSteps;
  21623. var angleY = normalizedY * Math.PI * 2;
  21624. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21625. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21626. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21627. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21628. var vertex = complete.scale(radius);
  21629. var normal = BABYLON.Vector3.Normalize(vertex);
  21630. positions.push(vertex.x, vertex.y, vertex.z);
  21631. normals.push(normal.x, normal.y, normal.z);
  21632. uvs.push(normalizedZ, normalizedY);
  21633. }
  21634. if (zRotationStep > 0) {
  21635. var verticesCount = positions.length / 3;
  21636. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21637. indices.push((firstIndex));
  21638. indices.push((firstIndex + 1));
  21639. indices.push(firstIndex + totalYRotationSteps + 1);
  21640. indices.push((firstIndex + totalYRotationSteps + 1));
  21641. indices.push((firstIndex + 1));
  21642. indices.push((firstIndex + totalYRotationSteps + 2));
  21643. }
  21644. }
  21645. }
  21646. // Sides
  21647. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21648. // Result
  21649. var vertexData = new VertexData();
  21650. vertexData.indices = indices;
  21651. vertexData.positions = positions;
  21652. vertexData.normals = normals;
  21653. vertexData.uvs = uvs;
  21654. return vertexData;
  21655. };
  21656. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21657. if (subdivisions === void 0) { subdivisions = 1; }
  21658. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21659. var radiusTop = diameterTop / 2;
  21660. var radiusBottom = diameterBottom / 2;
  21661. var indices = [];
  21662. var positions = [];
  21663. var normals = [];
  21664. var uvs = [];
  21665. height = height || 1;
  21666. diameterTop = diameterTop || 0.5;
  21667. diameterBottom = diameterBottom || 1;
  21668. tessellation = tessellation || 16;
  21669. subdivisions = subdivisions || 1;
  21670. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21671. var getCircleVector = function (i) {
  21672. var angle = (i * 2.0 * Math.PI / tessellation);
  21673. var dx = Math.cos(angle);
  21674. var dz = Math.sin(angle);
  21675. return new BABYLON.Vector3(dx, 0, dz);
  21676. };
  21677. var createCylinderCap = function (isTop) {
  21678. var radius = isTop ? radiusTop : radiusBottom;
  21679. if (radius === 0) {
  21680. return;
  21681. }
  21682. var vbase = positions.length / 3;
  21683. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21684. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21685. if (!isTop) {
  21686. offset.scaleInPlace(-1);
  21687. textureScale.x = -textureScale.x;
  21688. }
  21689. for (var i = 0; i < tessellation; i++) {
  21690. var circleVector = getCircleVector(i);
  21691. var position = circleVector.scale(radius).add(offset);
  21692. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21693. positions.push(position.x, position.y, position.z);
  21694. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21695. }
  21696. for (i = 0; i < tessellation - 2; i++) {
  21697. if (!isTop) {
  21698. indices.push(vbase);
  21699. indices.push(vbase + (i + 2) % tessellation);
  21700. indices.push(vbase + (i + 1) % tessellation);
  21701. }
  21702. else {
  21703. indices.push(vbase);
  21704. indices.push(vbase + (i + 1) % tessellation);
  21705. indices.push(vbase + (i + 2) % tessellation);
  21706. }
  21707. }
  21708. };
  21709. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21710. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21711. var stride = tessellation + 1;
  21712. for (var i = 0; i <= tessellation; i++) {
  21713. var circleVector = getCircleVector(i);
  21714. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21715. var position, radius = radiusBottom;
  21716. for (var s = 0; s <= subdivisions; s++) {
  21717. // Update variables
  21718. position = circleVector.scale(radius);
  21719. position.addInPlace(base.add(offset.scale(s)));
  21720. textureCoordinate.y += 1 / subdivisions;
  21721. radius += (radiusTop - radiusBottom) / subdivisions;
  21722. // Push in arrays
  21723. positions.push(position.x, position.y, position.z);
  21724. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21725. }
  21726. }
  21727. subdivisions += 1;
  21728. for (s = 0; s < subdivisions - 1; s++) {
  21729. for (i = 0; i <= tessellation; i++) {
  21730. indices.push(i * subdivisions + s);
  21731. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21732. indices.push(i * subdivisions + (s + 1));
  21733. indices.push(i * subdivisions + (s + 1));
  21734. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21735. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21736. }
  21737. }
  21738. // Create flat triangle fan caps to seal the top and bottom.
  21739. createCylinderCap(true);
  21740. createCylinderCap(false);
  21741. // Normals
  21742. VertexData.ComputeNormals(positions, indices, normals);
  21743. // Sides
  21744. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21745. // Result
  21746. var vertexData = new VertexData();
  21747. vertexData.indices = indices;
  21748. vertexData.positions = positions;
  21749. vertexData.normals = normals;
  21750. vertexData.uvs = uvs;
  21751. return vertexData;
  21752. };
  21753. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  21754. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21755. var indices = [];
  21756. var positions = [];
  21757. var normals = [];
  21758. var uvs = [];
  21759. diameter = diameter || 1;
  21760. thickness = thickness || 0.5;
  21761. tessellation = tessellation || 16;
  21762. var stride = tessellation + 1;
  21763. for (var i = 0; i <= tessellation; i++) {
  21764. var u = i / tessellation;
  21765. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21766. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21767. for (var j = 0; j <= tessellation; j++) {
  21768. var v = 1 - j / tessellation;
  21769. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21770. var dx = Math.cos(innerAngle);
  21771. var dy = Math.sin(innerAngle);
  21772. // Create a vertex.
  21773. var normal = new BABYLON.Vector3(dx, dy, 0);
  21774. var position = normal.scale(thickness / 2);
  21775. var textureCoordinate = new BABYLON.Vector2(u, v);
  21776. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21777. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21778. positions.push(position.x, position.y, position.z);
  21779. normals.push(normal.x, normal.y, normal.z);
  21780. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21781. // And create indices for two triangles.
  21782. var nextI = (i + 1) % stride;
  21783. var nextJ = (j + 1) % stride;
  21784. indices.push(i * stride + j);
  21785. indices.push(i * stride + nextJ);
  21786. indices.push(nextI * stride + j);
  21787. indices.push(i * stride + nextJ);
  21788. indices.push(nextI * stride + nextJ);
  21789. indices.push(nextI * stride + j);
  21790. }
  21791. }
  21792. // Sides
  21793. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21794. // Result
  21795. var vertexData = new VertexData();
  21796. vertexData.indices = indices;
  21797. vertexData.positions = positions;
  21798. vertexData.normals = normals;
  21799. vertexData.uvs = uvs;
  21800. return vertexData;
  21801. };
  21802. VertexData.CreateLines = function (points) {
  21803. var indices = [];
  21804. var positions = [];
  21805. for (var index = 0; index < points.length; index++) {
  21806. positions.push(points[index].x, points[index].y, points[index].z);
  21807. if (index > 0) {
  21808. indices.push(index - 1);
  21809. indices.push(index);
  21810. }
  21811. }
  21812. // Result
  21813. var vertexData = new VertexData();
  21814. vertexData.indices = indices;
  21815. vertexData.positions = positions;
  21816. return vertexData;
  21817. };
  21818. VertexData.CreateGround = function (width, height, subdivisions) {
  21819. var indices = [];
  21820. var positions = [];
  21821. var normals = [];
  21822. var uvs = [];
  21823. var row, col;
  21824. width = width || 1;
  21825. height = height || 1;
  21826. subdivisions = subdivisions || 1;
  21827. for (row = 0; row <= subdivisions; row++) {
  21828. for (col = 0; col <= subdivisions; col++) {
  21829. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21830. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21831. positions.push(position.x, position.y, position.z);
  21832. normals.push(normal.x, normal.y, normal.z);
  21833. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21834. }
  21835. }
  21836. for (row = 0; row < subdivisions; row++) {
  21837. for (col = 0; col < subdivisions; col++) {
  21838. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21839. indices.push(col + 1 + row * (subdivisions + 1));
  21840. indices.push(col + row * (subdivisions + 1));
  21841. indices.push(col + (row + 1) * (subdivisions + 1));
  21842. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21843. indices.push(col + row * (subdivisions + 1));
  21844. }
  21845. }
  21846. // Result
  21847. var vertexData = new VertexData();
  21848. vertexData.indices = indices;
  21849. vertexData.positions = positions;
  21850. vertexData.normals = normals;
  21851. vertexData.uvs = uvs;
  21852. return vertexData;
  21853. };
  21854. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21855. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21856. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21857. var indices = [];
  21858. var positions = [];
  21859. var normals = [];
  21860. var uvs = [];
  21861. var row, col, tileRow, tileCol;
  21862. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21863. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21864. precision.w = (precision.w < 1) ? 1 : precision.w;
  21865. precision.h = (precision.h < 1) ? 1 : precision.h;
  21866. var tileSize = {
  21867. 'w': (xmax - xmin) / subdivisions.w,
  21868. 'h': (zmax - zmin) / subdivisions.h
  21869. };
  21870. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21871. // Indices
  21872. var base = positions.length / 3;
  21873. var rowLength = precision.w + 1;
  21874. for (row = 0; row < precision.h; row++) {
  21875. for (col = 0; col < precision.w; col++) {
  21876. var square = [
  21877. base + col + row * rowLength,
  21878. base + (col + 1) + row * rowLength,
  21879. base + (col + 1) + (row + 1) * rowLength,
  21880. base + col + (row + 1) * rowLength
  21881. ];
  21882. indices.push(square[1]);
  21883. indices.push(square[2]);
  21884. indices.push(square[3]);
  21885. indices.push(square[0]);
  21886. indices.push(square[1]);
  21887. indices.push(square[3]);
  21888. }
  21889. }
  21890. // Position, normals and uvs
  21891. var position = BABYLON.Vector3.Zero();
  21892. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21893. for (row = 0; row <= precision.h; row++) {
  21894. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21895. for (col = 0; col <= precision.w; col++) {
  21896. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21897. position.y = 0;
  21898. positions.push(position.x, position.y, position.z);
  21899. normals.push(normal.x, normal.y, normal.z);
  21900. uvs.push(col / precision.w, row / precision.h);
  21901. }
  21902. }
  21903. }
  21904. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21905. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21906. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21907. }
  21908. }
  21909. // Result
  21910. var vertexData = new VertexData();
  21911. vertexData.indices = indices;
  21912. vertexData.positions = positions;
  21913. vertexData.normals = normals;
  21914. vertexData.uvs = uvs;
  21915. return vertexData;
  21916. };
  21917. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21918. var indices = [];
  21919. var positions = [];
  21920. var normals = [];
  21921. var uvs = [];
  21922. var row, col;
  21923. for (row = 0; row <= subdivisions; row++) {
  21924. for (col = 0; col <= subdivisions; col++) {
  21925. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21926. // Compute height
  21927. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21928. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21929. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21930. var r = buffer[pos] / 255.0;
  21931. var g = buffer[pos + 1] / 255.0;
  21932. var b = buffer[pos + 2] / 255.0;
  21933. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21934. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21935. // Add vertex
  21936. positions.push(position.x, position.y, position.z);
  21937. normals.push(0, 0, 0);
  21938. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21939. }
  21940. }
  21941. for (row = 0; row < subdivisions; row++) {
  21942. for (col = 0; col < subdivisions; col++) {
  21943. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21944. indices.push(col + 1 + row * (subdivisions + 1));
  21945. indices.push(col + row * (subdivisions + 1));
  21946. indices.push(col + (row + 1) * (subdivisions + 1));
  21947. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21948. indices.push(col + row * (subdivisions + 1));
  21949. }
  21950. }
  21951. // Normals
  21952. VertexData.ComputeNormals(positions, indices, normals);
  21953. // Result
  21954. var vertexData = new VertexData();
  21955. vertexData.indices = indices;
  21956. vertexData.positions = positions;
  21957. vertexData.normals = normals;
  21958. vertexData.uvs = uvs;
  21959. return vertexData;
  21960. };
  21961. VertexData.CreatePlane = function (size, sideOrientation) {
  21962. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21963. var indices = [];
  21964. var positions = [];
  21965. var normals = [];
  21966. var uvs = [];
  21967. size = size || 1;
  21968. // Vertices
  21969. var halfSize = size / 2.0;
  21970. positions.push(-halfSize, -halfSize, 0);
  21971. normals.push(0, 0, -1.0);
  21972. uvs.push(0.0, 0.0);
  21973. positions.push(halfSize, -halfSize, 0);
  21974. normals.push(0, 0, -1.0);
  21975. uvs.push(1.0, 0.0);
  21976. positions.push(halfSize, halfSize, 0);
  21977. normals.push(0, 0, -1.0);
  21978. uvs.push(1.0, 1.0);
  21979. positions.push(-halfSize, halfSize, 0);
  21980. normals.push(0, 0, -1.0);
  21981. uvs.push(0.0, 1.0);
  21982. // Indices
  21983. indices.push(0);
  21984. indices.push(1);
  21985. indices.push(2);
  21986. indices.push(0);
  21987. indices.push(2);
  21988. indices.push(3);
  21989. // Sides
  21990. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21991. // Result
  21992. var vertexData = new VertexData();
  21993. vertexData.indices = indices;
  21994. vertexData.positions = positions;
  21995. vertexData.normals = normals;
  21996. vertexData.uvs = uvs;
  21997. return vertexData;
  21998. };
  21999. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22000. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22001. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22002. var indices = [];
  22003. var positions = [];
  22004. var normals = [];
  22005. var uvs = [];
  22006. radius = radius || 2;
  22007. tube = tube || 0.5;
  22008. radialSegments = radialSegments || 32;
  22009. tubularSegments = tubularSegments || 32;
  22010. p = p || 2;
  22011. q = q || 3;
  22012. // Helper
  22013. var getPos = function (angle) {
  22014. var cu = Math.cos(angle);
  22015. var su = Math.sin(angle);
  22016. var quOverP = q / p * angle;
  22017. var cs = Math.cos(quOverP);
  22018. var tx = radius * (2 + cs) * 0.5 * cu;
  22019. var ty = radius * (2 + cs) * su * 0.5;
  22020. var tz = radius * Math.sin(quOverP) * 0.5;
  22021. return new BABYLON.Vector3(tx, ty, tz);
  22022. };
  22023. for (var i = 0; i <= radialSegments; i++) {
  22024. var modI = i % radialSegments;
  22025. var u = modI / radialSegments * 2 * p * Math.PI;
  22026. var p1 = getPos(u);
  22027. var p2 = getPos(u + 0.01);
  22028. var tang = p2.subtract(p1);
  22029. var n = p2.add(p1);
  22030. var bitan = BABYLON.Vector3.Cross(tang, n);
  22031. n = BABYLON.Vector3.Cross(bitan, tang);
  22032. bitan.normalize();
  22033. n.normalize();
  22034. for (var j = 0; j < tubularSegments; j++) {
  22035. var modJ = j % tubularSegments;
  22036. var v = modJ / tubularSegments * 2 * Math.PI;
  22037. var cx = -tube * Math.cos(v);
  22038. var cy = tube * Math.sin(v);
  22039. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22040. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22041. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22042. uvs.push(i / radialSegments);
  22043. uvs.push(j / tubularSegments);
  22044. }
  22045. }
  22046. for (i = 0; i < radialSegments; i++) {
  22047. for (j = 0; j < tubularSegments; j++) {
  22048. var jNext = (j + 1) % tubularSegments;
  22049. var a = i * tubularSegments + j;
  22050. var b = (i + 1) * tubularSegments + j;
  22051. var c = (i + 1) * tubularSegments + jNext;
  22052. var d = i * tubularSegments + jNext;
  22053. indices.push(d);
  22054. indices.push(b);
  22055. indices.push(a);
  22056. indices.push(d);
  22057. indices.push(c);
  22058. indices.push(b);
  22059. }
  22060. }
  22061. // Normals
  22062. VertexData.ComputeNormals(positions, indices, normals);
  22063. // Sides
  22064. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22065. // Result
  22066. var vertexData = new VertexData();
  22067. vertexData.indices = indices;
  22068. vertexData.positions = positions;
  22069. vertexData.normals = normals;
  22070. vertexData.uvs = uvs;
  22071. return vertexData;
  22072. };
  22073. // Tools
  22074. VertexData.ComputeNormals = function (positions, indices, normals) {
  22075. var positionVectors = [];
  22076. var facesOfVertices = [];
  22077. var index;
  22078. for (index = 0; index < positions.length; index += 3) {
  22079. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22080. positionVectors.push(vector3);
  22081. facesOfVertices.push([]);
  22082. }
  22083. // Compute normals
  22084. var facesNormals = [];
  22085. for (index = 0; index < indices.length / 3; index++) {
  22086. var i1 = indices[index * 3];
  22087. var i2 = indices[index * 3 + 1];
  22088. var i3 = indices[index * 3 + 2];
  22089. var p1 = positionVectors[i1];
  22090. var p2 = positionVectors[i2];
  22091. var p3 = positionVectors[i3];
  22092. var p1p2 = p1.subtract(p2);
  22093. var p3p2 = p3.subtract(p2);
  22094. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22095. facesOfVertices[i1].push(index);
  22096. facesOfVertices[i2].push(index);
  22097. facesOfVertices[i3].push(index);
  22098. }
  22099. for (index = 0; index < positionVectors.length; index++) {
  22100. var faces = facesOfVertices[index];
  22101. var normal = BABYLON.Vector3.Zero();
  22102. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22103. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22104. }
  22105. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22106. normals[index * 3] = normal.x;
  22107. normals[index * 3 + 1] = normal.y;
  22108. normals[index * 3 + 2] = normal.z;
  22109. }
  22110. };
  22111. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22112. var li = indices.length;
  22113. var ln = normals.length;
  22114. var i;
  22115. var n;
  22116. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22117. switch (sideOrientation) {
  22118. case BABYLON.Mesh.FRONTSIDE:
  22119. break;
  22120. case BABYLON.Mesh.BACKSIDE:
  22121. var tmp;
  22122. for (i = 0; i < li; i += 3) {
  22123. tmp = indices[i];
  22124. indices[i] = indices[i + 2];
  22125. indices[i + 2] = tmp;
  22126. }
  22127. for (n = 0; n < ln; n++) {
  22128. normals[n] = -normals[n];
  22129. }
  22130. break;
  22131. case BABYLON.Mesh.DOUBLESIDE:
  22132. // positions
  22133. var lp = positions.length;
  22134. var l = lp / 3;
  22135. for (var p = 0; p < lp; p++) {
  22136. positions[lp + p] = positions[p];
  22137. }
  22138. for (i = 0; i < li; i += 3) {
  22139. indices[i + li] = indices[i + 2] + l;
  22140. indices[i + 1 + li] = indices[i + 1] + l;
  22141. indices[i + 2 + li] = indices[i] + l;
  22142. }
  22143. for (n = 0; n < ln; n++) {
  22144. normals[ln + n] = -normals[n];
  22145. }
  22146. // uvs
  22147. var lu = uvs.length;
  22148. for (var u = 0; u < lu; u++) {
  22149. uvs[u + lu] = uvs[u];
  22150. }
  22151. break;
  22152. }
  22153. };
  22154. return VertexData;
  22155. })();
  22156. BABYLON.VertexData = VertexData;
  22157. })(BABYLON || (BABYLON = {}));
  22158. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22159. var BABYLON;
  22160. (function (BABYLON) {
  22161. var buildCamera = function (that, name) {
  22162. that._leftCamera.isIntermediate = true;
  22163. that.subCameras.push(that._leftCamera);
  22164. that.subCameras.push(that._rightCamera);
  22165. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22166. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22167. that._anaglyphPostProcess.onApply = function (effect) {
  22168. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22169. };
  22170. that._update();
  22171. };
  22172. var AnaglyphArcRotateCamera = (function (_super) {
  22173. __extends(AnaglyphArcRotateCamera, _super);
  22174. // ANY
  22175. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22176. _super.call(this, name, alpha, beta, radius, target, scene);
  22177. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22178. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22179. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22180. buildCamera(this, name);
  22181. }
  22182. AnaglyphArcRotateCamera.prototype._update = function () {
  22183. this._updateCamera(this._leftCamera);
  22184. this._updateCamera(this._rightCamera);
  22185. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22186. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22187. _super.prototype._update.call(this);
  22188. };
  22189. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22190. camera.beta = this.beta;
  22191. camera.radius = this.radius;
  22192. camera.minZ = this.minZ;
  22193. camera.maxZ = this.maxZ;
  22194. camera.fov = this.fov;
  22195. camera.target = this.target;
  22196. };
  22197. return AnaglyphArcRotateCamera;
  22198. })(BABYLON.ArcRotateCamera);
  22199. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22200. var AnaglyphFreeCamera = (function (_super) {
  22201. __extends(AnaglyphFreeCamera, _super);
  22202. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22203. _super.call(this, name, position, scene);
  22204. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22205. this._transformMatrix = new BABYLON.Matrix();
  22206. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22207. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22208. buildCamera(this, name);
  22209. }
  22210. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22211. var target = this.getTarget();
  22212. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22213. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22214. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22215. };
  22216. AnaglyphFreeCamera.prototype._update = function () {
  22217. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22218. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22219. this._updateCamera(this._leftCamera);
  22220. this._updateCamera(this._rightCamera);
  22221. _super.prototype._update.call(this);
  22222. };
  22223. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22224. camera.minZ = this.minZ;
  22225. camera.maxZ = this.maxZ;
  22226. camera.fov = this.fov;
  22227. camera.viewport = this.viewport;
  22228. camera.setTarget(this.getTarget());
  22229. };
  22230. return AnaglyphFreeCamera;
  22231. })(BABYLON.FreeCamera);
  22232. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22233. })(BABYLON || (BABYLON = {}));
  22234. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22235. var BABYLON;
  22236. (function (BABYLON) {
  22237. var AnaglyphPostProcess = (function (_super) {
  22238. __extends(AnaglyphPostProcess, _super);
  22239. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22240. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22241. }
  22242. return AnaglyphPostProcess;
  22243. })(BABYLON.PostProcess);
  22244. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22245. })(BABYLON || (BABYLON = {}));
  22246. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22247. (function (BABYLON) {
  22248. var Tags = (function () {
  22249. function Tags() {
  22250. }
  22251. Tags.EnableFor = function (obj) {
  22252. obj._tags = obj._tags || {};
  22253. obj.hasTags = function () {
  22254. return Tags.HasTags(obj);
  22255. };
  22256. obj.addTags = function (tagsString) {
  22257. return Tags.AddTagsTo(obj, tagsString);
  22258. };
  22259. obj.removeTags = function (tagsString) {
  22260. return Tags.RemoveTagsFrom(obj, tagsString);
  22261. };
  22262. obj.matchesTagsQuery = function (tagsQuery) {
  22263. return Tags.MatchesQuery(obj, tagsQuery);
  22264. };
  22265. };
  22266. Tags.DisableFor = function (obj) {
  22267. delete obj._tags;
  22268. delete obj.hasTags;
  22269. delete obj.addTags;
  22270. delete obj.removeTags;
  22271. delete obj.matchesTagsQuery;
  22272. };
  22273. Tags.HasTags = function (obj) {
  22274. if (!obj._tags) {
  22275. return false;
  22276. }
  22277. return !BABYLON.Tools.IsEmpty(obj._tags);
  22278. };
  22279. Tags.GetTags = function (obj) {
  22280. if (!obj._tags) {
  22281. return null;
  22282. }
  22283. return obj._tags;
  22284. };
  22285. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22286. // a tag cannot start with '||', '&&', and '!'
  22287. // it cannot contain whitespaces
  22288. Tags.AddTagsTo = function (obj, tagsString) {
  22289. if (!tagsString) {
  22290. return;
  22291. }
  22292. var tags = tagsString.split(" ");
  22293. for (var t in tags) {
  22294. Tags._AddTagTo(obj, tags[t]);
  22295. }
  22296. };
  22297. Tags._AddTagTo = function (obj, tag) {
  22298. tag = tag.trim();
  22299. if (tag === "" || tag === "true" || tag === "false") {
  22300. return;
  22301. }
  22302. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22303. return;
  22304. }
  22305. Tags.EnableFor(obj);
  22306. obj._tags[tag] = true;
  22307. };
  22308. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22309. if (!Tags.HasTags(obj)) {
  22310. return;
  22311. }
  22312. var tags = tagsString.split(" ");
  22313. for (var t in tags) {
  22314. Tags._RemoveTagFrom(obj, tags[t]);
  22315. }
  22316. };
  22317. Tags._RemoveTagFrom = function (obj, tag) {
  22318. delete obj._tags[tag];
  22319. };
  22320. Tags.MatchesQuery = function (obj, tagsQuery) {
  22321. if (tagsQuery === undefined) {
  22322. return true;
  22323. }
  22324. if (tagsQuery === "") {
  22325. return Tags.HasTags(obj);
  22326. }
  22327. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22328. };
  22329. return Tags;
  22330. })();
  22331. BABYLON.Tags = Tags;
  22332. })(BABYLON || (BABYLON = {}));
  22333. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22334. (function (BABYLON) {
  22335. var Internals;
  22336. (function (Internals) {
  22337. var AndOrNotEvaluator = (function () {
  22338. function AndOrNotEvaluator() {
  22339. }
  22340. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22341. if (!query.match(/\([^\(\)]*\)/g)) {
  22342. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22343. }
  22344. else {
  22345. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22346. // remove parenthesis
  22347. r = r.slice(1, r.length - 1);
  22348. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22349. });
  22350. }
  22351. if (query === "true") {
  22352. return true;
  22353. }
  22354. if (query === "false") {
  22355. return false;
  22356. }
  22357. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22358. };
  22359. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22360. evaluateCallback = evaluateCallback || (function (r) {
  22361. return r === "true" ? true : false;
  22362. });
  22363. var result;
  22364. var or = parenthesisContent.split("||");
  22365. for (var i in or) {
  22366. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22367. var and = ori.split("&&");
  22368. if (and.length > 1) {
  22369. for (var j = 0; j < and.length; ++j) {
  22370. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22371. if (andj !== "true" && andj !== "false") {
  22372. if (andj[0] === "!") {
  22373. result = !evaluateCallback(andj.substring(1));
  22374. }
  22375. else {
  22376. result = evaluateCallback(andj);
  22377. }
  22378. }
  22379. else {
  22380. result = andj === "true" ? true : false;
  22381. }
  22382. if (!result) {
  22383. ori = "false";
  22384. break;
  22385. }
  22386. }
  22387. }
  22388. if (result || ori === "true") {
  22389. result = true;
  22390. break;
  22391. }
  22392. // result equals false (or undefined)
  22393. if (ori !== "true" && ori !== "false") {
  22394. if (ori[0] === "!") {
  22395. result = !evaluateCallback(ori.substring(1));
  22396. }
  22397. else {
  22398. result = evaluateCallback(ori);
  22399. }
  22400. }
  22401. else {
  22402. result = ori === "true" ? true : false;
  22403. }
  22404. }
  22405. // the whole parenthesis scope is replaced by 'true' or 'false'
  22406. return result ? "true" : "false";
  22407. };
  22408. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22409. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22410. // remove whitespaces
  22411. r = r.replace(/[\s]/g, function () { return ""; });
  22412. return r.length % 2 ? "!" : "";
  22413. });
  22414. booleanString = booleanString.trim();
  22415. if (booleanString === "!true") {
  22416. booleanString = "false";
  22417. }
  22418. else if (booleanString === "!false") {
  22419. booleanString = "true";
  22420. }
  22421. return booleanString;
  22422. };
  22423. return AndOrNotEvaluator;
  22424. })();
  22425. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22426. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22427. })(BABYLON || (BABYLON = {}));
  22428. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22429. (function (BABYLON) {
  22430. var PostProcessRenderPass = (function () {
  22431. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22432. this._enabled = true;
  22433. this._refCount = 0;
  22434. this._name = name;
  22435. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22436. this.setRenderList(renderList);
  22437. this._renderTexture.onBeforeRender = beforeRender;
  22438. this._renderTexture.onAfterRender = afterRender;
  22439. this._scene = scene;
  22440. this._renderList = renderList;
  22441. }
  22442. // private
  22443. PostProcessRenderPass.prototype._incRefCount = function () {
  22444. if (this._refCount === 0) {
  22445. this._scene.customRenderTargets.push(this._renderTexture);
  22446. }
  22447. return ++this._refCount;
  22448. };
  22449. PostProcessRenderPass.prototype._decRefCount = function () {
  22450. this._refCount--;
  22451. if (this._refCount <= 0) {
  22452. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22453. }
  22454. return this._refCount;
  22455. };
  22456. PostProcessRenderPass.prototype._update = function () {
  22457. this.setRenderList(this._renderList);
  22458. };
  22459. // public
  22460. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22461. this._renderTexture.renderList = renderList;
  22462. };
  22463. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22464. return this._renderTexture;
  22465. };
  22466. return PostProcessRenderPass;
  22467. })();
  22468. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22469. })(BABYLON || (BABYLON = {}));
  22470. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22471. (function (BABYLON) {
  22472. var PostProcessRenderEffect = (function () {
  22473. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22474. this._engine = engine;
  22475. this._name = name;
  22476. this._singleInstance = singleInstance || true;
  22477. this._getPostProcess = getPostProcess;
  22478. this._cameras = [];
  22479. this._indicesForCamera = [];
  22480. this._postProcesses = {};
  22481. this._renderPasses = {};
  22482. this._renderEffectAsPasses = {};
  22483. }
  22484. PostProcessRenderEffect.prototype._update = function () {
  22485. for (var renderPassName in this._renderPasses) {
  22486. this._renderPasses[renderPassName]._update();
  22487. }
  22488. };
  22489. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22490. this._renderPasses[renderPass._name] = renderPass;
  22491. this._linkParameters();
  22492. };
  22493. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22494. delete this._renderPasses[renderPass._name];
  22495. this._linkParameters();
  22496. };
  22497. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22498. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22499. this._linkParameters();
  22500. };
  22501. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22502. for (var renderPassName in this._renderPasses) {
  22503. if (renderPassName === passName) {
  22504. return this._renderPasses[passName];
  22505. }
  22506. }
  22507. };
  22508. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22509. this._renderPasses = {};
  22510. this._linkParameters();
  22511. };
  22512. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22513. var cameraKey;
  22514. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22515. for (var i = 0; i < _cam.length; i++) {
  22516. var camera = _cam[i];
  22517. var cameraName = camera.name;
  22518. if (this._singleInstance) {
  22519. cameraKey = 0;
  22520. }
  22521. else {
  22522. cameraKey = cameraName;
  22523. }
  22524. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22525. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22526. if (!this._indicesForCamera[cameraName]) {
  22527. this._indicesForCamera[cameraName] = [];
  22528. }
  22529. this._indicesForCamera[cameraName].push(index);
  22530. if (this._cameras.indexOf(camera) === -1) {
  22531. this._cameras[cameraName] = camera;
  22532. }
  22533. for (var passName in this._renderPasses) {
  22534. this._renderPasses[passName]._incRefCount();
  22535. }
  22536. }
  22537. this._linkParameters();
  22538. };
  22539. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22540. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22541. for (var i = 0; i < _cam.length; i++) {
  22542. var camera = _cam[i];
  22543. var cameraName = camera.name;
  22544. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22545. var index = this._cameras.indexOf(cameraName);
  22546. this._indicesForCamera.splice(index, 1);
  22547. this._cameras.splice(index, 1);
  22548. for (var passName in this._renderPasses) {
  22549. this._renderPasses[passName]._decRefCount();
  22550. }
  22551. }
  22552. };
  22553. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22554. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22555. for (var i = 0; i < _cam.length; i++) {
  22556. var camera = _cam[i];
  22557. var cameraName = camera.name;
  22558. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22559. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22560. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22561. }
  22562. }
  22563. for (var passName in this._renderPasses) {
  22564. this._renderPasses[passName]._incRefCount();
  22565. }
  22566. }
  22567. };
  22568. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22569. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22570. for (var i = 0; i < _cam.length; i++) {
  22571. var camera = _cam[i];
  22572. var cameraName = camera.Name;
  22573. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22574. for (var passName in this._renderPasses) {
  22575. this._renderPasses[passName]._decRefCount();
  22576. }
  22577. }
  22578. };
  22579. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22580. if (this._singleInstance) {
  22581. return this._postProcesses[0];
  22582. }
  22583. else {
  22584. return this._postProcesses[camera.name];
  22585. }
  22586. };
  22587. PostProcessRenderEffect.prototype._linkParameters = function () {
  22588. var _this = this;
  22589. for (var index in this._postProcesses) {
  22590. if (this.applyParameters) {
  22591. this.applyParameters(this._postProcesses[index]);
  22592. }
  22593. this._postProcesses[index].onBeforeRender = function (effect) {
  22594. _this._linkTextures(effect);
  22595. };
  22596. }
  22597. };
  22598. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22599. for (var renderPassName in this._renderPasses) {
  22600. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22601. }
  22602. for (var renderEffectName in this._renderEffectAsPasses) {
  22603. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22604. }
  22605. };
  22606. return PostProcessRenderEffect;
  22607. })();
  22608. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22609. })(BABYLON || (BABYLON = {}));
  22610. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22611. (function (BABYLON) {
  22612. var PostProcessRenderPipeline = (function () {
  22613. function PostProcessRenderPipeline(engine, name) {
  22614. this._engine = engine;
  22615. this._name = name;
  22616. this._renderEffects = {};
  22617. this._renderEffectsForIsolatedPass = {};
  22618. this._cameras = [];
  22619. }
  22620. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22621. this._renderEffects[renderEffect._name] = renderEffect;
  22622. };
  22623. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22624. var renderEffects = this._renderEffects[renderEffectName];
  22625. if (!renderEffects) {
  22626. return;
  22627. }
  22628. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22629. };
  22630. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22631. var renderEffects = this._renderEffects[renderEffectName];
  22632. if (!renderEffects) {
  22633. return;
  22634. }
  22635. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22636. };
  22637. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22638. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22639. var indicesToDelete = [];
  22640. for (var i = 0; i < _cam.length; i++) {
  22641. var camera = _cam[i];
  22642. var cameraName = camera.name;
  22643. if (this._cameras.indexOf(camera) === -1) {
  22644. this._cameras[cameraName] = camera;
  22645. }
  22646. else if (unique) {
  22647. indicesToDelete.push(i);
  22648. }
  22649. }
  22650. for (var i = 0; i < indicesToDelete.length; i++) {
  22651. cameras.splice(indicesToDelete[i], 1);
  22652. }
  22653. for (var renderEffectName in this._renderEffects) {
  22654. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22655. }
  22656. };
  22657. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22658. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22659. for (var renderEffectName in this._renderEffects) {
  22660. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22661. }
  22662. for (var i = 0; i < _cam.length; i++) {
  22663. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22664. }
  22665. };
  22666. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22667. var _this = this;
  22668. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22669. var pass = null;
  22670. for (var renderEffectName in this._renderEffects) {
  22671. pass = this._renderEffects[renderEffectName].getPass(passName);
  22672. if (pass != null) {
  22673. break;
  22674. }
  22675. }
  22676. if (pass === null) {
  22677. return;
  22678. }
  22679. for (var renderEffectName in this._renderEffects) {
  22680. this._renderEffects[renderEffectName]._disable(_cam);
  22681. }
  22682. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22683. for (var i = 0; i < _cam.length; i++) {
  22684. var camera = _cam[i];
  22685. var cameraName = camera.name;
  22686. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22687. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22688. });
  22689. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22690. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22691. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22692. }
  22693. };
  22694. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22695. var _this = this;
  22696. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22697. for (var i = 0; i < _cam.length; i++) {
  22698. var camera = _cam[i];
  22699. var cameraName = camera.name;
  22700. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22701. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22702. });
  22703. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22704. }
  22705. for (var renderEffectName in this._renderEffects) {
  22706. this._renderEffects[renderEffectName]._enable(_cam);
  22707. }
  22708. };
  22709. PostProcessRenderPipeline.prototype._update = function () {
  22710. for (var renderEffectName in this._renderEffects) {
  22711. this._renderEffects[renderEffectName]._update();
  22712. }
  22713. for (var i = 0; i < this._cameras.length; i++) {
  22714. var cameraName = this._cameras[i].name;
  22715. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22716. this._renderEffectsForIsolatedPass[cameraName]._update();
  22717. }
  22718. }
  22719. };
  22720. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22721. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22722. return PostProcessRenderPipeline;
  22723. })();
  22724. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22725. })(BABYLON || (BABYLON = {}));
  22726. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22727. (function (BABYLON) {
  22728. var PostProcessRenderPipelineManager = (function () {
  22729. function PostProcessRenderPipelineManager() {
  22730. this._renderPipelines = {};
  22731. }
  22732. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22733. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22734. };
  22735. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22736. var renderPipeline = this._renderPipelines[renderPipelineName];
  22737. if (!renderPipeline) {
  22738. return;
  22739. }
  22740. renderPipeline._attachCameras(cameras, unique);
  22741. };
  22742. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22743. var renderPipeline = this._renderPipelines[renderPipelineName];
  22744. if (!renderPipeline) {
  22745. return;
  22746. }
  22747. renderPipeline._detachCameras(cameras);
  22748. };
  22749. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22750. var renderPipeline = this._renderPipelines[renderPipelineName];
  22751. if (!renderPipeline) {
  22752. return;
  22753. }
  22754. renderPipeline._enableEffect(renderEffectName, cameras);
  22755. };
  22756. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22757. var renderPipeline = this._renderPipelines[renderPipelineName];
  22758. if (!renderPipeline) {
  22759. return;
  22760. }
  22761. renderPipeline._disableEffect(renderEffectName, cameras);
  22762. };
  22763. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22764. var renderPipeline = this._renderPipelines[renderPipelineName];
  22765. if (!renderPipeline) {
  22766. return;
  22767. }
  22768. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22769. };
  22770. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22771. var renderPipeline = this._renderPipelines[renderPipelineName];
  22772. if (!renderPipeline) {
  22773. return;
  22774. }
  22775. renderPipeline._disableDisplayOnlyPass(cameras);
  22776. };
  22777. PostProcessRenderPipelineManager.prototype.update = function () {
  22778. for (var renderPipelineName in this._renderPipelines) {
  22779. this._renderPipelines[renderPipelineName]._update();
  22780. }
  22781. };
  22782. return PostProcessRenderPipelineManager;
  22783. })();
  22784. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22785. })(BABYLON || (BABYLON = {}));
  22786. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22787. var BABYLON;
  22788. (function (BABYLON) {
  22789. var DisplayPassPostProcess = (function (_super) {
  22790. __extends(DisplayPassPostProcess, _super);
  22791. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22792. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22793. }
  22794. return DisplayPassPostProcess;
  22795. })(BABYLON.PostProcess);
  22796. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22797. })(BABYLON || (BABYLON = {}));
  22798. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22799. (function (BABYLON) {
  22800. var BoundingBoxRenderer = (function () {
  22801. function BoundingBoxRenderer(scene) {
  22802. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22803. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22804. this.showBackLines = true;
  22805. this.renderList = new BABYLON.SmartArray(32);
  22806. this._scene = scene;
  22807. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22808. attributes: ["position"],
  22809. uniforms: ["worldViewProjection", "color"]
  22810. });
  22811. var engine = this._scene.getEngine();
  22812. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22813. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22814. 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]);
  22815. }
  22816. BoundingBoxRenderer.prototype.reset = function () {
  22817. this.renderList.reset();
  22818. };
  22819. BoundingBoxRenderer.prototype.render = function () {
  22820. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22821. return;
  22822. }
  22823. var engine = this._scene.getEngine();
  22824. engine.setDepthWrite(false);
  22825. this._colorShader._preBind();
  22826. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22827. var boundingBox = this.renderList.data[boundingBoxIndex];
  22828. var min = boundingBox.minimum;
  22829. var max = boundingBox.maximum;
  22830. var diff = max.subtract(min);
  22831. var median = min.add(diff.scale(0.5));
  22832. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22833. // VBOs
  22834. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22835. if (this.showBackLines) {
  22836. // Back
  22837. engine.setDepthFunctionToGreaterOrEqual();
  22838. this._scene.resetCachedMaterial();
  22839. this._colorShader.setColor4("color", this.backColor.toColor4());
  22840. this._colorShader.bind(worldMatrix);
  22841. // Draw order
  22842. engine.draw(false, 0, 24);
  22843. }
  22844. // Front
  22845. engine.setDepthFunctionToLess();
  22846. this._scene.resetCachedMaterial();
  22847. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22848. this._colorShader.bind(worldMatrix);
  22849. // Draw order
  22850. engine.draw(false, 0, 24);
  22851. }
  22852. this._colorShader.unbind();
  22853. engine.setDepthFunctionToLessOrEqual();
  22854. engine.setDepthWrite(true);
  22855. };
  22856. BoundingBoxRenderer.prototype.dispose = function () {
  22857. this._colorShader.dispose();
  22858. this._vb.dispose();
  22859. this._scene.getEngine()._releaseBuffer(this._ib);
  22860. };
  22861. return BoundingBoxRenderer;
  22862. })();
  22863. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22864. })(BABYLON || (BABYLON = {}));
  22865. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22866. (function (BABYLON) {
  22867. var Internals;
  22868. (function (Internals) {
  22869. /*
  22870. * Based on jsTGALoader - Javascript loader for TGA file
  22871. * By Vincent Thibault
  22872. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22873. */
  22874. var TGATools = (function () {
  22875. function TGATools() {
  22876. }
  22877. TGATools.GetTGAHeader = function (data) {
  22878. var offset = 0;
  22879. var header = {
  22880. id_length: data[offset++],
  22881. colormap_type: data[offset++],
  22882. image_type: data[offset++],
  22883. colormap_index: data[offset++] | data[offset++] << 8,
  22884. colormap_length: data[offset++] | data[offset++] << 8,
  22885. colormap_size: data[offset++],
  22886. origin: [
  22887. data[offset++] | data[offset++] << 8,
  22888. data[offset++] | data[offset++] << 8
  22889. ],
  22890. width: data[offset++] | data[offset++] << 8,
  22891. height: data[offset++] | data[offset++] << 8,
  22892. pixel_size: data[offset++],
  22893. flags: data[offset++]
  22894. };
  22895. return header;
  22896. };
  22897. TGATools.UploadContent = function (gl, data) {
  22898. // Not enough data to contain header ?
  22899. if (data.length < 19) {
  22900. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22901. return;
  22902. }
  22903. // Read Header
  22904. var offset = 18;
  22905. var header = TGATools.GetTGAHeader(data);
  22906. // Assume it's a valid Targa file.
  22907. if (header.id_length + offset > data.length) {
  22908. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22909. return;
  22910. }
  22911. // Skip not needed data
  22912. offset += header.id_length;
  22913. var use_rle = false;
  22914. var use_pal = false;
  22915. var use_rgb = false;
  22916. var use_grey = false;
  22917. switch (header.image_type) {
  22918. case TGATools._TYPE_RLE_INDEXED:
  22919. use_rle = true;
  22920. case TGATools._TYPE_INDEXED:
  22921. use_pal = true;
  22922. break;
  22923. case TGATools._TYPE_RLE_RGB:
  22924. use_rle = true;
  22925. case TGATools._TYPE_RGB:
  22926. use_rgb = true;
  22927. break;
  22928. case TGATools._TYPE_RLE_GREY:
  22929. use_rle = true;
  22930. case TGATools._TYPE_GREY:
  22931. use_grey = true;
  22932. break;
  22933. }
  22934. var pixel_data;
  22935. var numAlphaBits = header.flags & 0xf;
  22936. var pixel_size = header.pixel_size >> 3;
  22937. var pixel_total = header.width * header.height * pixel_size;
  22938. // Read palettes
  22939. var palettes;
  22940. if (use_pal) {
  22941. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22942. }
  22943. // Read LRE
  22944. if (use_rle) {
  22945. pixel_data = new Uint8Array(pixel_total);
  22946. var c, count, i;
  22947. var localOffset = 0;
  22948. var pixels = new Uint8Array(pixel_size);
  22949. while (offset < pixel_total && localOffset < pixel_total) {
  22950. c = data[offset++];
  22951. count = (c & 0x7f) + 1;
  22952. // RLE pixels
  22953. if (c & 0x80) {
  22954. for (i = 0; i < pixel_size; ++i) {
  22955. pixels[i] = data[offset++];
  22956. }
  22957. for (i = 0; i < count; ++i) {
  22958. pixel_data.set(pixels, localOffset + i * pixel_size);
  22959. }
  22960. localOffset += pixel_size * count;
  22961. }
  22962. else {
  22963. count *= pixel_size;
  22964. for (i = 0; i < count; ++i) {
  22965. pixel_data[localOffset + i] = data[offset++];
  22966. }
  22967. localOffset += count;
  22968. }
  22969. }
  22970. }
  22971. else {
  22972. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22973. }
  22974. // Load to texture
  22975. var x_start, y_start, x_step, y_step, y_end, x_end;
  22976. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22977. default:
  22978. case TGATools._ORIGIN_UL:
  22979. x_start = 0;
  22980. x_step = 1;
  22981. x_end = header.width;
  22982. y_start = 0;
  22983. y_step = 1;
  22984. y_end = header.height;
  22985. break;
  22986. case TGATools._ORIGIN_BL:
  22987. x_start = 0;
  22988. x_step = 1;
  22989. x_end = header.width;
  22990. y_start = header.height - 1;
  22991. y_step = -1;
  22992. y_end = -1;
  22993. break;
  22994. case TGATools._ORIGIN_UR:
  22995. x_start = header.width - 1;
  22996. x_step = -1;
  22997. x_end = -1;
  22998. y_start = 0;
  22999. y_step = 1;
  23000. y_end = header.height;
  23001. break;
  23002. case TGATools._ORIGIN_BR:
  23003. x_start = header.width - 1;
  23004. x_step = -1;
  23005. x_end = -1;
  23006. y_start = header.height - 1;
  23007. y_step = -1;
  23008. y_end = -1;
  23009. break;
  23010. }
  23011. // Load the specify method
  23012. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23013. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23014. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23015. };
  23016. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23017. var image = pixel_data, colormap = palettes;
  23018. var width = header.width, height = header.height;
  23019. var color, i = 0, x, y;
  23020. var imageData = new Uint8Array(width * height * 4);
  23021. for (y = y_start; y !== y_end; y += y_step) {
  23022. for (x = x_start; x !== x_end; x += x_step, i++) {
  23023. color = image[i];
  23024. imageData[(x + width * y) * 4 + 3] = 255;
  23025. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23026. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23027. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23028. }
  23029. }
  23030. return imageData;
  23031. };
  23032. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23033. var image = pixel_data;
  23034. var width = header.width, height = header.height;
  23035. var color, i = 0, x, y;
  23036. var imageData = new Uint8Array(width * height * 4);
  23037. for (y = y_start; y !== y_end; y += y_step) {
  23038. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23039. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23040. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23041. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23042. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23043. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23044. }
  23045. }
  23046. return imageData;
  23047. };
  23048. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23049. var image = pixel_data;
  23050. var width = header.width, height = header.height;
  23051. var i = 0, x, y;
  23052. var imageData = new Uint8Array(width * height * 4);
  23053. for (y = y_start; y !== y_end; y += y_step) {
  23054. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23055. imageData[(x + width * y) * 4 + 3] = 255;
  23056. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23057. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23058. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23059. }
  23060. }
  23061. return imageData;
  23062. };
  23063. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23064. var image = pixel_data;
  23065. var width = header.width, height = header.height;
  23066. var i = 0, x, y;
  23067. var imageData = new Uint8Array(width * height * 4);
  23068. for (y = y_start; y !== y_end; y += y_step) {
  23069. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23070. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23071. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23072. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23073. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23074. }
  23075. }
  23076. return imageData;
  23077. };
  23078. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23079. var image = pixel_data;
  23080. var width = header.width, height = header.height;
  23081. var color, i = 0, x, y;
  23082. var imageData = new Uint8Array(width * height * 4);
  23083. for (y = y_start; y !== y_end; y += y_step) {
  23084. for (x = x_start; x !== x_end; x += x_step, i++) {
  23085. color = image[i];
  23086. imageData[(x + width * y) * 4 + 0] = color;
  23087. imageData[(x + width * y) * 4 + 1] = color;
  23088. imageData[(x + width * y) * 4 + 2] = color;
  23089. imageData[(x + width * y) * 4 + 3] = 255;
  23090. }
  23091. }
  23092. return imageData;
  23093. };
  23094. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23095. var image = pixel_data;
  23096. var width = header.width, height = header.height;
  23097. var i = 0, x, y;
  23098. var imageData = new Uint8Array(width * height * 4);
  23099. for (y = y_start; y !== y_end; y += y_step) {
  23100. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23101. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23102. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23103. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23104. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23105. }
  23106. }
  23107. return imageData;
  23108. };
  23109. TGATools._TYPE_NO_DATA = 0;
  23110. TGATools._TYPE_INDEXED = 1;
  23111. TGATools._TYPE_RGB = 2;
  23112. TGATools._TYPE_GREY = 3;
  23113. TGATools._TYPE_RLE_INDEXED = 9;
  23114. TGATools._TYPE_RLE_RGB = 10;
  23115. TGATools._TYPE_RLE_GREY = 11;
  23116. TGATools._ORIGIN_MASK = 0x30;
  23117. TGATools._ORIGIN_SHIFT = 0x04;
  23118. TGATools._ORIGIN_BL = 0x00;
  23119. TGATools._ORIGIN_BR = 0x01;
  23120. TGATools._ORIGIN_UL = 0x02;
  23121. TGATools._ORIGIN_UR = 0x03;
  23122. return TGATools;
  23123. })();
  23124. Internals.TGATools = TGATools;
  23125. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23126. })(BABYLON || (BABYLON = {}));
  23127. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23128. (function (BABYLON) {
  23129. var Internals;
  23130. (function (Internals) {
  23131. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23132. // All values and structures referenced from:
  23133. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23134. var DDS_MAGIC = 0x20534444;
  23135. 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;
  23136. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23137. 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;
  23138. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23139. function FourCCToInt32(value) {
  23140. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23141. }
  23142. function Int32ToFourCC(value) {
  23143. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23144. }
  23145. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23146. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23147. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23148. var headerLengthInt = 31; // The header length in 32 bit ints
  23149. // Offsets into the header array
  23150. var off_magic = 0;
  23151. var off_size = 1;
  23152. var off_flags = 2;
  23153. var off_height = 3;
  23154. var off_width = 4;
  23155. var off_mipmapCount = 7;
  23156. var off_pfFlags = 20;
  23157. var off_pfFourCC = 21;
  23158. var off_RGBbpp = 22;
  23159. var off_RMask = 23;
  23160. var off_GMask = 24;
  23161. var off_BMask = 25;
  23162. var off_AMask = 26;
  23163. var off_caps1 = 27;
  23164. var off_caps2 = 28;
  23165. ;
  23166. var DDSTools = (function () {
  23167. function DDSTools() {
  23168. }
  23169. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23170. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23171. var mipmapCount = 1;
  23172. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23173. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23174. }
  23175. return {
  23176. width: header[off_width],
  23177. height: header[off_height],
  23178. mipmapCount: mipmapCount,
  23179. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23180. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23181. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23182. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23183. };
  23184. };
  23185. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23186. var byteArray = new Uint8Array(dataLength);
  23187. var srcData = new Uint8Array(arrayBuffer);
  23188. var index = 0;
  23189. for (var y = height - 1; y >= 0; y--) {
  23190. for (var x = 0; x < width; x++) {
  23191. var srcPos = dataOffset + (x + y * width) * 4;
  23192. byteArray[index + 2] = srcData[srcPos];
  23193. byteArray[index + 1] = srcData[srcPos + 1];
  23194. byteArray[index] = srcData[srcPos + 2];
  23195. byteArray[index + 3] = srcData[srcPos + 3];
  23196. index += 4;
  23197. }
  23198. }
  23199. return byteArray;
  23200. };
  23201. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23202. var byteArray = new Uint8Array(dataLength);
  23203. var srcData = new Uint8Array(arrayBuffer);
  23204. var index = 0;
  23205. for (var y = height - 1; y >= 0; y--) {
  23206. for (var x = 0; x < width; x++) {
  23207. var srcPos = dataOffset + (x + y * width) * 3;
  23208. byteArray[index + 2] = srcData[srcPos];
  23209. byteArray[index + 1] = srcData[srcPos + 1];
  23210. byteArray[index] = srcData[srcPos + 2];
  23211. index += 3;
  23212. }
  23213. }
  23214. return byteArray;
  23215. };
  23216. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23217. var byteArray = new Uint8Array(dataLength);
  23218. var srcData = new Uint8Array(arrayBuffer);
  23219. var index = 0;
  23220. for (var y = height - 1; y >= 0; y--) {
  23221. for (var x = 0; x < width; x++) {
  23222. var srcPos = dataOffset + (x + y * width);
  23223. byteArray[index] = srcData[srcPos];
  23224. index++;
  23225. }
  23226. }
  23227. return byteArray;
  23228. };
  23229. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23230. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23231. if (header[off_magic] != DDS_MAGIC) {
  23232. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23233. return;
  23234. }
  23235. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23236. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23237. return;
  23238. }
  23239. if (info.isFourCC) {
  23240. fourCC = header[off_pfFourCC];
  23241. switch (fourCC) {
  23242. case FOURCC_DXT1:
  23243. blockBytes = 8;
  23244. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23245. break;
  23246. case FOURCC_DXT3:
  23247. blockBytes = 16;
  23248. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23249. break;
  23250. case FOURCC_DXT5:
  23251. blockBytes = 16;
  23252. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23253. break;
  23254. default:
  23255. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23256. return;
  23257. }
  23258. }
  23259. mipmapCount = 1;
  23260. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23261. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23262. }
  23263. var bpp = header[off_RGBbpp];
  23264. for (var face = 0; face < faces; face++) {
  23265. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23266. width = header[off_width];
  23267. height = header[off_height];
  23268. dataOffset = header[off_size] + 4;
  23269. for (i = 0; i < mipmapCount; ++i) {
  23270. if (info.isRGB) {
  23271. if (bpp == 24) {
  23272. dataLength = width * height * 3;
  23273. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23274. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23275. }
  23276. else {
  23277. dataLength = width * height * 4;
  23278. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23279. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23280. }
  23281. }
  23282. else if (info.isLuminance) {
  23283. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23284. var unpaddedRowSize = width;
  23285. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23286. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23287. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23288. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23289. }
  23290. else {
  23291. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23292. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23293. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23294. }
  23295. dataOffset += dataLength;
  23296. width *= 0.5;
  23297. height *= 0.5;
  23298. width = Math.max(1.0, width);
  23299. height = Math.max(1.0, height);
  23300. }
  23301. }
  23302. };
  23303. return DDSTools;
  23304. })();
  23305. Internals.DDSTools = DDSTools;
  23306. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23307. })(BABYLON || (BABYLON = {}));
  23308. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23309. (function (BABYLON) {
  23310. var SmartArray = (function () {
  23311. function SmartArray(capacity) {
  23312. this.length = 0;
  23313. this._duplicateId = 0;
  23314. this.data = new Array(capacity);
  23315. this._id = SmartArray._GlobalId++;
  23316. }
  23317. SmartArray.prototype.push = function (value) {
  23318. this.data[this.length++] = value;
  23319. if (this.length > this.data.length) {
  23320. this.data.length *= 2;
  23321. }
  23322. if (!value.__smartArrayFlags) {
  23323. value.__smartArrayFlags = {};
  23324. }
  23325. value.__smartArrayFlags[this._id] = this._duplicateId;
  23326. };
  23327. SmartArray.prototype.pushNoDuplicate = function (value) {
  23328. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23329. return;
  23330. }
  23331. this.push(value);
  23332. };
  23333. SmartArray.prototype.sort = function (compareFn) {
  23334. this.data.sort(compareFn);
  23335. };
  23336. SmartArray.prototype.reset = function () {
  23337. this.length = 0;
  23338. this._duplicateId++;
  23339. };
  23340. SmartArray.prototype.concat = function (array) {
  23341. if (array.length === 0) {
  23342. return;
  23343. }
  23344. if (this.length + array.length > this.data.length) {
  23345. this.data.length = (this.length + array.length) * 2;
  23346. }
  23347. for (var index = 0; index < array.length; index++) {
  23348. this.data[this.length++] = (array.data || array)[index];
  23349. }
  23350. };
  23351. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23352. if (array.length === 0) {
  23353. return;
  23354. }
  23355. if (this.length + array.length > this.data.length) {
  23356. this.data.length = (this.length + array.length) * 2;
  23357. }
  23358. for (var index = 0; index < array.length; index++) {
  23359. var item = (array.data || array)[index];
  23360. this.pushNoDuplicate(item);
  23361. }
  23362. };
  23363. SmartArray.prototype.indexOf = function (value) {
  23364. var position = this.data.indexOf(value);
  23365. if (position >= this.length) {
  23366. return -1;
  23367. }
  23368. return position;
  23369. };
  23370. // Statics
  23371. SmartArray._GlobalId = 0;
  23372. return SmartArray;
  23373. })();
  23374. BABYLON.SmartArray = SmartArray;
  23375. })(BABYLON || (BABYLON = {}));
  23376. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23377. (function (BABYLON) {
  23378. var CannonJSPlugin = (function () {
  23379. function CannonJSPlugin() {
  23380. this._registeredMeshes = [];
  23381. this._physicsMaterials = [];
  23382. this.updateBodyPosition = function (mesh) {
  23383. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23384. var registeredMesh = this._registeredMeshes[index];
  23385. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23386. var body = registeredMesh.body;
  23387. var center = mesh.getBoundingInfo().boundingBox.center;
  23388. body.position.set(center.x, center.z, center.y);
  23389. body.quaternion.x = mesh.rotationQuaternion.x;
  23390. body.quaternion.z = mesh.rotationQuaternion.y;
  23391. body.quaternion.y = mesh.rotationQuaternion.z;
  23392. body.quaternion.w = -mesh.rotationQuaternion.w;
  23393. return;
  23394. }
  23395. }
  23396. };
  23397. }
  23398. CannonJSPlugin.prototype.initialize = function (iterations) {
  23399. if (iterations === void 0) { iterations = 10; }
  23400. this._world = new CANNON.World();
  23401. this._world.broadphase = new CANNON.NaiveBroadphase();
  23402. this._world.solver.iterations = iterations;
  23403. };
  23404. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23405. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23406. };
  23407. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23408. this._world.step(delta);
  23409. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23410. var registeredMesh = this._registeredMeshes[index];
  23411. if (registeredMesh.isChild) {
  23412. continue;
  23413. }
  23414. // Body position
  23415. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23416. var deltaPos = registeredMesh.delta;
  23417. if (deltaPos) {
  23418. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23419. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23420. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23421. }
  23422. else {
  23423. registeredMesh.mesh.position.x = bodyX;
  23424. registeredMesh.mesh.position.y = bodyZ;
  23425. registeredMesh.mesh.position.z = bodyY;
  23426. }
  23427. if (!registeredMesh.mesh.rotationQuaternion) {
  23428. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23429. }
  23430. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23431. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23432. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23433. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23434. }
  23435. };
  23436. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23437. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23438. };
  23439. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23440. this.unregisterMesh(mesh);
  23441. mesh.computeWorldMatrix(true);
  23442. switch (impostor) {
  23443. case BABYLON.PhysicsEngine.SphereImpostor:
  23444. var bbox = mesh.getBoundingInfo().boundingBox;
  23445. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23446. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23447. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23448. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23449. case BABYLON.PhysicsEngine.BoxImpostor:
  23450. bbox = mesh.getBoundingInfo().boundingBox;
  23451. var min = bbox.minimumWorld;
  23452. var max = bbox.maximumWorld;
  23453. var box = max.subtract(min).scale(0.5);
  23454. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23455. case BABYLON.PhysicsEngine.PlaneImpostor:
  23456. return this._createPlane(mesh, options);
  23457. case BABYLON.PhysicsEngine.MeshImpostor:
  23458. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23459. var rawFaces = mesh.getIndices();
  23460. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23461. }
  23462. return null;
  23463. };
  23464. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23465. var shape = new CANNON.Sphere(radius);
  23466. if (!options) {
  23467. return shape;
  23468. }
  23469. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23470. };
  23471. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23472. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23473. if (!options) {
  23474. return shape;
  23475. }
  23476. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23477. };
  23478. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23479. var shape = new CANNON.Plane();
  23480. if (!options) {
  23481. return shape;
  23482. }
  23483. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23484. };
  23485. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23486. var verts = [], faces = [];
  23487. mesh.computeWorldMatrix(true);
  23488. for (var i = 0; i < rawVerts.length; i += 3) {
  23489. var transformed = BABYLON.Vector3.Zero();
  23490. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23491. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23492. }
  23493. for (var j = 0; j < rawFaces.length; j += 3) {
  23494. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23495. }
  23496. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23497. if (!options) {
  23498. return shape;
  23499. }
  23500. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23501. };
  23502. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23503. var index;
  23504. var mat;
  23505. for (index = 0; index < this._physicsMaterials.length; index++) {
  23506. mat = this._physicsMaterials[index];
  23507. if (mat.friction === friction && mat.restitution === restitution) {
  23508. return mat;
  23509. }
  23510. }
  23511. var currentMat = new CANNON.Material();
  23512. currentMat.friction = friction;
  23513. currentMat.restitution = restitution;
  23514. this._physicsMaterials.push(currentMat);
  23515. for (index = 0; index < this._physicsMaterials.length; index++) {
  23516. mat = this._physicsMaterials[index];
  23517. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23518. contactMaterial.contactEquationStiffness = 1e10;
  23519. contactMaterial.contactEquationRegularizationTime = 10;
  23520. this._world.addContactMaterial(contactMaterial);
  23521. }
  23522. return currentMat;
  23523. };
  23524. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23525. var initialRotation = null;
  23526. if (mesh.rotationQuaternion) {
  23527. initialRotation = mesh.rotationQuaternion.clone();
  23528. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23529. }
  23530. // The delta between the mesh position and the mesh bounding box center
  23531. var bbox = mesh.getBoundingInfo().boundingBox;
  23532. var deltaPosition = mesh.position.subtract(bbox.center);
  23533. var material = this._addMaterial(friction, restitution);
  23534. var body = new CANNON.RigidBody(mass, shape, material);
  23535. if (initialRotation) {
  23536. body.quaternion.x = initialRotation.x;
  23537. body.quaternion.z = initialRotation.y;
  23538. body.quaternion.y = initialRotation.z;
  23539. body.quaternion.w = -initialRotation.w;
  23540. }
  23541. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23542. this._world.add(body);
  23543. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23544. return body;
  23545. };
  23546. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23547. var compoundShape = new CANNON.Compound();
  23548. for (var index = 0; index < parts.length; index++) {
  23549. var mesh = parts[index].mesh;
  23550. var shape = this.registerMesh(mesh, parts[index].impostor);
  23551. if (index == 0) {
  23552. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23553. }
  23554. else {
  23555. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23556. }
  23557. }
  23558. var initialMesh = parts[0].mesh;
  23559. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23560. body.parts = parts;
  23561. return body;
  23562. };
  23563. CannonJSPlugin.prototype._unbindBody = function (body) {
  23564. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23565. var registeredMesh = this._registeredMeshes[index];
  23566. if (registeredMesh.body === body) {
  23567. registeredMesh.body = null;
  23568. registeredMesh.delta = 0;
  23569. }
  23570. }
  23571. };
  23572. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23573. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23574. var registeredMesh = this._registeredMeshes[index];
  23575. if (registeredMesh.mesh === mesh) {
  23576. // Remove body
  23577. if (registeredMesh.body) {
  23578. this._world.remove(registeredMesh.body);
  23579. this._unbindBody(registeredMesh.body);
  23580. }
  23581. this._registeredMeshes.splice(index, 1);
  23582. return;
  23583. }
  23584. }
  23585. };
  23586. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23587. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23588. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23589. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23590. var registeredMesh = this._registeredMeshes[index];
  23591. if (registeredMesh.mesh === mesh) {
  23592. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23593. return;
  23594. }
  23595. }
  23596. };
  23597. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23598. var body1 = null, body2 = null;
  23599. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23600. var registeredMesh = this._registeredMeshes[index];
  23601. if (registeredMesh.mesh === mesh1) {
  23602. body1 = registeredMesh.body;
  23603. }
  23604. else if (registeredMesh.mesh === mesh2) {
  23605. body2 = registeredMesh.body;
  23606. }
  23607. }
  23608. if (!body1 || !body2) {
  23609. return false;
  23610. }
  23611. 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));
  23612. this._world.addConstraint(constraint);
  23613. return true;
  23614. };
  23615. CannonJSPlugin.prototype.dispose = function () {
  23616. while (this._registeredMeshes.length) {
  23617. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23618. }
  23619. };
  23620. CannonJSPlugin.prototype.isSupported = function () {
  23621. return window.CANNON !== undefined;
  23622. };
  23623. return CannonJSPlugin;
  23624. })();
  23625. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23626. })(BABYLON || (BABYLON = {}));
  23627. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23628. var BABYLON;
  23629. (function (BABYLON) {
  23630. var Condition = (function () {
  23631. function Condition(actionManager) {
  23632. this._actionManager = actionManager;
  23633. }
  23634. Condition.prototype.isValid = function () {
  23635. return true;
  23636. };
  23637. Condition.prototype._getProperty = function (propertyPath) {
  23638. return this._actionManager._getProperty(propertyPath);
  23639. };
  23640. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23641. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23642. };
  23643. return Condition;
  23644. })();
  23645. BABYLON.Condition = Condition;
  23646. var ValueCondition = (function (_super) {
  23647. __extends(ValueCondition, _super);
  23648. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23649. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23650. _super.call(this, actionManager);
  23651. this.propertyPath = propertyPath;
  23652. this.value = value;
  23653. this.operator = operator;
  23654. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23655. this._property = this._getProperty(this.propertyPath);
  23656. }
  23657. Object.defineProperty(ValueCondition, "IsEqual", {
  23658. get: function () {
  23659. return ValueCondition._IsEqual;
  23660. },
  23661. enumerable: true,
  23662. configurable: true
  23663. });
  23664. Object.defineProperty(ValueCondition, "IsDifferent", {
  23665. get: function () {
  23666. return ValueCondition._IsDifferent;
  23667. },
  23668. enumerable: true,
  23669. configurable: true
  23670. });
  23671. Object.defineProperty(ValueCondition, "IsGreater", {
  23672. get: function () {
  23673. return ValueCondition._IsGreater;
  23674. },
  23675. enumerable: true,
  23676. configurable: true
  23677. });
  23678. Object.defineProperty(ValueCondition, "IsLesser", {
  23679. get: function () {
  23680. return ValueCondition._IsLesser;
  23681. },
  23682. enumerable: true,
  23683. configurable: true
  23684. });
  23685. // Methods
  23686. ValueCondition.prototype.isValid = function () {
  23687. switch (this.operator) {
  23688. case ValueCondition.IsGreater:
  23689. return this._target[this._property] > this.value;
  23690. case ValueCondition.IsLesser:
  23691. return this._target[this._property] < this.value;
  23692. case ValueCondition.IsEqual:
  23693. case ValueCondition.IsDifferent:
  23694. var check;
  23695. if (this.value.equals) {
  23696. check = this.value.equals(this._target[this._property]);
  23697. }
  23698. else {
  23699. check = this.value === this._target[this._property];
  23700. }
  23701. return this.operator === ValueCondition.IsEqual ? check : !check;
  23702. }
  23703. return false;
  23704. };
  23705. // Statics
  23706. ValueCondition._IsEqual = 0;
  23707. ValueCondition._IsDifferent = 1;
  23708. ValueCondition._IsGreater = 2;
  23709. ValueCondition._IsLesser = 3;
  23710. return ValueCondition;
  23711. })(Condition);
  23712. BABYLON.ValueCondition = ValueCondition;
  23713. var PredicateCondition = (function (_super) {
  23714. __extends(PredicateCondition, _super);
  23715. function PredicateCondition(actionManager, predicate) {
  23716. _super.call(this, actionManager);
  23717. this.predicate = predicate;
  23718. }
  23719. PredicateCondition.prototype.isValid = function () {
  23720. return this.predicate();
  23721. };
  23722. return PredicateCondition;
  23723. })(Condition);
  23724. BABYLON.PredicateCondition = PredicateCondition;
  23725. var StateCondition = (function (_super) {
  23726. __extends(StateCondition, _super);
  23727. function StateCondition(actionManager, target, value) {
  23728. _super.call(this, actionManager);
  23729. this.value = value;
  23730. this._target = target;
  23731. }
  23732. // Methods
  23733. StateCondition.prototype.isValid = function () {
  23734. return this._target.state === this.value;
  23735. };
  23736. return StateCondition;
  23737. })(Condition);
  23738. BABYLON.StateCondition = StateCondition;
  23739. })(BABYLON || (BABYLON = {}));
  23740. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23741. (function (BABYLON) {
  23742. var Action = (function () {
  23743. function Action(triggerOptions, condition) {
  23744. this.triggerOptions = triggerOptions;
  23745. if (triggerOptions.parameter) {
  23746. this.trigger = triggerOptions.trigger;
  23747. this._triggerParameter = triggerOptions.parameter;
  23748. }
  23749. else {
  23750. this.trigger = triggerOptions;
  23751. }
  23752. this._nextActiveAction = this;
  23753. this._condition = condition;
  23754. }
  23755. // Methods
  23756. Action.prototype._prepare = function () {
  23757. };
  23758. Action.prototype.getTriggerParameter = function () {
  23759. return this._triggerParameter;
  23760. };
  23761. Action.prototype._executeCurrent = function (evt) {
  23762. if (this._nextActiveAction._condition) {
  23763. var condition = this._nextActiveAction._condition;
  23764. var currentRenderId = this._actionManager.getScene().getRenderId();
  23765. // We cache the current evaluation for the current frame
  23766. if (condition._evaluationId === currentRenderId) {
  23767. if (!condition._currentResult) {
  23768. return;
  23769. }
  23770. }
  23771. else {
  23772. condition._evaluationId = currentRenderId;
  23773. if (!condition.isValid()) {
  23774. condition._currentResult = false;
  23775. return;
  23776. }
  23777. condition._currentResult = true;
  23778. }
  23779. }
  23780. this._nextActiveAction.execute(evt);
  23781. if (this._nextActiveAction._child) {
  23782. if (!this._nextActiveAction._child._actionManager) {
  23783. this._nextActiveAction._child._actionManager = this._actionManager;
  23784. }
  23785. this._nextActiveAction = this._nextActiveAction._child;
  23786. }
  23787. else {
  23788. this._nextActiveAction = this;
  23789. }
  23790. };
  23791. Action.prototype.execute = function (evt) {
  23792. };
  23793. Action.prototype.then = function (action) {
  23794. this._child = action;
  23795. action._actionManager = this._actionManager;
  23796. action._prepare();
  23797. return action;
  23798. };
  23799. Action.prototype._getProperty = function (propertyPath) {
  23800. return this._actionManager._getProperty(propertyPath);
  23801. };
  23802. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23803. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23804. };
  23805. return Action;
  23806. })();
  23807. BABYLON.Action = Action;
  23808. })(BABYLON || (BABYLON = {}));
  23809. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23810. (function (BABYLON) {
  23811. /**
  23812. * ActionEvent is the event beint sent when an action is triggered.
  23813. */
  23814. var ActionEvent = (function () {
  23815. /**
  23816. * @constructor
  23817. * @param source The mesh that triggered the action.
  23818. * @param pointerX the X mouse cursor position at the time of the event
  23819. * @param pointerY the Y mouse cursor position at the time of the event
  23820. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23821. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23822. */
  23823. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23824. this.source = source;
  23825. this.pointerX = pointerX;
  23826. this.pointerY = pointerY;
  23827. this.meshUnderPointer = meshUnderPointer;
  23828. this.sourceEvent = sourceEvent;
  23829. }
  23830. /**
  23831. * Helper function to auto-create an ActionEvent from a source mesh.
  23832. * @param source the source mesh that triggered the event
  23833. * @param evt {Event} The original (browser) event
  23834. */
  23835. ActionEvent.CreateNew = function (source, evt) {
  23836. var scene = source.getScene();
  23837. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23838. };
  23839. /**
  23840. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23841. * @param scene the scene where the event occurred
  23842. * @param evt {Event} The original (browser) event
  23843. */
  23844. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23845. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23846. };
  23847. return ActionEvent;
  23848. })();
  23849. BABYLON.ActionEvent = ActionEvent;
  23850. /**
  23851. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23852. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23853. */
  23854. var ActionManager = (function () {
  23855. function ActionManager(scene) {
  23856. // Members
  23857. this.actions = new Array();
  23858. this._scene = scene;
  23859. scene._actionManagers.push(this);
  23860. }
  23861. Object.defineProperty(ActionManager, "NothingTrigger", {
  23862. get: function () {
  23863. return ActionManager._NothingTrigger;
  23864. },
  23865. enumerable: true,
  23866. configurable: true
  23867. });
  23868. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23869. get: function () {
  23870. return ActionManager._OnPickTrigger;
  23871. },
  23872. enumerable: true,
  23873. configurable: true
  23874. });
  23875. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23876. get: function () {
  23877. return ActionManager._OnLeftPickTrigger;
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23883. get: function () {
  23884. return ActionManager._OnRightPickTrigger;
  23885. },
  23886. enumerable: true,
  23887. configurable: true
  23888. });
  23889. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23890. get: function () {
  23891. return ActionManager._OnCenterPickTrigger;
  23892. },
  23893. enumerable: true,
  23894. configurable: true
  23895. });
  23896. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23897. get: function () {
  23898. return ActionManager._OnPointerOverTrigger;
  23899. },
  23900. enumerable: true,
  23901. configurable: true
  23902. });
  23903. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23904. get: function () {
  23905. return ActionManager._OnPointerOutTrigger;
  23906. },
  23907. enumerable: true,
  23908. configurable: true
  23909. });
  23910. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23911. get: function () {
  23912. return ActionManager._OnEveryFrameTrigger;
  23913. },
  23914. enumerable: true,
  23915. configurable: true
  23916. });
  23917. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23918. get: function () {
  23919. return ActionManager._OnIntersectionEnterTrigger;
  23920. },
  23921. enumerable: true,
  23922. configurable: true
  23923. });
  23924. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23925. get: function () {
  23926. return ActionManager._OnIntersectionExitTrigger;
  23927. },
  23928. enumerable: true,
  23929. configurable: true
  23930. });
  23931. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23932. get: function () {
  23933. return ActionManager._OnKeyDownTrigger;
  23934. },
  23935. enumerable: true,
  23936. configurable: true
  23937. });
  23938. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23939. get: function () {
  23940. return ActionManager._OnKeyUpTrigger;
  23941. },
  23942. enumerable: true,
  23943. configurable: true
  23944. });
  23945. // Methods
  23946. ActionManager.prototype.dispose = function () {
  23947. var index = this._scene._actionManagers.indexOf(this);
  23948. if (index > -1) {
  23949. this._scene._actionManagers.splice(index, 1);
  23950. }
  23951. };
  23952. ActionManager.prototype.getScene = function () {
  23953. return this._scene;
  23954. };
  23955. /**
  23956. * Does this action manager handles actions of any of the given triggers
  23957. * @param {number[]} triggers - the triggers to be tested
  23958. * @return {boolean} whether one (or more) of the triggers is handeled
  23959. */
  23960. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23961. for (var index = 0; index < this.actions.length; index++) {
  23962. var action = this.actions[index];
  23963. if (triggers.indexOf(action.trigger) > -1) {
  23964. return true;
  23965. }
  23966. }
  23967. return false;
  23968. };
  23969. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23970. /**
  23971. * Does this action manager has pointer triggers
  23972. * @return {boolean} whether or not it has pointer triggers
  23973. */
  23974. get: function () {
  23975. for (var index = 0; index < this.actions.length; index++) {
  23976. var action = this.actions[index];
  23977. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23978. return true;
  23979. }
  23980. }
  23981. return false;
  23982. },
  23983. enumerable: true,
  23984. configurable: true
  23985. });
  23986. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23987. /**
  23988. * Does this action manager has pick triggers
  23989. * @return {boolean} whether or not it has pick triggers
  23990. */
  23991. get: function () {
  23992. for (var index = 0; index < this.actions.length; index++) {
  23993. var action = this.actions[index];
  23994. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23995. return true;
  23996. }
  23997. }
  23998. return false;
  23999. },
  24000. enumerable: true,
  24001. configurable: true
  24002. });
  24003. /**
  24004. * Registers an action to this action manager
  24005. * @param {BABYLON.Action} action - the action to be registered
  24006. * @return {BABYLON.Action} the action amended (prepared) after registration
  24007. */
  24008. ActionManager.prototype.registerAction = function (action) {
  24009. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24010. if (this.getScene().actionManager !== this) {
  24011. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24012. return null;
  24013. }
  24014. }
  24015. this.actions.push(action);
  24016. action._actionManager = this;
  24017. action._prepare();
  24018. return action;
  24019. };
  24020. /**
  24021. * Process a specific trigger
  24022. * @param {number} trigger - the trigger to process
  24023. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24024. */
  24025. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24026. for (var index = 0; index < this.actions.length; index++) {
  24027. var action = this.actions[index];
  24028. if (action.trigger === trigger) {
  24029. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24030. var parameter = action.getTriggerParameter();
  24031. if (parameter) {
  24032. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24033. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24034. if (actualkey !== parameter.toLowerCase()) {
  24035. continue;
  24036. }
  24037. }
  24038. }
  24039. action._executeCurrent(evt);
  24040. }
  24041. }
  24042. };
  24043. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24044. var properties = propertyPath.split(".");
  24045. for (var index = 0; index < properties.length - 1; index++) {
  24046. target = target[properties[index]];
  24047. }
  24048. return target;
  24049. };
  24050. ActionManager.prototype._getProperty = function (propertyPath) {
  24051. var properties = propertyPath.split(".");
  24052. return properties[properties.length - 1];
  24053. };
  24054. // Statics
  24055. ActionManager._NothingTrigger = 0;
  24056. ActionManager._OnPickTrigger = 1;
  24057. ActionManager._OnLeftPickTrigger = 2;
  24058. ActionManager._OnRightPickTrigger = 3;
  24059. ActionManager._OnCenterPickTrigger = 4;
  24060. ActionManager._OnPointerOverTrigger = 5;
  24061. ActionManager._OnPointerOutTrigger = 6;
  24062. ActionManager._OnEveryFrameTrigger = 7;
  24063. ActionManager._OnIntersectionEnterTrigger = 8;
  24064. ActionManager._OnIntersectionExitTrigger = 9;
  24065. ActionManager._OnKeyDownTrigger = 10;
  24066. ActionManager._OnKeyUpTrigger = 11;
  24067. return ActionManager;
  24068. })();
  24069. BABYLON.ActionManager = ActionManager;
  24070. })(BABYLON || (BABYLON = {}));
  24071. //# sourceMappingURL=babylon.actionManager.js.map
  24072. var BABYLON;
  24073. (function (BABYLON) {
  24074. var InterpolateValueAction = (function (_super) {
  24075. __extends(InterpolateValueAction, _super);
  24076. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24077. if (duration === void 0) { duration = 1000; }
  24078. _super.call(this, triggerOptions, condition);
  24079. this.propertyPath = propertyPath;
  24080. this.value = value;
  24081. this.duration = duration;
  24082. this.stopOtherAnimations = stopOtherAnimations;
  24083. this._target = target;
  24084. }
  24085. InterpolateValueAction.prototype._prepare = function () {
  24086. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24087. this._property = this._getProperty(this.propertyPath);
  24088. };
  24089. InterpolateValueAction.prototype.execute = function () {
  24090. var scene = this._actionManager.getScene();
  24091. var keys = [
  24092. {
  24093. frame: 0,
  24094. value: this._target[this._property]
  24095. },
  24096. {
  24097. frame: 100,
  24098. value: this.value
  24099. }
  24100. ];
  24101. var dataType;
  24102. if (typeof this.value === "number") {
  24103. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24104. }
  24105. else if (this.value instanceof BABYLON.Color3) {
  24106. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24107. }
  24108. else if (this.value instanceof BABYLON.Vector3) {
  24109. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24110. }
  24111. else if (this.value instanceof BABYLON.Matrix) {
  24112. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24113. }
  24114. else if (this.value instanceof BABYLON.Quaternion) {
  24115. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24116. }
  24117. else {
  24118. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24119. return;
  24120. }
  24121. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24122. animation.setKeys(keys);
  24123. if (this.stopOtherAnimations) {
  24124. scene.stopAnimation(this._target);
  24125. }
  24126. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24127. };
  24128. return InterpolateValueAction;
  24129. })(BABYLON.Action);
  24130. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24131. })(BABYLON || (BABYLON = {}));
  24132. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24133. var BABYLON;
  24134. (function (BABYLON) {
  24135. var SwitchBooleanAction = (function (_super) {
  24136. __extends(SwitchBooleanAction, _super);
  24137. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24138. _super.call(this, triggerOptions, condition);
  24139. this.propertyPath = propertyPath;
  24140. this._target = target;
  24141. }
  24142. SwitchBooleanAction.prototype._prepare = function () {
  24143. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24144. this._property = this._getProperty(this.propertyPath);
  24145. };
  24146. SwitchBooleanAction.prototype.execute = function () {
  24147. this._target[this._property] = !this._target[this._property];
  24148. };
  24149. return SwitchBooleanAction;
  24150. })(BABYLON.Action);
  24151. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24152. var SetStateAction = (function (_super) {
  24153. __extends(SetStateAction, _super);
  24154. function SetStateAction(triggerOptions, target, value, condition) {
  24155. _super.call(this, triggerOptions, condition);
  24156. this.value = value;
  24157. this._target = target;
  24158. }
  24159. SetStateAction.prototype.execute = function () {
  24160. this._target.state = this.value;
  24161. };
  24162. return SetStateAction;
  24163. })(BABYLON.Action);
  24164. BABYLON.SetStateAction = SetStateAction;
  24165. var SetValueAction = (function (_super) {
  24166. __extends(SetValueAction, _super);
  24167. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24168. _super.call(this, triggerOptions, condition);
  24169. this.propertyPath = propertyPath;
  24170. this.value = value;
  24171. this._target = target;
  24172. }
  24173. SetValueAction.prototype._prepare = function () {
  24174. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24175. this._property = this._getProperty(this.propertyPath);
  24176. };
  24177. SetValueAction.prototype.execute = function () {
  24178. this._target[this._property] = this.value;
  24179. };
  24180. return SetValueAction;
  24181. })(BABYLON.Action);
  24182. BABYLON.SetValueAction = SetValueAction;
  24183. var IncrementValueAction = (function (_super) {
  24184. __extends(IncrementValueAction, _super);
  24185. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24186. _super.call(this, triggerOptions, condition);
  24187. this.propertyPath = propertyPath;
  24188. this.value = value;
  24189. this._target = target;
  24190. }
  24191. IncrementValueAction.prototype._prepare = function () {
  24192. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24193. this._property = this._getProperty(this.propertyPath);
  24194. if (typeof this._target[this._property] !== "number") {
  24195. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24196. }
  24197. };
  24198. IncrementValueAction.prototype.execute = function () {
  24199. this._target[this._property] += this.value;
  24200. };
  24201. return IncrementValueAction;
  24202. })(BABYLON.Action);
  24203. BABYLON.IncrementValueAction = IncrementValueAction;
  24204. var PlayAnimationAction = (function (_super) {
  24205. __extends(PlayAnimationAction, _super);
  24206. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24207. _super.call(this, triggerOptions, condition);
  24208. this.from = from;
  24209. this.to = to;
  24210. this.loop = loop;
  24211. this._target = target;
  24212. }
  24213. PlayAnimationAction.prototype._prepare = function () {
  24214. };
  24215. PlayAnimationAction.prototype.execute = function () {
  24216. var scene = this._actionManager.getScene();
  24217. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24218. };
  24219. return PlayAnimationAction;
  24220. })(BABYLON.Action);
  24221. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24222. var StopAnimationAction = (function (_super) {
  24223. __extends(StopAnimationAction, _super);
  24224. function StopAnimationAction(triggerOptions, target, condition) {
  24225. _super.call(this, triggerOptions, condition);
  24226. this._target = target;
  24227. }
  24228. StopAnimationAction.prototype._prepare = function () {
  24229. };
  24230. StopAnimationAction.prototype.execute = function () {
  24231. var scene = this._actionManager.getScene();
  24232. scene.stopAnimation(this._target);
  24233. };
  24234. return StopAnimationAction;
  24235. })(BABYLON.Action);
  24236. BABYLON.StopAnimationAction = StopAnimationAction;
  24237. var DoNothingAction = (function (_super) {
  24238. __extends(DoNothingAction, _super);
  24239. function DoNothingAction(triggerOptions, condition) {
  24240. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24241. _super.call(this, triggerOptions, condition);
  24242. }
  24243. DoNothingAction.prototype.execute = function () {
  24244. };
  24245. return DoNothingAction;
  24246. })(BABYLON.Action);
  24247. BABYLON.DoNothingAction = DoNothingAction;
  24248. var CombineAction = (function (_super) {
  24249. __extends(CombineAction, _super);
  24250. function CombineAction(triggerOptions, children, condition) {
  24251. _super.call(this, triggerOptions, condition);
  24252. this.children = children;
  24253. }
  24254. CombineAction.prototype._prepare = function () {
  24255. for (var index = 0; index < this.children.length; index++) {
  24256. this.children[index]._actionManager = this._actionManager;
  24257. this.children[index]._prepare();
  24258. }
  24259. };
  24260. CombineAction.prototype.execute = function (evt) {
  24261. for (var index = 0; index < this.children.length; index++) {
  24262. this.children[index].execute(evt);
  24263. }
  24264. };
  24265. return CombineAction;
  24266. })(BABYLON.Action);
  24267. BABYLON.CombineAction = CombineAction;
  24268. var ExecuteCodeAction = (function (_super) {
  24269. __extends(ExecuteCodeAction, _super);
  24270. function ExecuteCodeAction(triggerOptions, func, condition) {
  24271. _super.call(this, triggerOptions, condition);
  24272. this.func = func;
  24273. }
  24274. ExecuteCodeAction.prototype.execute = function (evt) {
  24275. this.func(evt);
  24276. };
  24277. return ExecuteCodeAction;
  24278. })(BABYLON.Action);
  24279. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24280. var SetParentAction = (function (_super) {
  24281. __extends(SetParentAction, _super);
  24282. function SetParentAction(triggerOptions, target, parent, condition) {
  24283. _super.call(this, triggerOptions, condition);
  24284. this._target = target;
  24285. this._parent = parent;
  24286. }
  24287. SetParentAction.prototype._prepare = function () {
  24288. };
  24289. SetParentAction.prototype.execute = function () {
  24290. if (this._target.parent === this._parent) {
  24291. return;
  24292. }
  24293. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24294. invertParentWorldMatrix.invert();
  24295. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24296. this._target.parent = this._parent;
  24297. };
  24298. return SetParentAction;
  24299. })(BABYLON.Action);
  24300. BABYLON.SetParentAction = SetParentAction;
  24301. var PlaySoundAction = (function (_super) {
  24302. __extends(PlaySoundAction, _super);
  24303. function PlaySoundAction(triggerOptions, sound, condition) {
  24304. _super.call(this, triggerOptions, condition);
  24305. this._sound = sound;
  24306. }
  24307. PlaySoundAction.prototype._prepare = function () {
  24308. };
  24309. PlaySoundAction.prototype.execute = function () {
  24310. if (this._sound !== undefined)
  24311. this._sound.play();
  24312. };
  24313. return PlaySoundAction;
  24314. })(BABYLON.Action);
  24315. BABYLON.PlaySoundAction = PlaySoundAction;
  24316. var StopSoundAction = (function (_super) {
  24317. __extends(StopSoundAction, _super);
  24318. function StopSoundAction(triggerOptions, sound, condition) {
  24319. _super.call(this, triggerOptions, condition);
  24320. this._sound = sound;
  24321. }
  24322. StopSoundAction.prototype._prepare = function () {
  24323. };
  24324. StopSoundAction.prototype.execute = function () {
  24325. if (this._sound !== undefined)
  24326. this._sound.stop();
  24327. };
  24328. return StopSoundAction;
  24329. })(BABYLON.Action);
  24330. BABYLON.StopSoundAction = StopSoundAction;
  24331. })(BABYLON || (BABYLON = {}));
  24332. //# sourceMappingURL=babylon.directActions.js.map
  24333. var BABYLON;
  24334. (function (BABYLON) {
  24335. var Geometry = (function () {
  24336. function Geometry(id, scene, vertexData, updatable, mesh) {
  24337. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24338. this._totalVertices = 0;
  24339. this._indices = [];
  24340. this.id = id;
  24341. this._engine = scene.getEngine();
  24342. this._meshes = [];
  24343. this._scene = scene;
  24344. // vertexData
  24345. if (vertexData) {
  24346. this.setAllVerticesData(vertexData, updatable);
  24347. }
  24348. else {
  24349. this._totalVertices = 0;
  24350. this._indices = [];
  24351. }
  24352. // applyToMesh
  24353. if (mesh) {
  24354. this.applyToMesh(mesh);
  24355. mesh.computeWorldMatrix(true);
  24356. }
  24357. }
  24358. Geometry.prototype.getScene = function () {
  24359. return this._scene;
  24360. };
  24361. Geometry.prototype.getEngine = function () {
  24362. return this._engine;
  24363. };
  24364. Geometry.prototype.isReady = function () {
  24365. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24366. };
  24367. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24368. vertexData.applyToGeometry(this, updatable);
  24369. };
  24370. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24371. this._vertexBuffers = this._vertexBuffers || {};
  24372. if (this._vertexBuffers[kind]) {
  24373. this._vertexBuffers[kind].dispose();
  24374. }
  24375. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24376. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24377. stride = this._vertexBuffers[kind].getStrideSize();
  24378. this._totalVertices = data.length / stride;
  24379. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24380. var meshes = this._meshes;
  24381. var numOfMeshes = meshes.length;
  24382. for (var index = 0; index < numOfMeshes; index++) {
  24383. var mesh = meshes[index];
  24384. mesh._resetPointsArrayCache();
  24385. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24386. mesh._createGlobalSubMesh();
  24387. mesh.computeWorldMatrix(true);
  24388. }
  24389. }
  24390. };
  24391. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24392. var vertexBuffer = this.getVertexBuffer(kind);
  24393. if (!vertexBuffer) {
  24394. return;
  24395. }
  24396. vertexBuffer.updateDirectly(data, offset);
  24397. };
  24398. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24399. var vertexBuffer = this.getVertexBuffer(kind);
  24400. if (!vertexBuffer) {
  24401. return;
  24402. }
  24403. vertexBuffer.update(data);
  24404. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24405. var extend;
  24406. var stride = vertexBuffer.getStrideSize();
  24407. this._totalVertices = data.length / stride;
  24408. if (updateExtends) {
  24409. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24410. }
  24411. var meshes = this._meshes;
  24412. var numOfMeshes = meshes.length;
  24413. for (var index = 0; index < numOfMeshes; index++) {
  24414. var mesh = meshes[index];
  24415. mesh._resetPointsArrayCache();
  24416. if (updateExtends) {
  24417. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24418. }
  24419. }
  24420. }
  24421. };
  24422. Geometry.prototype.getTotalVertices = function () {
  24423. if (!this.isReady()) {
  24424. return 0;
  24425. }
  24426. return this._totalVertices;
  24427. };
  24428. Geometry.prototype.getVerticesData = function (kind) {
  24429. var vertexBuffer = this.getVertexBuffer(kind);
  24430. if (!vertexBuffer) {
  24431. return null;
  24432. }
  24433. return vertexBuffer.getData();
  24434. };
  24435. Geometry.prototype.getVertexBuffer = function (kind) {
  24436. if (!this.isReady()) {
  24437. return null;
  24438. }
  24439. return this._vertexBuffers[kind];
  24440. };
  24441. Geometry.prototype.getVertexBuffers = function () {
  24442. if (!this.isReady()) {
  24443. return null;
  24444. }
  24445. return this._vertexBuffers;
  24446. };
  24447. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24448. if (!this._vertexBuffers) {
  24449. if (this._delayInfo) {
  24450. return this._delayInfo.indexOf(kind) !== -1;
  24451. }
  24452. return false;
  24453. }
  24454. return this._vertexBuffers[kind] !== undefined;
  24455. };
  24456. Geometry.prototype.getVerticesDataKinds = function () {
  24457. var result = [];
  24458. if (!this._vertexBuffers && this._delayInfo) {
  24459. for (var kind in this._delayInfo) {
  24460. result.push(kind);
  24461. }
  24462. }
  24463. else {
  24464. for (kind in this._vertexBuffers) {
  24465. result.push(kind);
  24466. }
  24467. }
  24468. return result;
  24469. };
  24470. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24471. if (this._indexBuffer) {
  24472. this._engine._releaseBuffer(this._indexBuffer);
  24473. }
  24474. this._indices = indices;
  24475. if (this._meshes.length !== 0 && this._indices) {
  24476. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24477. }
  24478. if (totalVertices !== undefined) {
  24479. this._totalVertices = totalVertices;
  24480. }
  24481. var meshes = this._meshes;
  24482. var numOfMeshes = meshes.length;
  24483. for (var index = 0; index < numOfMeshes; index++) {
  24484. meshes[index]._createGlobalSubMesh();
  24485. }
  24486. };
  24487. Geometry.prototype.getTotalIndices = function () {
  24488. if (!this.isReady()) {
  24489. return 0;
  24490. }
  24491. return this._indices.length;
  24492. };
  24493. Geometry.prototype.getIndices = function () {
  24494. if (!this.isReady()) {
  24495. return null;
  24496. }
  24497. return this._indices;
  24498. };
  24499. Geometry.prototype.getIndexBuffer = function () {
  24500. if (!this.isReady()) {
  24501. return null;
  24502. }
  24503. return this._indexBuffer;
  24504. };
  24505. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24506. var meshes = this._meshes;
  24507. var index = meshes.indexOf(mesh);
  24508. if (index === -1) {
  24509. return;
  24510. }
  24511. for (var kind in this._vertexBuffers) {
  24512. this._vertexBuffers[kind].dispose();
  24513. }
  24514. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24515. this._indexBuffer = null;
  24516. }
  24517. meshes.splice(index, 1);
  24518. mesh._geometry = null;
  24519. if (meshes.length === 0 && shouldDispose) {
  24520. this.dispose();
  24521. }
  24522. };
  24523. Geometry.prototype.applyToMesh = function (mesh) {
  24524. if (mesh._geometry === this) {
  24525. return;
  24526. }
  24527. var previousGeometry = mesh._geometry;
  24528. if (previousGeometry) {
  24529. previousGeometry.releaseForMesh(mesh);
  24530. }
  24531. var meshes = this._meshes;
  24532. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24533. mesh._geometry = this;
  24534. this._scene.pushGeometry(this);
  24535. meshes.push(mesh);
  24536. if (this.isReady()) {
  24537. this._applyToMesh(mesh);
  24538. }
  24539. else {
  24540. mesh._boundingInfo = this._boundingInfo;
  24541. }
  24542. };
  24543. Geometry.prototype._applyToMesh = function (mesh) {
  24544. var numOfMeshes = this._meshes.length;
  24545. for (var kind in this._vertexBuffers) {
  24546. if (numOfMeshes === 1) {
  24547. this._vertexBuffers[kind].create();
  24548. }
  24549. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24550. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24551. mesh._resetPointsArrayCache();
  24552. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24553. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24554. mesh._createGlobalSubMesh();
  24555. //bounding info was just created again, world matrix should be applied again.
  24556. mesh._updateBoundingInfo();
  24557. }
  24558. }
  24559. // indexBuffer
  24560. if (numOfMeshes === 1 && this._indices) {
  24561. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24562. }
  24563. if (this._indexBuffer) {
  24564. this._indexBuffer.references = numOfMeshes;
  24565. }
  24566. };
  24567. Geometry.prototype.load = function (scene, onLoaded) {
  24568. var _this = this;
  24569. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24570. return;
  24571. }
  24572. if (this.isReady()) {
  24573. if (onLoaded) {
  24574. onLoaded();
  24575. }
  24576. return;
  24577. }
  24578. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24579. scene._addPendingData(this);
  24580. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24581. _this._delayLoadingFunction(JSON.parse(data), _this);
  24582. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24583. _this._delayInfo = [];
  24584. scene._removePendingData(_this);
  24585. var meshes = _this._meshes;
  24586. var numOfMeshes = meshes.length;
  24587. for (var index = 0; index < numOfMeshes; index++) {
  24588. _this._applyToMesh(meshes[index]);
  24589. }
  24590. if (onLoaded) {
  24591. onLoaded();
  24592. }
  24593. }, function () {
  24594. }, scene.database);
  24595. };
  24596. Geometry.prototype.dispose = function () {
  24597. var meshes = this._meshes;
  24598. var numOfMeshes = meshes.length;
  24599. var index;
  24600. for (index = 0; index < numOfMeshes; index++) {
  24601. this.releaseForMesh(meshes[index]);
  24602. }
  24603. this._meshes = [];
  24604. for (var kind in this._vertexBuffers) {
  24605. this._vertexBuffers[kind].dispose();
  24606. }
  24607. this._vertexBuffers = [];
  24608. this._totalVertices = 0;
  24609. if (this._indexBuffer) {
  24610. this._engine._releaseBuffer(this._indexBuffer);
  24611. }
  24612. this._indexBuffer = null;
  24613. this._indices = [];
  24614. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24615. this.delayLoadingFile = null;
  24616. this._delayLoadingFunction = null;
  24617. this._delayInfo = [];
  24618. this._boundingInfo = null; // todo: .dispose()
  24619. var geometries = this._scene.getGeometries();
  24620. index = geometries.indexOf(this);
  24621. if (index > -1) {
  24622. geometries.splice(index, 1);
  24623. }
  24624. };
  24625. Geometry.prototype.copy = function (id) {
  24626. var vertexData = new BABYLON.VertexData();
  24627. vertexData.indices = [];
  24628. var indices = this.getIndices();
  24629. for (var index = 0; index < indices.length; index++) {
  24630. vertexData.indices.push(indices[index]);
  24631. }
  24632. var updatable = false;
  24633. var stopChecking = false;
  24634. for (var kind in this._vertexBuffers) {
  24635. vertexData.set(this.getVerticesData(kind), kind);
  24636. if (!stopChecking) {
  24637. updatable = this.getVertexBuffer(kind).isUpdatable();
  24638. stopChecking = !updatable;
  24639. }
  24640. }
  24641. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24642. geometry.delayLoadState = this.delayLoadState;
  24643. geometry.delayLoadingFile = this.delayLoadingFile;
  24644. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24645. for (kind in this._delayInfo) {
  24646. geometry._delayInfo = geometry._delayInfo || [];
  24647. geometry._delayInfo.push(kind);
  24648. }
  24649. // Bounding info
  24650. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24651. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24652. return geometry;
  24653. };
  24654. // Statics
  24655. Geometry.ExtractFromMesh = function (mesh, id) {
  24656. var geometry = mesh._geometry;
  24657. if (!geometry) {
  24658. return null;
  24659. }
  24660. return geometry.copy(id);
  24661. };
  24662. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24663. // be aware Math.random() could cause collisions
  24664. Geometry.RandomId = function () {
  24665. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24666. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24667. return v.toString(16);
  24668. });
  24669. };
  24670. return Geometry;
  24671. })();
  24672. BABYLON.Geometry = Geometry;
  24673. /////// Primitives //////////////////////////////////////////////
  24674. var Geometry;
  24675. (function (Geometry) {
  24676. var Primitives;
  24677. (function (Primitives) {
  24678. /// Abstract class
  24679. var _Primitive = (function (_super) {
  24680. __extends(_Primitive, _super);
  24681. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24682. this._beingRegenerated = true;
  24683. this._canBeRegenerated = canBeRegenerated;
  24684. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24685. this._beingRegenerated = false;
  24686. }
  24687. _Primitive.prototype.canBeRegenerated = function () {
  24688. return this._canBeRegenerated;
  24689. };
  24690. _Primitive.prototype.regenerate = function () {
  24691. if (!this._canBeRegenerated) {
  24692. return;
  24693. }
  24694. this._beingRegenerated = true;
  24695. this.setAllVerticesData(this._regenerateVertexData(), false);
  24696. this._beingRegenerated = false;
  24697. };
  24698. _Primitive.prototype.asNewGeometry = function (id) {
  24699. return _super.prototype.copy.call(this, id);
  24700. };
  24701. // overrides
  24702. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24703. if (!this._beingRegenerated) {
  24704. return;
  24705. }
  24706. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24707. };
  24708. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24709. if (!this._beingRegenerated) {
  24710. return;
  24711. }
  24712. _super.prototype.setVerticesData.call(this, kind, data, false);
  24713. };
  24714. // to override
  24715. // protected
  24716. _Primitive.prototype._regenerateVertexData = function () {
  24717. throw new Error("Abstract method");
  24718. };
  24719. _Primitive.prototype.copy = function (id) {
  24720. throw new Error("Must be overriden in sub-classes.");
  24721. };
  24722. return _Primitive;
  24723. })(Geometry);
  24724. Primitives._Primitive = _Primitive;
  24725. var Ribbon = (function (_super) {
  24726. __extends(Ribbon, _super);
  24727. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  24728. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24729. this.pathArray = pathArray;
  24730. this.closeArray = closeArray;
  24731. this.closePath = closePath;
  24732. this.offset = offset;
  24733. this.side = side;
  24734. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24735. }
  24736. Ribbon.prototype._regenerateVertexData = function () {
  24737. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  24738. };
  24739. Ribbon.prototype.copy = function (id) {
  24740. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  24741. };
  24742. return Ribbon;
  24743. })(_Primitive);
  24744. Primitives.Ribbon = Ribbon;
  24745. var Box = (function (_super) {
  24746. __extends(Box, _super);
  24747. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  24748. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24749. this.size = size;
  24750. this.side = side;
  24751. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24752. }
  24753. Box.prototype._regenerateVertexData = function () {
  24754. return BABYLON.VertexData.CreateBox(this.size, this.side);
  24755. };
  24756. Box.prototype.copy = function (id) {
  24757. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24758. };
  24759. return Box;
  24760. })(_Primitive);
  24761. Primitives.Box = Box;
  24762. var Sphere = (function (_super) {
  24763. __extends(Sphere, _super);
  24764. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  24765. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24766. this.segments = segments;
  24767. this.diameter = diameter;
  24768. this.side = side;
  24769. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24770. }
  24771. Sphere.prototype._regenerateVertexData = function () {
  24772. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  24773. };
  24774. Sphere.prototype.copy = function (id) {
  24775. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  24776. };
  24777. return Sphere;
  24778. })(_Primitive);
  24779. Primitives.Sphere = Sphere;
  24780. var Cylinder = (function (_super) {
  24781. __extends(Cylinder, _super);
  24782. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  24783. if (subdivisions === void 0) { subdivisions = 1; }
  24784. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24785. this.height = height;
  24786. this.diameterTop = diameterTop;
  24787. this.diameterBottom = diameterBottom;
  24788. this.tessellation = tessellation;
  24789. this.subdivisions = subdivisions;
  24790. this.side = side;
  24791. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24792. }
  24793. Cylinder.prototype._regenerateVertexData = function () {
  24794. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  24795. };
  24796. Cylinder.prototype.copy = function (id) {
  24797. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  24798. };
  24799. return Cylinder;
  24800. })(_Primitive);
  24801. Primitives.Cylinder = Cylinder;
  24802. var Torus = (function (_super) {
  24803. __extends(Torus, _super);
  24804. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  24805. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24806. this.diameter = diameter;
  24807. this.thickness = thickness;
  24808. this.tessellation = tessellation;
  24809. this.side = side;
  24810. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24811. }
  24812. Torus.prototype._regenerateVertexData = function () {
  24813. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  24814. };
  24815. Torus.prototype.copy = function (id) {
  24816. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  24817. };
  24818. return Torus;
  24819. })(_Primitive);
  24820. Primitives.Torus = Torus;
  24821. var Ground = (function (_super) {
  24822. __extends(Ground, _super);
  24823. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24824. this.width = width;
  24825. this.height = height;
  24826. this.subdivisions = subdivisions;
  24827. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24828. }
  24829. Ground.prototype._regenerateVertexData = function () {
  24830. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24831. };
  24832. Ground.prototype.copy = function (id) {
  24833. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24834. };
  24835. return Ground;
  24836. })(_Primitive);
  24837. Primitives.Ground = Ground;
  24838. var TiledGround = (function (_super) {
  24839. __extends(TiledGround, _super);
  24840. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24841. this.xmin = xmin;
  24842. this.zmin = zmin;
  24843. this.xmax = xmax;
  24844. this.zmax = zmax;
  24845. this.subdivisions = subdivisions;
  24846. this.precision = precision;
  24847. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24848. }
  24849. TiledGround.prototype._regenerateVertexData = function () {
  24850. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24851. };
  24852. TiledGround.prototype.copy = function (id) {
  24853. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24854. };
  24855. return TiledGround;
  24856. })(_Primitive);
  24857. Primitives.TiledGround = TiledGround;
  24858. var Plane = (function (_super) {
  24859. __extends(Plane, _super);
  24860. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  24861. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24862. this.size = size;
  24863. this.side = side;
  24864. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24865. }
  24866. Plane.prototype._regenerateVertexData = function () {
  24867. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  24868. };
  24869. Plane.prototype.copy = function (id) {
  24870. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24871. };
  24872. return Plane;
  24873. })(_Primitive);
  24874. Primitives.Plane = Plane;
  24875. var TorusKnot = (function (_super) {
  24876. __extends(TorusKnot, _super);
  24877. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  24878. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24879. this.radius = radius;
  24880. this.tube = tube;
  24881. this.radialSegments = radialSegments;
  24882. this.tubularSegments = tubularSegments;
  24883. this.p = p;
  24884. this.q = q;
  24885. this.side = side;
  24886. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24887. }
  24888. TorusKnot.prototype._regenerateVertexData = function () {
  24889. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  24890. };
  24891. TorusKnot.prototype.copy = function (id) {
  24892. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  24893. };
  24894. return TorusKnot;
  24895. })(_Primitive);
  24896. Primitives.TorusKnot = TorusKnot;
  24897. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  24898. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  24899. })(BABYLON || (BABYLON = {}));
  24900. //# sourceMappingURL=babylon.geometry.js.map
  24901. var BABYLON;
  24902. (function (BABYLON) {
  24903. var Gamepads = (function () {
  24904. function Gamepads(ongamedpadconnected) {
  24905. var _this = this;
  24906. this.babylonGamepads = [];
  24907. this.oneGamepadConnected = false;
  24908. this.isMonitoring = false;
  24909. this.gamepadEventSupported = 'GamepadEvent' in window;
  24910. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  24911. 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=";
  24912. this._callbackGamepadConnected = ongamedpadconnected;
  24913. if (this.gamepadSupportAvailable) {
  24914. // Checking if the gamepad connected event is supported (like in Firefox)
  24915. if (this.gamepadEventSupported) {
  24916. window.addEventListener('gamepadconnected', function (evt) {
  24917. _this._onGamepadConnected(evt);
  24918. }, false);
  24919. window.addEventListener('gamepaddisconnected', function (evt) {
  24920. _this._onGamepadDisconnected(evt);
  24921. }, false);
  24922. }
  24923. else {
  24924. this._startMonitoringGamepads();
  24925. }
  24926. if (!this.oneGamepadConnected) {
  24927. this._insertGamepadDOMInstructions();
  24928. }
  24929. }
  24930. else {
  24931. this._insertGamepadDOMNotSupported();
  24932. }
  24933. }
  24934. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24935. Gamepads.gamepadDOMInfo = document.createElement("div");
  24936. var buttonAImage = document.createElement("img");
  24937. buttonAImage.src = this.buttonADataURL;
  24938. var spanMessage = document.createElement("span");
  24939. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24940. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24941. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24942. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24943. Gamepads.gamepadDOMInfo.style.width = "100%";
  24944. Gamepads.gamepadDOMInfo.style.height = "48px";
  24945. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24946. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24947. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24948. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24949. buttonAImage.style.position = "relative";
  24950. buttonAImage.style.bottom = "8px";
  24951. spanMessage.style.position = "relative";
  24952. spanMessage.style.fontSize = "32px";
  24953. spanMessage.style.bottom = "32px";
  24954. spanMessage.style.color = "green";
  24955. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24956. };
  24957. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24958. Gamepads.gamepadDOMInfo = document.createElement("div");
  24959. var spanMessage = document.createElement("span");
  24960. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24961. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24962. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24963. Gamepads.gamepadDOMInfo.style.width = "100%";
  24964. Gamepads.gamepadDOMInfo.style.height = "40px";
  24965. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24966. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24967. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24968. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24969. spanMessage.style.position = "relative";
  24970. spanMessage.style.fontSize = "32px";
  24971. spanMessage.style.color = "red";
  24972. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24973. };
  24974. Gamepads.prototype.dispose = function () {
  24975. if (Gamepads.gamepadDOMInfo) {
  24976. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24977. }
  24978. };
  24979. Gamepads.prototype._onGamepadConnected = function (evt) {
  24980. var newGamepad = this._addNewGamepad(evt.gamepad);
  24981. if (this._callbackGamepadConnected)
  24982. this._callbackGamepadConnected(newGamepad);
  24983. this._startMonitoringGamepads();
  24984. };
  24985. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24986. if (!this.oneGamepadConnected) {
  24987. this.oneGamepadConnected = true;
  24988. if (Gamepads.gamepadDOMInfo) {
  24989. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24990. Gamepads.gamepadDOMInfo = null;
  24991. }
  24992. }
  24993. var newGamepad;
  24994. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24995. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24996. }
  24997. else {
  24998. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24999. }
  25000. this.babylonGamepads.push(newGamepad);
  25001. return newGamepad;
  25002. };
  25003. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25004. for (var i in this.babylonGamepads) {
  25005. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25006. this.babylonGamepads.splice(i, 1);
  25007. break;
  25008. }
  25009. }
  25010. // If no gamepads are left, stop the polling loop.
  25011. if (this.babylonGamepads.length == 0) {
  25012. this._stopMonitoringGamepads();
  25013. }
  25014. };
  25015. Gamepads.prototype._startMonitoringGamepads = function () {
  25016. if (!this.isMonitoring) {
  25017. this.isMonitoring = true;
  25018. this._checkGamepadsStatus();
  25019. }
  25020. };
  25021. Gamepads.prototype._stopMonitoringGamepads = function () {
  25022. this.isMonitoring = false;
  25023. };
  25024. Gamepads.prototype._checkGamepadsStatus = function () {
  25025. var _this = this;
  25026. // updating gamepad objects
  25027. this._updateGamepadObjects();
  25028. for (var i in this.babylonGamepads) {
  25029. this.babylonGamepads[i].update();
  25030. }
  25031. if (this.isMonitoring) {
  25032. if (window.requestAnimationFrame) {
  25033. window.requestAnimationFrame(function () {
  25034. _this._checkGamepadsStatus();
  25035. });
  25036. }
  25037. else if (window.mozRequestAnimationFrame) {
  25038. window.mozRequestAnimationFrame(function () {
  25039. _this._checkGamepadsStatus();
  25040. });
  25041. }
  25042. else if (window.webkitRequestAnimationFrame) {
  25043. window.webkitRequestAnimationFrame(function () {
  25044. _this._checkGamepadsStatus();
  25045. });
  25046. }
  25047. }
  25048. };
  25049. // This function is called only on Chrome, which does not yet support
  25050. // connection/disconnection events, but requires you to monitor
  25051. // an array for changes.
  25052. Gamepads.prototype._updateGamepadObjects = function () {
  25053. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25054. for (var i = 0; i < gamepads.length; i++) {
  25055. if (gamepads[i]) {
  25056. if (!(gamepads[i].index in this.babylonGamepads)) {
  25057. var newGamepad = this._addNewGamepad(gamepads[i]);
  25058. if (this._callbackGamepadConnected) {
  25059. this._callbackGamepadConnected(newGamepad);
  25060. }
  25061. }
  25062. else {
  25063. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25064. }
  25065. }
  25066. }
  25067. };
  25068. return Gamepads;
  25069. })();
  25070. BABYLON.Gamepads = Gamepads;
  25071. var StickValues = (function () {
  25072. function StickValues(x, y) {
  25073. this.x = x;
  25074. this.y = y;
  25075. }
  25076. return StickValues;
  25077. })();
  25078. BABYLON.StickValues = StickValues;
  25079. var Gamepad = (function () {
  25080. function Gamepad(id, index, browserGamepad) {
  25081. this.id = id;
  25082. this.index = index;
  25083. this.browserGamepad = browserGamepad;
  25084. if (this.browserGamepad.axes.length >= 2) {
  25085. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25086. }
  25087. if (this.browserGamepad.axes.length >= 4) {
  25088. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25089. }
  25090. }
  25091. Gamepad.prototype.onleftstickchanged = function (callback) {
  25092. this._onleftstickchanged = callback;
  25093. };
  25094. Gamepad.prototype.onrightstickchanged = function (callback) {
  25095. this._onrightstickchanged = callback;
  25096. };
  25097. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25098. get: function () {
  25099. return this._leftStick;
  25100. },
  25101. set: function (newValues) {
  25102. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25103. this._onleftstickchanged(newValues);
  25104. }
  25105. this._leftStick = newValues;
  25106. },
  25107. enumerable: true,
  25108. configurable: true
  25109. });
  25110. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25111. get: function () {
  25112. return this._rightStick;
  25113. },
  25114. set: function (newValues) {
  25115. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25116. this._onrightstickchanged(newValues);
  25117. }
  25118. this._rightStick = newValues;
  25119. },
  25120. enumerable: true,
  25121. configurable: true
  25122. });
  25123. Gamepad.prototype.update = function () {
  25124. if (this._leftStick) {
  25125. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25126. }
  25127. if (this._rightStick) {
  25128. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25129. }
  25130. };
  25131. return Gamepad;
  25132. })();
  25133. BABYLON.Gamepad = Gamepad;
  25134. var GenericPad = (function (_super) {
  25135. __extends(GenericPad, _super);
  25136. function GenericPad(id, index, gamepad) {
  25137. _super.call(this, id, index, gamepad);
  25138. this.id = id;
  25139. this.index = index;
  25140. this.gamepad = gamepad;
  25141. this._buttons = new Array(gamepad.buttons.length);
  25142. }
  25143. GenericPad.prototype.onbuttondown = function (callback) {
  25144. this._onbuttondown = callback;
  25145. };
  25146. GenericPad.prototype.onbuttonup = function (callback) {
  25147. this._onbuttonup = callback;
  25148. };
  25149. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25150. if (newValue !== currentValue) {
  25151. if (this._onbuttondown && newValue === 1) {
  25152. this._onbuttondown(buttonIndex);
  25153. }
  25154. if (this._onbuttonup && newValue === 0) {
  25155. this._onbuttonup(buttonIndex);
  25156. }
  25157. }
  25158. return newValue;
  25159. };
  25160. GenericPad.prototype.update = function () {
  25161. _super.prototype.update.call(this);
  25162. for (var index = 0; index < this._buttons.length; index++) {
  25163. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25164. }
  25165. };
  25166. return GenericPad;
  25167. })(Gamepad);
  25168. BABYLON.GenericPad = GenericPad;
  25169. (function (Xbox360Button) {
  25170. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25171. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25172. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25173. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25174. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25175. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25176. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25177. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25178. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25179. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25180. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25181. var Xbox360Button = BABYLON.Xbox360Button;
  25182. (function (Xbox360Dpad) {
  25183. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25184. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25185. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25186. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25187. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25188. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25189. var Xbox360Pad = (function (_super) {
  25190. __extends(Xbox360Pad, _super);
  25191. function Xbox360Pad() {
  25192. _super.apply(this, arguments);
  25193. this._leftTrigger = 0;
  25194. this._rightTrigger = 0;
  25195. this._buttonA = 0;
  25196. this._buttonB = 0;
  25197. this._buttonX = 0;
  25198. this._buttonY = 0;
  25199. this._buttonBack = 0;
  25200. this._buttonStart = 0;
  25201. this._buttonLB = 0;
  25202. this._buttonRB = 0;
  25203. this._buttonLeftStick = 0;
  25204. this._buttonRightStick = 0;
  25205. this._dPadUp = 0;
  25206. this._dPadDown = 0;
  25207. this._dPadLeft = 0;
  25208. this._dPadRight = 0;
  25209. }
  25210. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25211. this._onlefttriggerchanged = callback;
  25212. };
  25213. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25214. this._onrighttriggerchanged = callback;
  25215. };
  25216. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25217. get: function () {
  25218. return this._leftTrigger;
  25219. },
  25220. set: function (newValue) {
  25221. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25222. this._onlefttriggerchanged(newValue);
  25223. }
  25224. this._leftTrigger = newValue;
  25225. },
  25226. enumerable: true,
  25227. configurable: true
  25228. });
  25229. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25230. get: function () {
  25231. return this._rightTrigger;
  25232. },
  25233. set: function (newValue) {
  25234. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25235. this._onrighttriggerchanged(newValue);
  25236. }
  25237. this._rightTrigger = newValue;
  25238. },
  25239. enumerable: true,
  25240. configurable: true
  25241. });
  25242. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25243. this._onbuttondown = callback;
  25244. };
  25245. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25246. this._onbuttonup = callback;
  25247. };
  25248. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25249. this._ondpaddown = callback;
  25250. };
  25251. Xbox360Pad.prototype.ondpadup = function (callback) {
  25252. this._ondpadup = callback;
  25253. };
  25254. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25255. if (newValue !== currentValue) {
  25256. if (this._onbuttondown && newValue === 1) {
  25257. this._onbuttondown(buttonType);
  25258. }
  25259. if (this._onbuttonup && newValue === 0) {
  25260. this._onbuttonup(buttonType);
  25261. }
  25262. }
  25263. return newValue;
  25264. };
  25265. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25266. if (newValue !== currentValue) {
  25267. if (this._ondpaddown && newValue === 1) {
  25268. this._ondpaddown(buttonType);
  25269. }
  25270. if (this._ondpadup && newValue === 0) {
  25271. this._ondpadup(buttonType);
  25272. }
  25273. }
  25274. return newValue;
  25275. };
  25276. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25277. get: function () {
  25278. return this._buttonA;
  25279. },
  25280. set: function (value) {
  25281. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25282. },
  25283. enumerable: true,
  25284. configurable: true
  25285. });
  25286. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25287. get: function () {
  25288. return this._buttonB;
  25289. },
  25290. set: function (value) {
  25291. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25292. },
  25293. enumerable: true,
  25294. configurable: true
  25295. });
  25296. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25297. get: function () {
  25298. return this._buttonX;
  25299. },
  25300. set: function (value) {
  25301. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25302. },
  25303. enumerable: true,
  25304. configurable: true
  25305. });
  25306. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25307. get: function () {
  25308. return this._buttonY;
  25309. },
  25310. set: function (value) {
  25311. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25312. },
  25313. enumerable: true,
  25314. configurable: true
  25315. });
  25316. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25317. get: function () {
  25318. return this._buttonStart;
  25319. },
  25320. set: function (value) {
  25321. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25322. },
  25323. enumerable: true,
  25324. configurable: true
  25325. });
  25326. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25327. get: function () {
  25328. return this._buttonBack;
  25329. },
  25330. set: function (value) {
  25331. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25332. },
  25333. enumerable: true,
  25334. configurable: true
  25335. });
  25336. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25337. get: function () {
  25338. return this._buttonLB;
  25339. },
  25340. set: function (value) {
  25341. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25342. },
  25343. enumerable: true,
  25344. configurable: true
  25345. });
  25346. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25347. get: function () {
  25348. return this._buttonRB;
  25349. },
  25350. set: function (value) {
  25351. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25352. },
  25353. enumerable: true,
  25354. configurable: true
  25355. });
  25356. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25357. get: function () {
  25358. return this._buttonLeftStick;
  25359. },
  25360. set: function (value) {
  25361. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25362. },
  25363. enumerable: true,
  25364. configurable: true
  25365. });
  25366. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25367. get: function () {
  25368. return this._buttonRightStick;
  25369. },
  25370. set: function (value) {
  25371. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25372. },
  25373. enumerable: true,
  25374. configurable: true
  25375. });
  25376. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25377. get: function () {
  25378. return this._dPadUp;
  25379. },
  25380. set: function (value) {
  25381. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25382. },
  25383. enumerable: true,
  25384. configurable: true
  25385. });
  25386. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25387. get: function () {
  25388. return this._dPadDown;
  25389. },
  25390. set: function (value) {
  25391. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25392. },
  25393. enumerable: true,
  25394. configurable: true
  25395. });
  25396. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25397. get: function () {
  25398. return this._dPadLeft;
  25399. },
  25400. set: function (value) {
  25401. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25402. },
  25403. enumerable: true,
  25404. configurable: true
  25405. });
  25406. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25407. get: function () {
  25408. return this._dPadRight;
  25409. },
  25410. set: function (value) {
  25411. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25412. },
  25413. enumerable: true,
  25414. configurable: true
  25415. });
  25416. Xbox360Pad.prototype.update = function () {
  25417. _super.prototype.update.call(this);
  25418. this.buttonA = this.browserGamepad.buttons[0].value;
  25419. this.buttonB = this.browserGamepad.buttons[1].value;
  25420. this.buttonX = this.browserGamepad.buttons[2].value;
  25421. this.buttonY = this.browserGamepad.buttons[3].value;
  25422. this.buttonLB = this.browserGamepad.buttons[4].value;
  25423. this.buttonRB = this.browserGamepad.buttons[5].value;
  25424. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25425. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25426. this.buttonBack = this.browserGamepad.buttons[8].value;
  25427. this.buttonStart = this.browserGamepad.buttons[9].value;
  25428. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25429. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25430. this.dPadUp = this.browserGamepad.buttons[12].value;
  25431. this.dPadDown = this.browserGamepad.buttons[13].value;
  25432. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25433. this.dPadRight = this.browserGamepad.buttons[15].value;
  25434. };
  25435. return Xbox360Pad;
  25436. })(Gamepad);
  25437. BABYLON.Xbox360Pad = Xbox360Pad;
  25438. })(BABYLON || (BABYLON = {}));
  25439. //# sourceMappingURL=babylon.gamepads.js.map
  25440. var BABYLON;
  25441. (function (BABYLON) {
  25442. // We're mainly based on the logic defined into the FreeCamera code
  25443. var GamepadCamera = (function (_super) {
  25444. __extends(GamepadCamera, _super);
  25445. function GamepadCamera(name, position, scene) {
  25446. var _this = this;
  25447. _super.call(this, name, position, scene);
  25448. this.angularSensibility = 200;
  25449. this.moveSensibility = 75;
  25450. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25451. _this._onNewGameConnected(gamepad);
  25452. });
  25453. }
  25454. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25455. // Only the first gamepad can control the camera
  25456. if (gamepad.index === 0) {
  25457. this._gamepad = gamepad;
  25458. }
  25459. };
  25460. GamepadCamera.prototype._checkInputs = function () {
  25461. if (!this._gamepad) {
  25462. return;
  25463. }
  25464. var LSValues = this._gamepad.leftStick;
  25465. var normalizedLX = LSValues.x / this.moveSensibility;
  25466. var normalizedLY = LSValues.y / this.moveSensibility;
  25467. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25468. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25469. var RSValues = this._gamepad.rightStick;
  25470. var normalizedRX = RSValues.x / this.angularSensibility;
  25471. var normalizedRY = RSValues.y / this.angularSensibility;
  25472. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25473. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25474. ;
  25475. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25476. var speed = this._computeLocalCameraSpeed() * 50.0;
  25477. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25478. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25479. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25480. };
  25481. GamepadCamera.prototype.dispose = function () {
  25482. this._gamepads.dispose();
  25483. _super.prototype.dispose.call(this);
  25484. };
  25485. return GamepadCamera;
  25486. })(BABYLON.FreeCamera);
  25487. BABYLON.GamepadCamera = GamepadCamera;
  25488. })(BABYLON || (BABYLON = {}));
  25489. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25490. var BABYLON;
  25491. (function (BABYLON) {
  25492. var LinesMesh = (function (_super) {
  25493. __extends(LinesMesh, _super);
  25494. function LinesMesh(name, scene, updatable) {
  25495. if (updatable === void 0) { updatable = false; }
  25496. _super.call(this, name, scene);
  25497. this.color = new BABYLON.Color3(1, 1, 1);
  25498. this.alpha = 1;
  25499. this._indices = new Array();
  25500. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25501. attributes: ["position"],
  25502. uniforms: ["worldViewProjection", "color"],
  25503. needAlphaBlending: true
  25504. });
  25505. }
  25506. Object.defineProperty(LinesMesh.prototype, "material", {
  25507. get: function () {
  25508. return this._colorShader;
  25509. },
  25510. enumerable: true,
  25511. configurable: true
  25512. });
  25513. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25514. get: function () {
  25515. return false;
  25516. },
  25517. enumerable: true,
  25518. configurable: true
  25519. });
  25520. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25521. get: function () {
  25522. return false;
  25523. },
  25524. enumerable: true,
  25525. configurable: true
  25526. });
  25527. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25528. var engine = this.getScene().getEngine();
  25529. var indexToBind = this._geometry.getIndexBuffer();
  25530. // VBOs
  25531. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25532. // Color
  25533. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25534. };
  25535. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25536. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25537. return;
  25538. }
  25539. var engine = this.getScene().getEngine();
  25540. // Draw order
  25541. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25542. };
  25543. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25544. return null;
  25545. };
  25546. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25547. this._colorShader.dispose();
  25548. _super.prototype.dispose.call(this, doNotRecurse);
  25549. };
  25550. return LinesMesh;
  25551. })(BABYLON.Mesh);
  25552. BABYLON.LinesMesh = LinesMesh;
  25553. })(BABYLON || (BABYLON = {}));
  25554. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25555. (function (BABYLON) {
  25556. var OutlineRenderer = (function () {
  25557. function OutlineRenderer(scene) {
  25558. this._scene = scene;
  25559. }
  25560. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25561. var _this = this;
  25562. if (useOverlay === void 0) { useOverlay = false; }
  25563. var scene = this._scene;
  25564. var engine = this._scene.getEngine();
  25565. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25566. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25567. return;
  25568. }
  25569. var mesh = subMesh.getRenderingMesh();
  25570. var material = subMesh.getMaterial();
  25571. engine.enableEffect(this._effect);
  25572. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25573. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25574. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25575. // Bones
  25576. if (mesh.useBones) {
  25577. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25578. }
  25579. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25580. // Alpha test
  25581. if (material && material.needAlphaTesting()) {
  25582. var alphaTexture = material.getAlphaTestTexture();
  25583. this._effect.setTexture("diffuseSampler", alphaTexture);
  25584. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25585. }
  25586. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25587. _this._effect.setMatrix("world", world);
  25588. });
  25589. };
  25590. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25591. var defines = [];
  25592. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25593. var mesh = subMesh.getMesh();
  25594. var material = subMesh.getMaterial();
  25595. // Alpha test
  25596. if (material && material.needAlphaTesting()) {
  25597. defines.push("#define ALPHATEST");
  25598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25599. attribs.push(BABYLON.VertexBuffer.UVKind);
  25600. defines.push("#define UV1");
  25601. }
  25602. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25603. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25604. defines.push("#define UV2");
  25605. }
  25606. }
  25607. // Bones
  25608. if (mesh.useBones) {
  25609. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25610. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25611. defines.push("#define BONES");
  25612. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25613. }
  25614. // Instances
  25615. if (useInstances) {
  25616. defines.push("#define INSTANCES");
  25617. attribs.push("world0");
  25618. attribs.push("world1");
  25619. attribs.push("world2");
  25620. attribs.push("world3");
  25621. }
  25622. // Get correct effect
  25623. var join = defines.join("\n");
  25624. if (this._cachedDefines !== join) {
  25625. this._cachedDefines = join;
  25626. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25627. }
  25628. return this._effect.isReady();
  25629. };
  25630. return OutlineRenderer;
  25631. })();
  25632. BABYLON.OutlineRenderer = OutlineRenderer;
  25633. })(BABYLON || (BABYLON = {}));
  25634. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25635. (function (BABYLON) {
  25636. var MeshAssetTask = (function () {
  25637. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25638. this.name = name;
  25639. this.meshesNames = meshesNames;
  25640. this.rootUrl = rootUrl;
  25641. this.sceneFilename = sceneFilename;
  25642. this.isCompleted = false;
  25643. }
  25644. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25645. var _this = this;
  25646. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25647. _this.loadedMeshes = meshes;
  25648. _this.loadedParticleSystems = particleSystems;
  25649. _this.loadedSkeletons = skeletons;
  25650. _this.isCompleted = true;
  25651. if (_this.onSuccess) {
  25652. _this.onSuccess(_this);
  25653. }
  25654. onSuccess();
  25655. }, null, function () {
  25656. if (_this.onError) {
  25657. _this.onError(_this);
  25658. }
  25659. onError();
  25660. });
  25661. };
  25662. return MeshAssetTask;
  25663. })();
  25664. BABYLON.MeshAssetTask = MeshAssetTask;
  25665. var TextFileAssetTask = (function () {
  25666. function TextFileAssetTask(name, url) {
  25667. this.name = name;
  25668. this.url = url;
  25669. this.isCompleted = false;
  25670. }
  25671. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25672. var _this = this;
  25673. BABYLON.Tools.LoadFile(this.url, function (data) {
  25674. _this.text = data;
  25675. _this.isCompleted = true;
  25676. if (_this.onSuccess) {
  25677. _this.onSuccess(_this);
  25678. }
  25679. onSuccess();
  25680. }, null, scene.database, false, function () {
  25681. if (_this.onError) {
  25682. _this.onError(_this);
  25683. }
  25684. onError();
  25685. });
  25686. };
  25687. return TextFileAssetTask;
  25688. })();
  25689. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25690. var BinaryFileAssetTask = (function () {
  25691. function BinaryFileAssetTask(name, url) {
  25692. this.name = name;
  25693. this.url = url;
  25694. this.isCompleted = false;
  25695. }
  25696. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25697. var _this = this;
  25698. BABYLON.Tools.LoadFile(this.url, function (data) {
  25699. _this.data = data;
  25700. _this.isCompleted = true;
  25701. if (_this.onSuccess) {
  25702. _this.onSuccess(_this);
  25703. }
  25704. onSuccess();
  25705. }, null, scene.database, true, function () {
  25706. if (_this.onError) {
  25707. _this.onError(_this);
  25708. }
  25709. onError();
  25710. });
  25711. };
  25712. return BinaryFileAssetTask;
  25713. })();
  25714. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25715. var ImageAssetTask = (function () {
  25716. function ImageAssetTask(name, url) {
  25717. this.name = name;
  25718. this.url = url;
  25719. this.isCompleted = false;
  25720. }
  25721. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25722. var _this = this;
  25723. var img = new Image();
  25724. img.onload = function () {
  25725. _this.image = img;
  25726. _this.isCompleted = true;
  25727. if (_this.onSuccess) {
  25728. _this.onSuccess(_this);
  25729. }
  25730. onSuccess();
  25731. };
  25732. img.onerror = function () {
  25733. if (_this.onError) {
  25734. _this.onError(_this);
  25735. }
  25736. onError();
  25737. };
  25738. img.src = this.url;
  25739. };
  25740. return ImageAssetTask;
  25741. })();
  25742. BABYLON.ImageAssetTask = ImageAssetTask;
  25743. var TextureAssetTask = (function () {
  25744. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25746. this.name = name;
  25747. this.url = url;
  25748. this.noMipmap = noMipmap;
  25749. this.invertY = invertY;
  25750. this.samplingMode = samplingMode;
  25751. this.isCompleted = false;
  25752. }
  25753. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25754. var _this = this;
  25755. var onload = function () {
  25756. _this.isCompleted = true;
  25757. if (_this.onSuccess) {
  25758. _this.onSuccess(_this);
  25759. }
  25760. onSuccess();
  25761. };
  25762. var onerror = function () {
  25763. if (_this.onError) {
  25764. _this.onError(_this);
  25765. }
  25766. onError();
  25767. };
  25768. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25769. };
  25770. return TextureAssetTask;
  25771. })();
  25772. BABYLON.TextureAssetTask = TextureAssetTask;
  25773. var AssetsManager = (function () {
  25774. function AssetsManager(scene) {
  25775. this._tasks = new Array();
  25776. this._waitingTasksCount = 0;
  25777. this.useDefaultLoadingScreen = true;
  25778. this._scene = scene;
  25779. }
  25780. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25781. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25782. this._tasks.push(task);
  25783. return task;
  25784. };
  25785. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25786. var task = new TextFileAssetTask(taskName, url);
  25787. this._tasks.push(task);
  25788. return task;
  25789. };
  25790. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25791. var task = new BinaryFileAssetTask(taskName, url);
  25792. this._tasks.push(task);
  25793. return task;
  25794. };
  25795. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25796. var task = new ImageAssetTask(taskName, url);
  25797. this._tasks.push(task);
  25798. return task;
  25799. };
  25800. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25801. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25802. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25803. this._tasks.push(task);
  25804. return task;
  25805. };
  25806. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25807. this._waitingTasksCount--;
  25808. if (this._waitingTasksCount === 0) {
  25809. if (this.onFinish) {
  25810. this.onFinish(this._tasks);
  25811. }
  25812. this._scene.getEngine().hideLoadingUI();
  25813. }
  25814. };
  25815. AssetsManager.prototype._runTask = function (task) {
  25816. var _this = this;
  25817. task.run(this._scene, function () {
  25818. if (_this.onTaskSuccess) {
  25819. _this.onTaskSuccess(task);
  25820. }
  25821. _this._decreaseWaitingTasksCount();
  25822. }, function () {
  25823. if (_this.onTaskError) {
  25824. _this.onTaskError(task);
  25825. }
  25826. _this._decreaseWaitingTasksCount();
  25827. });
  25828. };
  25829. AssetsManager.prototype.reset = function () {
  25830. this._tasks = new Array();
  25831. return this;
  25832. };
  25833. AssetsManager.prototype.load = function () {
  25834. this._waitingTasksCount = this._tasks.length;
  25835. if (this._waitingTasksCount === 0) {
  25836. if (this.onFinish) {
  25837. this.onFinish(this._tasks);
  25838. }
  25839. return this;
  25840. }
  25841. if (this.useDefaultLoadingScreen) {
  25842. this._scene.getEngine().displayLoadingUI();
  25843. }
  25844. for (var index = 0; index < this._tasks.length; index++) {
  25845. var task = this._tasks[index];
  25846. this._runTask(task);
  25847. }
  25848. return this;
  25849. };
  25850. return AssetsManager;
  25851. })();
  25852. BABYLON.AssetsManager = AssetsManager;
  25853. })(BABYLON || (BABYLON = {}));
  25854. //# sourceMappingURL=babylon.assetsManager.js.map
  25855. var BABYLON;
  25856. (function (BABYLON) {
  25857. var VRDeviceOrientationCamera = (function (_super) {
  25858. __extends(VRDeviceOrientationCamera, _super);
  25859. function VRDeviceOrientationCamera(name, position, scene) {
  25860. _super.call(this, name, position, scene);
  25861. this._alpha = 0;
  25862. this._beta = 0;
  25863. this._gamma = 0;
  25864. }
  25865. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25866. this._alpha = +evt.alpha | 0;
  25867. this._beta = +evt.beta | 0;
  25868. this._gamma = +evt.gamma | 0;
  25869. if (this._gamma < 0) {
  25870. this._gamma = 90 + this._gamma;
  25871. }
  25872. else {
  25873. // Incline it in the correct angle.
  25874. this._gamma = 270 - this._gamma;
  25875. }
  25876. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25877. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  25878. this.rotation.z = this._beta / 180.0 * Math.PI;
  25879. };
  25880. return VRDeviceOrientationCamera;
  25881. })(BABYLON.OculusCamera);
  25882. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  25883. })(BABYLON || (BABYLON = {}));
  25884. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  25885. var BABYLON;
  25886. (function (BABYLON) {
  25887. var WebVRCamera = (function (_super) {
  25888. __extends(WebVRCamera, _super);
  25889. function WebVRCamera(name, position, scene) {
  25890. _super.call(this, name, position, scene);
  25891. this._hmdDevice = null;
  25892. this._sensorDevice = null;
  25893. this._cacheState = null;
  25894. this._cacheQuaternion = new BABYLON.Quaternion();
  25895. this._cacheRotation = BABYLON.Vector3.Zero();
  25896. this._vrEnabled = false;
  25897. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  25898. }
  25899. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  25900. var size = devices.length;
  25901. var i = 0;
  25902. // Reset devices.
  25903. this._sensorDevice = null;
  25904. this._hmdDevice = null;
  25905. while (i < size && this._hmdDevice === null) {
  25906. if (devices[i] instanceof HMDVRDevice) {
  25907. this._hmdDevice = devices[i];
  25908. }
  25909. i++;
  25910. }
  25911. i = 0;
  25912. while (i < size && this._sensorDevice === null) {
  25913. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  25914. this._sensorDevice = devices[i];
  25915. }
  25916. i++;
  25917. }
  25918. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  25919. };
  25920. WebVRCamera.prototype._update = function () {
  25921. if (this._vrEnabled) {
  25922. this._cacheState = this._sensorDevice.getState();
  25923. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  25924. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  25925. this.rotation.x = -this._cacheRotation.z;
  25926. this.rotation.y = -this._cacheRotation.y;
  25927. this.rotation.z = this._cacheRotation.x;
  25928. }
  25929. _super.prototype._update.call(this);
  25930. };
  25931. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  25932. _super.prototype.attachControl.call(this, element, noPreventDefault);
  25933. if (navigator.getVRDevices) {
  25934. navigator.getVRDevices().then(this._getWebVRDevices);
  25935. }
  25936. else if (navigator.mozGetVRDevices) {
  25937. navigator.mozGetVRDevices(this._getWebVRDevices);
  25938. }
  25939. };
  25940. WebVRCamera.prototype.detachControl = function (element) {
  25941. _super.prototype.detachControl.call(this, element);
  25942. this._vrEnabled = false;
  25943. };
  25944. return WebVRCamera;
  25945. })(BABYLON.OculusCamera);
  25946. BABYLON.WebVRCamera = WebVRCamera;
  25947. })(BABYLON || (BABYLON = {}));
  25948. //# sourceMappingURL=babylon.webVRCamera.js.map
  25949. var BABYLON;
  25950. (function (BABYLON) {
  25951. // Standard optimizations
  25952. var SceneOptimization = (function () {
  25953. function SceneOptimization(priority) {
  25954. if (priority === void 0) { priority = 0; }
  25955. this.priority = priority;
  25956. this.apply = function (scene) {
  25957. return true; // Return true if everything that can be done was applied
  25958. };
  25959. }
  25960. return SceneOptimization;
  25961. })();
  25962. BABYLON.SceneOptimization = SceneOptimization;
  25963. var TextureOptimization = (function (_super) {
  25964. __extends(TextureOptimization, _super);
  25965. function TextureOptimization(priority, maximumSize) {
  25966. var _this = this;
  25967. if (priority === void 0) { priority = 0; }
  25968. if (maximumSize === void 0) { maximumSize = 1024; }
  25969. _super.call(this, priority);
  25970. this.priority = priority;
  25971. this.maximumSize = maximumSize;
  25972. this.apply = function (scene) {
  25973. var allDone = true;
  25974. for (var index = 0; index < scene.textures.length; index++) {
  25975. var texture = scene.textures[index];
  25976. if (!texture.canRescale) {
  25977. continue;
  25978. }
  25979. var currentSize = texture.getSize();
  25980. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25981. if (maxDimension > _this.maximumSize) {
  25982. texture.scale(0.5);
  25983. allDone = false;
  25984. }
  25985. }
  25986. return allDone;
  25987. };
  25988. }
  25989. return TextureOptimization;
  25990. })(SceneOptimization);
  25991. BABYLON.TextureOptimization = TextureOptimization;
  25992. var HardwareScalingOptimization = (function (_super) {
  25993. __extends(HardwareScalingOptimization, _super);
  25994. function HardwareScalingOptimization(priority, maximumScale) {
  25995. var _this = this;
  25996. if (priority === void 0) { priority = 0; }
  25997. if (maximumScale === void 0) { maximumScale = 2; }
  25998. _super.call(this, priority);
  25999. this.priority = priority;
  26000. this.maximumScale = maximumScale;
  26001. this._currentScale = 1;
  26002. this.apply = function (scene) {
  26003. _this._currentScale++;
  26004. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26005. return _this._currentScale >= _this.maximumScale;
  26006. };
  26007. }
  26008. return HardwareScalingOptimization;
  26009. })(SceneOptimization);
  26010. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26011. var ShadowsOptimization = (function (_super) {
  26012. __extends(ShadowsOptimization, _super);
  26013. function ShadowsOptimization() {
  26014. _super.apply(this, arguments);
  26015. this.apply = function (scene) {
  26016. scene.shadowsEnabled = false;
  26017. return true;
  26018. };
  26019. }
  26020. return ShadowsOptimization;
  26021. })(SceneOptimization);
  26022. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26023. var PostProcessesOptimization = (function (_super) {
  26024. __extends(PostProcessesOptimization, _super);
  26025. function PostProcessesOptimization() {
  26026. _super.apply(this, arguments);
  26027. this.apply = function (scene) {
  26028. scene.postProcessesEnabled = false;
  26029. return true;
  26030. };
  26031. }
  26032. return PostProcessesOptimization;
  26033. })(SceneOptimization);
  26034. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26035. var LensFlaresOptimization = (function (_super) {
  26036. __extends(LensFlaresOptimization, _super);
  26037. function LensFlaresOptimization() {
  26038. _super.apply(this, arguments);
  26039. this.apply = function (scene) {
  26040. scene.lensFlaresEnabled = false;
  26041. return true;
  26042. };
  26043. }
  26044. return LensFlaresOptimization;
  26045. })(SceneOptimization);
  26046. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26047. var ParticlesOptimization = (function (_super) {
  26048. __extends(ParticlesOptimization, _super);
  26049. function ParticlesOptimization() {
  26050. _super.apply(this, arguments);
  26051. this.apply = function (scene) {
  26052. scene.particlesEnabled = false;
  26053. return true;
  26054. };
  26055. }
  26056. return ParticlesOptimization;
  26057. })(SceneOptimization);
  26058. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26059. var RenderTargetsOptimization = (function (_super) {
  26060. __extends(RenderTargetsOptimization, _super);
  26061. function RenderTargetsOptimization() {
  26062. _super.apply(this, arguments);
  26063. this.apply = function (scene) {
  26064. scene.renderTargetsEnabled = false;
  26065. return true;
  26066. };
  26067. }
  26068. return RenderTargetsOptimization;
  26069. })(SceneOptimization);
  26070. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26071. var MergeMeshesOptimization = (function (_super) {
  26072. __extends(MergeMeshesOptimization, _super);
  26073. function MergeMeshesOptimization() {
  26074. var _this = this;
  26075. _super.apply(this, arguments);
  26076. this._canBeMerged = function (abstractMesh) {
  26077. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26078. return false;
  26079. }
  26080. var mesh = abstractMesh;
  26081. if (!mesh.isVisible || !mesh.isEnabled()) {
  26082. return false;
  26083. }
  26084. if (mesh.instances.length > 0) {
  26085. return false;
  26086. }
  26087. if (mesh.skeleton || mesh.hasLODLevels) {
  26088. return false;
  26089. }
  26090. return true;
  26091. };
  26092. this.apply = function (scene) {
  26093. var globalPool = scene.meshes.slice(0);
  26094. var globalLength = globalPool.length;
  26095. for (var index = 0; index < globalLength; index++) {
  26096. var currentPool = new Array();
  26097. var current = globalPool[index];
  26098. // Checks
  26099. if (!_this._canBeMerged(current)) {
  26100. continue;
  26101. }
  26102. currentPool.push(current);
  26103. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26104. var otherMesh = globalPool[subIndex];
  26105. if (!_this._canBeMerged(otherMesh)) {
  26106. continue;
  26107. }
  26108. if (otherMesh.material !== current.material) {
  26109. continue;
  26110. }
  26111. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26112. continue;
  26113. }
  26114. currentPool.push(otherMesh);
  26115. globalLength--;
  26116. globalPool.splice(subIndex, 1);
  26117. subIndex--;
  26118. }
  26119. if (currentPool.length < 2) {
  26120. continue;
  26121. }
  26122. // Merge meshes
  26123. BABYLON.Mesh.MergeMeshes(currentPool);
  26124. }
  26125. return true;
  26126. };
  26127. }
  26128. return MergeMeshesOptimization;
  26129. })(SceneOptimization);
  26130. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26131. // Options
  26132. var SceneOptimizerOptions = (function () {
  26133. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26134. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26135. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26136. this.targetFrameRate = targetFrameRate;
  26137. this.trackerDuration = trackerDuration;
  26138. this.optimizations = new Array();
  26139. }
  26140. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26141. var result = new SceneOptimizerOptions(targetFrameRate);
  26142. var priority = 0;
  26143. result.optimizations.push(new MergeMeshesOptimization(priority));
  26144. result.optimizations.push(new ShadowsOptimization(priority));
  26145. result.optimizations.push(new LensFlaresOptimization(priority));
  26146. // Next priority
  26147. priority++;
  26148. result.optimizations.push(new PostProcessesOptimization(priority));
  26149. result.optimizations.push(new ParticlesOptimization(priority));
  26150. // Next priority
  26151. priority++;
  26152. result.optimizations.push(new TextureOptimization(priority, 1024));
  26153. return result;
  26154. };
  26155. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26156. var result = new SceneOptimizerOptions(targetFrameRate);
  26157. var priority = 0;
  26158. result.optimizations.push(new MergeMeshesOptimization(priority));
  26159. result.optimizations.push(new ShadowsOptimization(priority));
  26160. result.optimizations.push(new LensFlaresOptimization(priority));
  26161. // Next priority
  26162. priority++;
  26163. result.optimizations.push(new PostProcessesOptimization(priority));
  26164. result.optimizations.push(new ParticlesOptimization(priority));
  26165. // Next priority
  26166. priority++;
  26167. result.optimizations.push(new TextureOptimization(priority, 512));
  26168. // Next priority
  26169. priority++;
  26170. result.optimizations.push(new RenderTargetsOptimization(priority));
  26171. // Next priority
  26172. priority++;
  26173. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26174. return result;
  26175. };
  26176. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26177. var result = new SceneOptimizerOptions(targetFrameRate);
  26178. var priority = 0;
  26179. result.optimizations.push(new MergeMeshesOptimization(priority));
  26180. result.optimizations.push(new ShadowsOptimization(priority));
  26181. result.optimizations.push(new LensFlaresOptimization(priority));
  26182. // Next priority
  26183. priority++;
  26184. result.optimizations.push(new PostProcessesOptimization(priority));
  26185. result.optimizations.push(new ParticlesOptimization(priority));
  26186. // Next priority
  26187. priority++;
  26188. result.optimizations.push(new TextureOptimization(priority, 256));
  26189. // Next priority
  26190. priority++;
  26191. result.optimizations.push(new RenderTargetsOptimization(priority));
  26192. // Next priority
  26193. priority++;
  26194. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26195. return result;
  26196. };
  26197. return SceneOptimizerOptions;
  26198. })();
  26199. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26200. // Scene optimizer tool
  26201. var SceneOptimizer = (function () {
  26202. function SceneOptimizer() {
  26203. }
  26204. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26205. // TODO: add an epsilon
  26206. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26207. if (onSuccess) {
  26208. onSuccess();
  26209. }
  26210. return;
  26211. }
  26212. // Apply current level of optimizations
  26213. var allDone = true;
  26214. var noOptimizationApplied = true;
  26215. for (var index = 0; index < options.optimizations.length; index++) {
  26216. var optimization = options.optimizations[index];
  26217. if (optimization.priority === currentPriorityLevel) {
  26218. noOptimizationApplied = false;
  26219. allDone = allDone && optimization.apply(scene);
  26220. }
  26221. }
  26222. // If no optimization was applied, this is a failure :(
  26223. if (noOptimizationApplied) {
  26224. if (onFailure) {
  26225. onFailure();
  26226. }
  26227. return;
  26228. }
  26229. // If all optimizations were done, move to next level
  26230. if (allDone) {
  26231. currentPriorityLevel++;
  26232. }
  26233. // Let's the system running for a specific amount of time before checking FPS
  26234. scene.executeWhenReady(function () {
  26235. setTimeout(function () {
  26236. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26237. }, options.trackerDuration);
  26238. });
  26239. };
  26240. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26241. if (!options) {
  26242. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26243. }
  26244. // Let's the system running for a specific amount of time before checking FPS
  26245. scene.executeWhenReady(function () {
  26246. setTimeout(function () {
  26247. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26248. }, options.trackerDuration);
  26249. });
  26250. };
  26251. return SceneOptimizer;
  26252. })();
  26253. BABYLON.SceneOptimizer = SceneOptimizer;
  26254. })(BABYLON || (BABYLON = {}));
  26255. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26256. (function (BABYLON) {
  26257. var Internals;
  26258. (function (Internals) {
  26259. var MeshLODLevel = (function () {
  26260. function MeshLODLevel(distance, mesh) {
  26261. this.distance = distance;
  26262. this.mesh = mesh;
  26263. }
  26264. return MeshLODLevel;
  26265. })();
  26266. Internals.MeshLODLevel = MeshLODLevel;
  26267. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26268. })(BABYLON || (BABYLON = {}));
  26269. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26270. (function (BABYLON) {
  26271. var AudioEngine = (function () {
  26272. function AudioEngine() {
  26273. this.audioContext = null;
  26274. this.canUseWebAudio = false;
  26275. this.WarnedWebAudioUnsupported = false;
  26276. try {
  26277. if (typeof AudioContext !== 'undefined') {
  26278. this.audioContext = new AudioContext();
  26279. this.canUseWebAudio = true;
  26280. }
  26281. else if (typeof webkitAudioContext !== 'undefined') {
  26282. this.audioContext = new webkitAudioContext();
  26283. this.canUseWebAudio = true;
  26284. }
  26285. }
  26286. catch (e) {
  26287. this.canUseWebAudio = false;
  26288. BABYLON.Tools.Error("Web Audio: " + e.message);
  26289. }
  26290. // create a global volume gain node
  26291. if (this.canUseWebAudio) {
  26292. this.masterGain = this.audioContext.createGain();
  26293. this.masterGain.gain.value = 1;
  26294. this.masterGain.connect(this.audioContext.destination);
  26295. }
  26296. }
  26297. AudioEngine.prototype.dispose = function () {
  26298. if (this.canUseWebAudio) {
  26299. if (this._connectedAnalyser) {
  26300. this._connectedAnalyser.stopDebugCanvas();
  26301. this._connectedAnalyser.dispose();
  26302. this.masterGain.disconnect();
  26303. this.masterGain.connect(this.audioContext.destination);
  26304. this._connectedAnalyser = null;
  26305. }
  26306. this.masterGain.gain.value = 1;
  26307. }
  26308. this.WarnedWebAudioUnsupported = false;
  26309. };
  26310. AudioEngine.prototype.getGlobalVolume = function () {
  26311. if (this.canUseWebAudio) {
  26312. return this.masterGain.gain.value;
  26313. }
  26314. else {
  26315. return -1;
  26316. }
  26317. };
  26318. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26319. if (this.canUseWebAudio) {
  26320. this.masterGain.gain.value = newVolume;
  26321. }
  26322. };
  26323. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26324. if (this._connectedAnalyser) {
  26325. this._connectedAnalyser.stopDebugCanvas();
  26326. }
  26327. this._connectedAnalyser = analyser;
  26328. if (this.canUseWebAudio) {
  26329. this.masterGain.disconnect();
  26330. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26331. }
  26332. };
  26333. return AudioEngine;
  26334. })();
  26335. BABYLON.AudioEngine = AudioEngine;
  26336. })(BABYLON || (BABYLON = {}));
  26337. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  26338. (function (BABYLON) {
  26339. var Sound = (function () {
  26340. /**
  26341. * Create a sound and attach it to a scene
  26342. * @param name Name of your sound
  26343. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26344. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26345. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26346. */
  26347. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26348. var _this = this;
  26349. this.autoplay = false;
  26350. this.loop = false;
  26351. this.useCustomAttenuation = false;
  26352. this.spatialSound = false;
  26353. this.refDistance = 1;
  26354. this.rolloffFactor = 1;
  26355. this.maxDistance = 100;
  26356. this.distanceModel = "linear";
  26357. this.panningModel = "HRTF";
  26358. this._playbackRate = 1;
  26359. this._startTime = 0;
  26360. this._startOffset = 0;
  26361. this._position = BABYLON.Vector3.Zero();
  26362. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26363. this._volume = 1;
  26364. this._isLoaded = false;
  26365. this._isReadyToPlay = false;
  26366. this.isPlaying = false;
  26367. this.isPaused = false;
  26368. this._isDirectional = false;
  26369. // Used if you'd like to create a directional sound.
  26370. // If not set, the sound will be omnidirectional
  26371. this._coneInnerAngle = 360;
  26372. this._coneOuterAngle = 360;
  26373. this._coneOuterGain = 0;
  26374. this.name = name;
  26375. this._scene = scene;
  26376. this._readyToPlayCallback = readyToPlayCallback;
  26377. // Default custom attenuation function is a linear attenuation
  26378. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26379. if (currentDistance < maxDistance) {
  26380. return currentVolume * (1 - currentDistance / maxDistance);
  26381. }
  26382. else {
  26383. return 0;
  26384. }
  26385. };
  26386. if (options) {
  26387. this.autoplay = options.autoplay || false;
  26388. this.loop = options.loop || false;
  26389. // if volume === 0, we need another way to check this option
  26390. if (options.volume !== undefined) {
  26391. this._volume = options.volume;
  26392. }
  26393. this.spatialSound = options.spatialSound || false;
  26394. this.maxDistance = options.maxDistance || 100;
  26395. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26396. this.rolloffFactor = options.rolloffFactor || 1;
  26397. this.refDistance = options.refDistance || 1;
  26398. this.distanceModel = options.distanceModel || "linear";
  26399. this.panningModel = options.panningModel || "HRTF";
  26400. this._playbackRate = options.playbackRate || 1;
  26401. }
  26402. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26403. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26404. this._soundGain.gain.value = this._volume;
  26405. this._inputAudioNode = this._soundGain;
  26406. this._ouputAudioNode = this._soundGain;
  26407. if (this.spatialSound) {
  26408. this._createSpatialParameters();
  26409. }
  26410. this._scene.mainSoundTrack.AddSound(this);
  26411. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26412. if (urlOrArrayBuffer) {
  26413. // If it's an URL
  26414. if (typeof (urlOrArrayBuffer) === "string") {
  26415. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26416. _this._soundLoaded(data);
  26417. }, null, null, true);
  26418. }
  26419. else {
  26420. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26421. this._soundLoaded(urlOrArrayBuffer);
  26422. }
  26423. else {
  26424. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26425. }
  26426. }
  26427. }
  26428. }
  26429. else {
  26430. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26431. this._scene.mainSoundTrack.AddSound(this);
  26432. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26433. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26434. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26435. }
  26436. }
  26437. }
  26438. Sound.prototype.dispose = function () {
  26439. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26440. if (this.isPlaying) {
  26441. this.stop();
  26442. }
  26443. this._isReadyToPlay = false;
  26444. if (this.soundTrackId === -1) {
  26445. this._scene.mainSoundTrack.RemoveSound(this);
  26446. }
  26447. else {
  26448. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26449. }
  26450. if (this._soundGain) {
  26451. this._soundGain.disconnect();
  26452. this._soundGain = null;
  26453. }
  26454. if (this._soundPanner) {
  26455. this._soundPanner.disconnect();
  26456. this._soundPanner = null;
  26457. }
  26458. if (this._soundSource) {
  26459. this._soundSource.disconnect();
  26460. this._soundSource = null;
  26461. }
  26462. this._audioBuffer = null;
  26463. if (this._connectedMesh) {
  26464. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26465. this._connectedMesh = null;
  26466. }
  26467. }
  26468. };
  26469. Sound.prototype._soundLoaded = function (audioData) {
  26470. var _this = this;
  26471. this._isLoaded = true;
  26472. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26473. _this._audioBuffer = buffer;
  26474. _this._isReadyToPlay = true;
  26475. if (_this.autoplay) {
  26476. _this.play();
  26477. }
  26478. if (_this._readyToPlayCallback) {
  26479. _this._readyToPlayCallback();
  26480. }
  26481. }, function (error) {
  26482. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26483. });
  26484. };
  26485. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26486. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26487. this._audioBuffer = audioBuffer;
  26488. this._isReadyToPlay = true;
  26489. }
  26490. };
  26491. Sound.prototype.updateOptions = function (options) {
  26492. if (options) {
  26493. this.loop = options.loop || this.loop;
  26494. this.maxDistance = options.maxDistance || this.maxDistance;
  26495. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26496. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26497. this.refDistance = options.refDistance || this.refDistance;
  26498. this.distanceModel = options.distanceModel || this.distanceModel;
  26499. this.panningModel = options.panningModel || this.panningModel;
  26500. this._playbackRate = options.playbackRate || this._playbackRate;
  26501. }
  26502. };
  26503. Sound.prototype._createSpatialParameters = function () {
  26504. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26505. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26506. if (this.useCustomAttenuation) {
  26507. // Tricks to disable in a way embedded Web Audio attenuation
  26508. this._soundPanner.distanceModel = "linear";
  26509. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26510. this._soundPanner.refDistance = 1;
  26511. this._soundPanner.rolloffFactor = 1;
  26512. this._soundPanner.panningModel = "HRTF";
  26513. }
  26514. else {
  26515. this._soundPanner.distanceModel = this.distanceModel;
  26516. this._soundPanner.maxDistance = this.maxDistance;
  26517. this._soundPanner.refDistance = this.refDistance;
  26518. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26519. this._soundPanner.panningModel = this.panningModel;
  26520. }
  26521. this._soundPanner.connect(this._ouputAudioNode);
  26522. this._inputAudioNode = this._soundPanner;
  26523. }
  26524. };
  26525. Sound.prototype.switchPanningModelToHRTF = function () {
  26526. this._switchPanningModel("HRTF");
  26527. };
  26528. Sound.prototype.switchPanningModelToEqualPower = function () {
  26529. this._switchPanningModel("equalpower");
  26530. };
  26531. Sound.prototype._switchPanningModel = function (newModel) {
  26532. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  26533. this._soundPanner.panningModel = newModel;
  26534. }
  26535. };
  26536. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26537. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26538. this._ouputAudioNode.disconnect();
  26539. this._ouputAudioNode.connect(soundTrackAudioNode);
  26540. }
  26541. };
  26542. /**
  26543. * Transform this sound into a directional source
  26544. * @param coneInnerAngle Size of the inner cone in degree
  26545. * @param coneOuterAngle Size of the outer cone in degree
  26546. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26547. */
  26548. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26549. if (coneOuterAngle < coneInnerAngle) {
  26550. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26551. return;
  26552. }
  26553. this._coneInnerAngle = coneInnerAngle;
  26554. this._coneOuterAngle = coneOuterAngle;
  26555. this._coneOuterGain = coneOuterGain;
  26556. this._isDirectional = true;
  26557. if (this.isPlaying && this.loop) {
  26558. this.stop();
  26559. this.play();
  26560. }
  26561. };
  26562. Sound.prototype.setPosition = function (newPosition) {
  26563. this._position = newPosition;
  26564. if (this.isPlaying && this.spatialSound) {
  26565. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26566. }
  26567. };
  26568. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26569. this._localDirection = newLocalDirection;
  26570. if (this._connectedMesh && this.isPlaying) {
  26571. this._updateDirection();
  26572. }
  26573. };
  26574. Sound.prototype._updateDirection = function () {
  26575. var mat = this._connectedMesh.getWorldMatrix();
  26576. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26577. direction.normalize();
  26578. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26579. };
  26580. Sound.prototype.updateDistanceFromListener = function () {
  26581. if (this._connectedMesh && this.useCustomAttenuation) {
  26582. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26583. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26584. }
  26585. };
  26586. Sound.prototype.setAttenuationFunction = function (callback) {
  26587. this._customAttenuationFunction = callback;
  26588. };
  26589. /**
  26590. * Play the sound
  26591. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26592. */
  26593. Sound.prototype.play = function (time) {
  26594. var _this = this;
  26595. if (this._isReadyToPlay && this._scene.audioEnabled) {
  26596. try {
  26597. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26598. if (!this._soundSource) {
  26599. if (this.spatialSound) {
  26600. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26601. if (this._isDirectional) {
  26602. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26603. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26604. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26605. if (this._connectedMesh) {
  26606. this._updateDirection();
  26607. }
  26608. else {
  26609. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26610. }
  26611. }
  26612. }
  26613. }
  26614. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26615. this._soundSource.buffer = this._audioBuffer;
  26616. this._soundSource.connect(this._inputAudioNode);
  26617. this._soundSource.loop = this.loop;
  26618. this._soundSource.playbackRate.value = this._playbackRate;
  26619. this._startTime = startTime;
  26620. this._soundSource.onended = function () {
  26621. _this._onended();
  26622. };
  26623. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  26624. this.isPlaying = true;
  26625. this.isPaused = false;
  26626. }
  26627. catch (ex) {
  26628. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26629. }
  26630. }
  26631. };
  26632. Sound.prototype._onended = function () {
  26633. this.isPlaying = false;
  26634. if (this.onended) {
  26635. this.onended();
  26636. }
  26637. };
  26638. /**
  26639. * Stop the sound
  26640. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26641. */
  26642. Sound.prototype.stop = function (time) {
  26643. if (this.isPlaying) {
  26644. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26645. this._soundSource.stop(stopTime);
  26646. this.isPlaying = false;
  26647. }
  26648. };
  26649. Sound.prototype.pause = function () {
  26650. if (this.isPlaying) {
  26651. this.stop(0);
  26652. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26653. this.isPaused = true;
  26654. }
  26655. };
  26656. Sound.prototype.setVolume = function (newVolume, time) {
  26657. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26658. if (time) {
  26659. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26660. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26661. }
  26662. else {
  26663. this._soundGain.gain.value = newVolume;
  26664. }
  26665. }
  26666. this._volume = newVolume;
  26667. };
  26668. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26669. this._playbackRate = newPlaybackRate;
  26670. if (this.isPlaying) {
  26671. this._soundSource.playbackRate.value = this._playbackRate;
  26672. }
  26673. };
  26674. Sound.prototype.getVolume = function () {
  26675. return this._volume;
  26676. };
  26677. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26678. var _this = this;
  26679. this._connectedMesh = meshToConnectTo;
  26680. if (!this.spatialSound) {
  26681. this._createSpatialParameters();
  26682. this.spatialSound = true;
  26683. if (this.isPlaying && this.loop) {
  26684. this.stop();
  26685. this.play();
  26686. }
  26687. }
  26688. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26689. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26690. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26691. };
  26692. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26693. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26694. if (this._isDirectional && this.isPlaying) {
  26695. this._updateDirection();
  26696. }
  26697. };
  26698. return Sound;
  26699. })();
  26700. BABYLON.Sound = Sound;
  26701. })(BABYLON || (BABYLON = {}));
  26702. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26703. (function (BABYLON) {
  26704. var SoundTrack = (function () {
  26705. function SoundTrack(scene, options) {
  26706. this.id = -1;
  26707. this._isMainTrack = false;
  26708. this._scene = scene;
  26709. this._audioEngine = BABYLON.Engine.audioEngine;
  26710. this.soundCollection = new Array();
  26711. if (this._audioEngine.canUseWebAudio) {
  26712. this._trackGain = this._audioEngine.audioContext.createGain();
  26713. this._trackGain.connect(this._audioEngine.masterGain);
  26714. if (options) {
  26715. if (options.volume) {
  26716. this._trackGain.gain.value = options.volume;
  26717. }
  26718. if (options.mainTrack) {
  26719. this._isMainTrack = options.mainTrack;
  26720. }
  26721. }
  26722. }
  26723. if (!this._isMainTrack) {
  26724. this._scene.soundTracks.push(this);
  26725. this.id = this._scene.soundTracks.length - 1;
  26726. }
  26727. }
  26728. SoundTrack.prototype.dispose = function () {
  26729. if (this._audioEngine.canUseWebAudio) {
  26730. if (this._connectedAnalyser) {
  26731. this._connectedAnalyser.stopDebugCanvas();
  26732. }
  26733. while (this.soundCollection.length) {
  26734. this.soundCollection[0].dispose();
  26735. }
  26736. this._trackGain.disconnect();
  26737. this._trackGain = null;
  26738. }
  26739. };
  26740. SoundTrack.prototype.AddSound = function (sound) {
  26741. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26742. sound.connectToSoundTrackAudioNode(this._trackGain);
  26743. }
  26744. if (sound.soundTrackId) {
  26745. if (sound.soundTrackId === -1) {
  26746. this._scene.mainSoundTrack.RemoveSound(sound);
  26747. }
  26748. else {
  26749. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26750. }
  26751. }
  26752. this.soundCollection.push(sound);
  26753. sound.soundTrackId = this.id;
  26754. };
  26755. SoundTrack.prototype.RemoveSound = function (sound) {
  26756. var index = this.soundCollection.indexOf(sound);
  26757. if (index !== -1) {
  26758. this.soundCollection.splice(index, 1);
  26759. }
  26760. };
  26761. SoundTrack.prototype.setVolume = function (newVolume) {
  26762. if (this._audioEngine.canUseWebAudio) {
  26763. this._trackGain.gain.value = newVolume;
  26764. }
  26765. };
  26766. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  26767. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26768. for (var i = 0; i < this.soundCollection.length; i++) {
  26769. this.soundCollection[i].switchPanningModelToHRTF();
  26770. }
  26771. }
  26772. };
  26773. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  26774. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26775. for (var i = 0; i < this.soundCollection.length; i++) {
  26776. this.soundCollection[i].switchPanningModelToEqualPower();
  26777. }
  26778. }
  26779. };
  26780. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26781. if (this._connectedAnalyser) {
  26782. this._connectedAnalyser.stopDebugCanvas();
  26783. }
  26784. this._connectedAnalyser = analyser;
  26785. if (this._audioEngine.canUseWebAudio) {
  26786. this._trackGain.disconnect();
  26787. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26788. }
  26789. };
  26790. return SoundTrack;
  26791. })();
  26792. BABYLON.SoundTrack = SoundTrack;
  26793. })(BABYLON || (BABYLON = {}));
  26794. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26795. (function (BABYLON) {
  26796. var DebugLayer = (function () {
  26797. function DebugLayer(scene) {
  26798. var _this = this;
  26799. this._transformationMatrix = BABYLON.Matrix.Identity();
  26800. this._enabled = false;
  26801. this._labelsEnabled = false;
  26802. this._displayStatistics = true;
  26803. this._displayTree = false;
  26804. this._displayLogs = false;
  26805. this._identityMatrix = BABYLON.Matrix.Identity();
  26806. this.axisRatio = 0.02;
  26807. this.accentColor = "orange";
  26808. this._scene = scene;
  26809. this._syncPositions = function () {
  26810. var engine = _this._scene.getEngine();
  26811. var canvasRect = engine.getRenderingCanvasClientRect();
  26812. if (_this._showUI) {
  26813. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26814. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26815. _this._statsDiv.style.width = "400px";
  26816. _this._statsDiv.style.height = "auto";
  26817. _this._statsSubsetDiv.style.maxHeight = "240px";
  26818. _this._optionsDiv.style.left = "0px";
  26819. _this._optionsDiv.style.top = "10px";
  26820. _this._optionsDiv.style.width = "200px";
  26821. _this._optionsDiv.style.height = "auto";
  26822. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26823. _this._logDiv.style.left = "0px";
  26824. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26825. _this._logDiv.style.width = "600px";
  26826. _this._logDiv.style.height = "160px";
  26827. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26828. _this._treeDiv.style.top = "10px";
  26829. _this._treeDiv.style.width = "300px";
  26830. _this._treeDiv.style.height = "auto";
  26831. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26832. }
  26833. _this._globalDiv.style.left = canvasRect.left + "px";
  26834. _this._globalDiv.style.top = canvasRect.top + "px";
  26835. _this._drawingCanvas.style.left = "0px";
  26836. _this._drawingCanvas.style.top = "0px";
  26837. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26838. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26839. var devicePixelRatio = window.devicePixelRatio || 1;
  26840. var context = _this._drawingContext;
  26841. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26842. _this._ratio = devicePixelRatio / backingStoreRatio;
  26843. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26844. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26845. };
  26846. this._onCanvasClick = function (evt) {
  26847. _this._clickPosition = {
  26848. x: evt.clientX * _this._ratio,
  26849. y: evt.clientY * _this._ratio
  26850. };
  26851. };
  26852. this._syncData = function () {
  26853. if (_this._showUI) {
  26854. if (_this._displayStatistics) {
  26855. _this._displayStats();
  26856. _this._statsDiv.style.display = "";
  26857. }
  26858. else {
  26859. _this._statsDiv.style.display = "none";
  26860. }
  26861. if (_this._displayLogs) {
  26862. _this._logDiv.style.display = "";
  26863. }
  26864. else {
  26865. _this._logDiv.style.display = "none";
  26866. }
  26867. if (_this._displayTree) {
  26868. _this._treeDiv.style.display = "";
  26869. if (_this._needToRefreshMeshesTree) {
  26870. _this._needToRefreshMeshesTree = false;
  26871. _this._refreshMeshesTreeContent();
  26872. }
  26873. }
  26874. else {
  26875. _this._treeDiv.style.display = "none";
  26876. }
  26877. }
  26878. if (_this._labelsEnabled || !_this._showUI) {
  26879. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26880. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26881. var engine = _this._scene.getEngine();
  26882. var viewport = _this._camera.viewport;
  26883. var globalViewport = viewport.toGlobal(engine);
  26884. // Meshes
  26885. var meshes = _this._camera.getActiveMeshes();
  26886. for (var index = 0; index < meshes.length; index++) {
  26887. var mesh = meshes.data[index];
  26888. var position = mesh.getBoundingInfo().boundingSphere.center;
  26889. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26890. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26891. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26892. }
  26893. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26894. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  26895. mesh.renderOverlay = !mesh.renderOverlay;
  26896. }, function () {
  26897. return mesh.renderOverlay ? 'red' : 'black';
  26898. });
  26899. }
  26900. }
  26901. // Cameras
  26902. var cameras = _this._scene.cameras;
  26903. for (index = 0; index < cameras.length; index++) {
  26904. var camera = cameras[index];
  26905. if (camera === _this._camera) {
  26906. continue;
  26907. }
  26908. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26909. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26910. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26911. _this._camera.detachControl(engine.getRenderingCanvas());
  26912. _this._camera = camera;
  26913. _this._camera.attachControl(engine.getRenderingCanvas());
  26914. }, function () {
  26915. return "purple";
  26916. });
  26917. }
  26918. }
  26919. // Lights
  26920. var lights = _this._scene.lights;
  26921. for (index = 0; index < lights.length; index++) {
  26922. var light = lights[index];
  26923. if (light.position) {
  26924. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26925. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26926. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26927. light.setEnabled(!light.isEnabled());
  26928. }, function () {
  26929. return light.isEnabled() ? "orange" : "gray";
  26930. });
  26931. }
  26932. }
  26933. }
  26934. }
  26935. _this._clickPosition = undefined;
  26936. };
  26937. }
  26938. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26939. while (this._treeSubsetDiv.hasChildNodes()) {
  26940. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26941. }
  26942. // Add meshes
  26943. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26944. sortedArray.sort(function (a, b) {
  26945. if (a.name === b.name) {
  26946. return 0;
  26947. }
  26948. return (a.name > b.name) ? 1 : -1;
  26949. });
  26950. for (var index = 0; index < sortedArray.length; index++) {
  26951. var mesh = sortedArray[index];
  26952. if (!mesh.isEnabled()) {
  26953. continue;
  26954. }
  26955. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26956. m.isVisible = element.checked;
  26957. }, mesh);
  26958. }
  26959. };
  26960. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26961. this._drawingContext.beginPath();
  26962. this._drawingContext.moveTo(zero.x, zero.y);
  26963. this._drawingContext.lineTo(unit.x, unit.y);
  26964. this._drawingContext.strokeStyle = color;
  26965. this._drawingContext.lineWidth = 4;
  26966. this._drawingContext.stroke();
  26967. this._drawingContext.font = "normal 14px Segoe UI";
  26968. this._drawingContext.fillStyle = color;
  26969. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26970. };
  26971. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26972. var position = mesh.getBoundingInfo().boundingSphere.center;
  26973. var worldMatrix = mesh.getWorldMatrix();
  26974. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26975. var unit = (unprojectedVector.subtract(position)).length();
  26976. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26977. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26978. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26979. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26980. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26981. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26982. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26983. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26984. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26985. };
  26986. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26987. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26988. this._drawingContext.font = "normal 12px Segoe UI";
  26989. var textMetrics = this._drawingContext.measureText(text);
  26990. var centerX = projectedPosition.x - textMetrics.width / 2;
  26991. var centerY = projectedPosition.y;
  26992. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26993. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26994. onClick();
  26995. }
  26996. this._drawingContext.beginPath();
  26997. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26998. this._drawingContext.fillStyle = getFillStyle();
  26999. this._drawingContext.globalAlpha = 0.5;
  27000. this._drawingContext.fill();
  27001. this._drawingContext.globalAlpha = 1.0;
  27002. this._drawingContext.strokeStyle = '#FFFFFF';
  27003. this._drawingContext.lineWidth = 1;
  27004. this._drawingContext.stroke();
  27005. this._drawingContext.fillStyle = "#FFFFFF";
  27006. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27007. this._drawingContext.beginPath();
  27008. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27009. this._drawingContext.fill();
  27010. }
  27011. };
  27012. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27013. if (!this._clickPosition) {
  27014. return false;
  27015. }
  27016. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27017. return false;
  27018. }
  27019. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27020. return false;
  27021. }
  27022. return true;
  27023. };
  27024. DebugLayer.prototype.isVisible = function () {
  27025. return this._enabled;
  27026. };
  27027. DebugLayer.prototype.hide = function () {
  27028. if (!this._enabled) {
  27029. return;
  27030. }
  27031. this._enabled = false;
  27032. var engine = this._scene.getEngine();
  27033. this._scene.unregisterBeforeRender(this._syncData);
  27034. document.body.removeChild(this._globalDiv);
  27035. window.removeEventListener("resize", this._syncPositions);
  27036. this._scene.forceShowBoundingBoxes = false;
  27037. this._scene.forceWireframe = false;
  27038. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27039. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27040. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27041. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27042. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27043. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27044. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27045. this._scene.shadowsEnabled = true;
  27046. this._scene.particlesEnabled = true;
  27047. this._scene.postProcessesEnabled = true;
  27048. this._scene.collisionsEnabled = true;
  27049. this._scene.lightsEnabled = true;
  27050. this._scene.texturesEnabled = true;
  27051. this._scene.lensFlaresEnabled = true;
  27052. this._scene.proceduralTexturesEnabled = true;
  27053. this._scene.renderTargetsEnabled = true;
  27054. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27055. };
  27056. DebugLayer.prototype.show = function (showUI, camera) {
  27057. if (showUI === void 0) { showUI = true; }
  27058. if (camera === void 0) { camera = null; }
  27059. if (this._enabled) {
  27060. return;
  27061. }
  27062. if (camera) {
  27063. this._camera = camera;
  27064. }
  27065. else {
  27066. this._camera = this._scene.activeCamera;
  27067. }
  27068. this._enabled = true;
  27069. this._showUI = showUI;
  27070. var engine = this._scene.getEngine();
  27071. this._globalDiv = document.createElement("div");
  27072. document.body.appendChild(this._globalDiv);
  27073. this._generateDOMelements();
  27074. window.addEventListener("resize", this._syncPositions);
  27075. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27076. this._syncPositions();
  27077. this._scene.registerBeforeRender(this._syncData);
  27078. };
  27079. DebugLayer.prototype._clearLabels = function () {
  27080. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27081. for (var index = 0; index < this._scene.meshes.length; index++) {
  27082. var mesh = this._scene.meshes[index];
  27083. mesh.renderOverlay = false;
  27084. }
  27085. };
  27086. DebugLayer.prototype._generateheader = function (root, text) {
  27087. var header = document.createElement("div");
  27088. header.innerHTML = text + "&nbsp;";
  27089. header.style.textAlign = "right";
  27090. header.style.width = "100%";
  27091. header.style.color = "white";
  27092. header.style.backgroundColor = "Black";
  27093. header.style.padding = "5px 5px 4px 0px";
  27094. header.style.marginLeft = "-5px";
  27095. header.style.fontWeight = "bold";
  27096. root.appendChild(header);
  27097. };
  27098. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27099. var label = document.createElement("label");
  27100. label.innerHTML = title;
  27101. label.style.color = color;
  27102. root.appendChild(label);
  27103. root.appendChild(document.createElement("br"));
  27104. };
  27105. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27106. if (tag === void 0) { tag = null; }
  27107. var label = document.createElement("label");
  27108. var boundingBoxesCheckbox = document.createElement("input");
  27109. boundingBoxesCheckbox.type = "checkbox";
  27110. boundingBoxesCheckbox.checked = initialState;
  27111. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27112. task(evt.target, tag);
  27113. });
  27114. label.appendChild(boundingBoxesCheckbox);
  27115. var container = document.createElement("span");
  27116. var leftPart = document.createElement("span");
  27117. var rightPart = document.createElement("span");
  27118. rightPart.style.cssFloat = "right";
  27119. leftPart.innerHTML = leftTitle;
  27120. rightPart.innerHTML = rightTitle;
  27121. rightPart.style.fontSize = "12px";
  27122. rightPart.style.maxWidth = "200px";
  27123. container.appendChild(leftPart);
  27124. container.appendChild(rightPart);
  27125. label.appendChild(container);
  27126. root.appendChild(label);
  27127. root.appendChild(document.createElement("br"));
  27128. };
  27129. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27130. if (tag === void 0) { tag = null; }
  27131. var label = document.createElement("label");
  27132. var checkBox = document.createElement("input");
  27133. checkBox.type = "checkbox";
  27134. checkBox.checked = initialState;
  27135. checkBox.addEventListener("change", function (evt) {
  27136. task(evt.target, tag);
  27137. });
  27138. label.appendChild(checkBox);
  27139. label.appendChild(document.createTextNode(title));
  27140. root.appendChild(label);
  27141. root.appendChild(document.createElement("br"));
  27142. };
  27143. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27144. if (tag === void 0) { tag = null; }
  27145. var button = document.createElement("button");
  27146. button.innerHTML = title;
  27147. button.style.height = "20px";
  27148. button.style.color = "#222222";
  27149. button.addEventListener("click", function (evt) {
  27150. task(evt.target, tag);
  27151. });
  27152. root.appendChild(button);
  27153. root.appendChild(document.createElement("br"));
  27154. };
  27155. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27156. if (tag === void 0) { tag = null; }
  27157. var label = document.createElement("label");
  27158. var boundingBoxesRadio = document.createElement("input");
  27159. boundingBoxesRadio.type = "radio";
  27160. boundingBoxesRadio.name = name;
  27161. boundingBoxesRadio.checked = initialState;
  27162. boundingBoxesRadio.addEventListener("change", function (evt) {
  27163. task(evt.target, tag);
  27164. });
  27165. label.appendChild(boundingBoxesRadio);
  27166. label.appendChild(document.createTextNode(title));
  27167. root.appendChild(label);
  27168. root.appendChild(document.createElement("br"));
  27169. };
  27170. DebugLayer.prototype._generateDOMelements = function () {
  27171. var _this = this;
  27172. this._globalDiv.id = "DebugLayer";
  27173. this._globalDiv.style.position = "absolute";
  27174. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27175. this._globalDiv.style.fontSize = "14px";
  27176. this._globalDiv.style.color = "white";
  27177. // Drawing canvas
  27178. this._drawingCanvas = document.createElement("canvas");
  27179. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27180. this._drawingCanvas.style.position = "absolute";
  27181. this._drawingCanvas.style.pointerEvents = "none";
  27182. this._drawingContext = this._drawingCanvas.getContext("2d");
  27183. this._globalDiv.appendChild(this._drawingCanvas);
  27184. if (this._showUI) {
  27185. var background = "rgba(128, 128, 128, 0.4)";
  27186. var border = "rgb(180, 180, 180) solid 1px";
  27187. // Stats
  27188. this._statsDiv = document.createElement("div");
  27189. this._statsDiv.id = "DebugLayerStats";
  27190. this._statsDiv.style.border = border;
  27191. this._statsDiv.style.position = "absolute";
  27192. this._statsDiv.style.background = background;
  27193. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27194. this._generateheader(this._statsDiv, "STATISTICS");
  27195. this._statsSubsetDiv = document.createElement("div");
  27196. this._statsSubsetDiv.style.paddingTop = "5px";
  27197. this._statsSubsetDiv.style.paddingBottom = "5px";
  27198. this._statsSubsetDiv.style.overflowY = "auto";
  27199. this._statsDiv.appendChild(this._statsSubsetDiv);
  27200. // Tree
  27201. this._treeDiv = document.createElement("div");
  27202. this._treeDiv.id = "DebugLayerTree";
  27203. this._treeDiv.style.border = border;
  27204. this._treeDiv.style.position = "absolute";
  27205. this._treeDiv.style.background = background;
  27206. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27207. this._treeDiv.style.display = "none";
  27208. this._generateheader(this._treeDiv, "MESHES TREE");
  27209. this._treeSubsetDiv = document.createElement("div");
  27210. this._treeSubsetDiv.style.paddingTop = "5px";
  27211. this._treeSubsetDiv.style.paddingRight = "5px";
  27212. this._treeSubsetDiv.style.overflowY = "auto";
  27213. this._treeSubsetDiv.style.maxHeight = "300px";
  27214. this._treeDiv.appendChild(this._treeSubsetDiv);
  27215. this._needToRefreshMeshesTree = true;
  27216. // Logs
  27217. this._logDiv = document.createElement("div");
  27218. this._logDiv.style.border = border;
  27219. this._logDiv.id = "DebugLayerLogs";
  27220. this._logDiv.style.position = "absolute";
  27221. this._logDiv.style.background = background;
  27222. this._logDiv.style.padding = "0px 0px 0px 5px";
  27223. this._logDiv.style.display = "none";
  27224. this._generateheader(this._logDiv, "LOGS");
  27225. this._logSubsetDiv = document.createElement("div");
  27226. this._logSubsetDiv.style.height = "127px";
  27227. this._logSubsetDiv.style.paddingTop = "5px";
  27228. this._logSubsetDiv.style.overflowY = "auto";
  27229. this._logSubsetDiv.style.fontSize = "12px";
  27230. this._logSubsetDiv.style.fontFamily = "consolas";
  27231. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27232. this._logDiv.appendChild(this._logSubsetDiv);
  27233. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27234. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27235. };
  27236. // Options
  27237. this._optionsDiv = document.createElement("div");
  27238. this._optionsDiv.id = "DebugLayerOptions";
  27239. this._optionsDiv.style.border = border;
  27240. this._optionsDiv.style.position = "absolute";
  27241. this._optionsDiv.style.background = background;
  27242. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27243. this._optionsDiv.style.overflowY = "auto";
  27244. this._generateheader(this._optionsDiv, "OPTIONS");
  27245. this._optionsSubsetDiv = document.createElement("div");
  27246. this._optionsSubsetDiv.style.paddingTop = "5px";
  27247. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27248. this._optionsSubsetDiv.style.overflowY = "auto";
  27249. this._optionsSubsetDiv.style.maxHeight = "200px";
  27250. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27251. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27252. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27253. _this._displayStatistics = element.checked;
  27254. });
  27255. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27256. _this._displayLogs = element.checked;
  27257. });
  27258. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27259. _this._displayTree = element.checked;
  27260. _this._needToRefreshMeshesTree = true;
  27261. });
  27262. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27263. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27264. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27265. _this._scene.forceShowBoundingBoxes = element.checked;
  27266. });
  27267. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27268. _this._labelsEnabled = element.checked;
  27269. if (!_this._labelsEnabled) {
  27270. _this._clearLabels();
  27271. }
  27272. });
  27273. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27274. if (element.checked) {
  27275. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27276. }
  27277. else {
  27278. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27279. }
  27280. });
  27281. ;
  27282. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27283. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27284. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27285. if (element.checked) {
  27286. _this._scene.forceWireframe = false;
  27287. _this._scene.forcePointsCloud = false;
  27288. }
  27289. });
  27290. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27291. if (element.checked) {
  27292. _this._scene.forceWireframe = true;
  27293. _this._scene.forcePointsCloud = false;
  27294. }
  27295. });
  27296. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27297. if (element.checked) {
  27298. _this._scene.forceWireframe = false;
  27299. _this._scene.forcePointsCloud = true;
  27300. }
  27301. });
  27302. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27303. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27304. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27305. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27306. });
  27307. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27308. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27309. });
  27310. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27311. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27312. });
  27313. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27314. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27315. });
  27316. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27317. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27318. });
  27319. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27320. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27321. });
  27322. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27323. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27324. });
  27325. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27326. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27327. });
  27328. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27329. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27330. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27331. _this._scene.animationsEnabled = element.checked;
  27332. });
  27333. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27334. _this._scene.collisionsEnabled = element.checked;
  27335. });
  27336. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27337. _this._scene.fogEnabled = element.checked;
  27338. });
  27339. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27340. _this._scene.lensFlaresEnabled = element.checked;
  27341. });
  27342. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27343. _this._scene.lightsEnabled = element.checked;
  27344. });
  27345. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27346. _this._scene.particlesEnabled = element.checked;
  27347. });
  27348. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27349. _this._scene.postProcessesEnabled = element.checked;
  27350. });
  27351. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27352. _this._scene.proceduralTexturesEnabled = element.checked;
  27353. });
  27354. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27355. _this._scene.renderTargetsEnabled = element.checked;
  27356. });
  27357. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27358. _this._scene.shadowsEnabled = element.checked;
  27359. });
  27360. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27361. _this._scene.skeletonsEnabled = element.checked;
  27362. });
  27363. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27364. _this._scene.spritesEnabled = element.checked;
  27365. });
  27366. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27367. _this._scene.texturesEnabled = element.checked;
  27368. });
  27369. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27370. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27371. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27372. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", true, function (element) {
  27373. if (element.checked) {
  27374. _this._scene.switchAudioModeForHeadphones();
  27375. }
  27376. });
  27377. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", false, function (element) {
  27378. if (element.checked) {
  27379. _this._scene.switchAudioModeForNormalSpeakers();
  27380. }
  27381. });
  27382. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27383. _this._scene.audioEnabled = !element.checked;
  27384. });
  27385. }
  27386. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27387. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27388. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27389. _this._scene.dumpNextRenderTargets = true;
  27390. });
  27391. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27392. this._globalDiv.appendChild(this._statsDiv);
  27393. this._globalDiv.appendChild(this._logDiv);
  27394. this._globalDiv.appendChild(this._optionsDiv);
  27395. this._globalDiv.appendChild(this._treeDiv);
  27396. }
  27397. };
  27398. DebugLayer.prototype._displayStats = function () {
  27399. var scene = this._scene;
  27400. var engine = scene.getEngine();
  27401. var glInfo = engine.getGlInfo();
  27402. 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>";
  27403. if (this.customStatsFunction) {
  27404. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27405. }
  27406. };
  27407. return DebugLayer;
  27408. })();
  27409. BABYLON.DebugLayer = DebugLayer;
  27410. })(BABYLON || (BABYLON = {}));
  27411. //# sourceMappingURL=babylon.debugLayer.js.map
  27412. var BABYLON;
  27413. (function (BABYLON) {
  27414. var RawTexture = (function (_super) {
  27415. __extends(RawTexture, _super);
  27416. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27417. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27418. if (invertY === void 0) { invertY = false; }
  27419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27420. _super.call(this, null, scene, !generateMipMaps, invertY);
  27421. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27422. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27423. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27424. }
  27425. // Statics
  27426. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27427. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27428. if (invertY === void 0) { invertY = false; }
  27429. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27430. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27431. };
  27432. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27433. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27434. if (invertY === void 0) { invertY = false; }
  27435. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27436. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27437. };
  27438. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27439. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27440. if (invertY === void 0) { invertY = false; }
  27441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27442. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27443. };
  27444. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27445. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27446. if (invertY === void 0) { invertY = false; }
  27447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27448. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27449. };
  27450. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27451. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27452. if (invertY === void 0) { invertY = false; }
  27453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27454. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27455. };
  27456. return RawTexture;
  27457. })(BABYLON.Texture);
  27458. BABYLON.RawTexture = RawTexture;
  27459. })(BABYLON || (BABYLON = {}));
  27460. //# sourceMappingURL=babylon.rawTexture.js.map
  27461. var BABYLON;
  27462. (function (BABYLON) {
  27463. var IndexedVector2 = (function (_super) {
  27464. __extends(IndexedVector2, _super);
  27465. function IndexedVector2(original, index) {
  27466. _super.call(this, original.x, original.y);
  27467. this.index = index;
  27468. }
  27469. return IndexedVector2;
  27470. })(BABYLON.Vector2);
  27471. var PolygonPoints = (function () {
  27472. function PolygonPoints() {
  27473. this.elements = new Array();
  27474. }
  27475. PolygonPoints.prototype.add = function (originalPoints) {
  27476. var _this = this;
  27477. var result = new Array();
  27478. originalPoints.forEach(function (point) {
  27479. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  27480. var newPoint = new IndexedVector2(point, _this.elements.length);
  27481. result.push(newPoint);
  27482. _this.elements.push(newPoint);
  27483. }
  27484. });
  27485. return result;
  27486. };
  27487. PolygonPoints.prototype.computeBounds = function () {
  27488. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27489. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27490. this.elements.forEach(function (point) {
  27491. // x
  27492. if (point.x < lmin.x) {
  27493. lmin.x = point.x;
  27494. }
  27495. else if (point.x > lmax.x) {
  27496. lmax.x = point.x;
  27497. }
  27498. // y
  27499. if (point.y < lmin.y) {
  27500. lmin.y = point.y;
  27501. }
  27502. else if (point.y > lmax.y) {
  27503. lmax.y = point.y;
  27504. }
  27505. });
  27506. return {
  27507. min: lmin,
  27508. max: lmax,
  27509. width: lmax.x - lmin.x,
  27510. height: lmax.y - lmin.y
  27511. };
  27512. };
  27513. return PolygonPoints;
  27514. })();
  27515. var Polygon = (function () {
  27516. function Polygon() {
  27517. }
  27518. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27519. return [
  27520. new BABYLON.Vector2(xmin, ymin),
  27521. new BABYLON.Vector2(xmax, ymin),
  27522. new BABYLON.Vector2(xmax, ymax),
  27523. new BABYLON.Vector2(xmin, ymax)
  27524. ];
  27525. };
  27526. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27527. if (cx === void 0) { cx = 0; }
  27528. if (cy === void 0) { cy = 0; }
  27529. if (numberOfSides === void 0) { numberOfSides = 32; }
  27530. var result = new Array();
  27531. var angle = 0;
  27532. var increment = (Math.PI * 2) / numberOfSides;
  27533. for (var i = 0; i < numberOfSides; i++) {
  27534. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27535. angle -= increment;
  27536. }
  27537. return result;
  27538. };
  27539. Polygon.Parse = function (input) {
  27540. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27541. var i, result = [];
  27542. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27543. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27544. }
  27545. return result;
  27546. };
  27547. Polygon.StartingAt = function (x, y) {
  27548. return BABYLON.Path2.StartingAt(x, y);
  27549. };
  27550. return Polygon;
  27551. })();
  27552. BABYLON.Polygon = Polygon;
  27553. var PolygonMeshBuilder = (function () {
  27554. function PolygonMeshBuilder(name, contours, scene) {
  27555. this._points = new PolygonPoints();
  27556. if (!("poly2tri" in window)) {
  27557. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27558. }
  27559. this._name = name;
  27560. this._scene = scene;
  27561. var points;
  27562. if (contours instanceof BABYLON.Path2) {
  27563. points = contours.getPoints();
  27564. }
  27565. else {
  27566. points = contours;
  27567. }
  27568. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27569. }
  27570. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27571. this._swctx.addHole(this._points.add(hole));
  27572. return this;
  27573. };
  27574. PolygonMeshBuilder.prototype.build = function (updatable) {
  27575. if (updatable === void 0) { updatable = false; }
  27576. var result = new BABYLON.Mesh(this._name, this._scene);
  27577. var normals = [];
  27578. var positions = [];
  27579. var uvs = [];
  27580. var bounds = this._points.computeBounds();
  27581. this._points.elements.forEach(function (p) {
  27582. normals.push(0, 1.0, 0);
  27583. positions.push(p.x, 0, p.y);
  27584. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27585. });
  27586. var indices = [];
  27587. this._swctx.triangulate();
  27588. this._swctx.getTriangles().forEach(function (triangle) {
  27589. triangle.getPoints().forEach(function (point) {
  27590. indices.push(point.index);
  27591. });
  27592. });
  27593. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27594. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27595. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27596. result.setIndices(indices);
  27597. return result;
  27598. };
  27599. return PolygonMeshBuilder;
  27600. })();
  27601. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27602. })(BABYLON || (BABYLON = {}));
  27603. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27604. (function (BABYLON) {
  27605. var SimplificationSettings = (function () {
  27606. function SimplificationSettings(quality, distance) {
  27607. this.quality = quality;
  27608. this.distance = distance;
  27609. }
  27610. return SimplificationSettings;
  27611. })();
  27612. BABYLON.SimplificationSettings = SimplificationSettings;
  27613. var SimplificationQueue = (function () {
  27614. function SimplificationQueue() {
  27615. this.running = false;
  27616. this._simplificationArray = [];
  27617. }
  27618. SimplificationQueue.prototype.addTask = function (task) {
  27619. this._simplificationArray.push(task);
  27620. };
  27621. SimplificationQueue.prototype.executeNext = function () {
  27622. var task = this._simplificationArray.pop();
  27623. if (task) {
  27624. this.running = true;
  27625. this.runSimplification(task);
  27626. }
  27627. else {
  27628. this.running = false;
  27629. }
  27630. };
  27631. SimplificationQueue.prototype.runSimplification = function (task) {
  27632. var _this = this;
  27633. function setLODLevel(distance, mesh) {
  27634. }
  27635. if (task.parallelProcessing) {
  27636. //parallel simplifier
  27637. task.settings.forEach(function (setting) {
  27638. var simplifier = _this.getSimplifier(task);
  27639. simplifier.simplify(setting, function (newMesh) {
  27640. task.mesh.addLODLevel(setting.distance, newMesh);
  27641. //check if it is the last
  27642. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  27643. //all done, run the success callback.
  27644. task.successCallback();
  27645. }
  27646. _this.executeNext();
  27647. });
  27648. });
  27649. }
  27650. else {
  27651. //single simplifier.
  27652. var simplifier = this.getSimplifier(task);
  27653. var runDecimation = function (setting, callback) {
  27654. simplifier.simplify(setting, function (newMesh) {
  27655. task.mesh.addLODLevel(setting.distance, newMesh);
  27656. //run the next quality level
  27657. callback();
  27658. });
  27659. };
  27660. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  27661. runDecimation(task.settings[loop.index], function () {
  27662. loop.executeNext();
  27663. });
  27664. }, function () {
  27665. //execution ended, run the success callback.
  27666. if (task.successCallback) {
  27667. task.successCallback();
  27668. }
  27669. _this.executeNext();
  27670. });
  27671. }
  27672. };
  27673. SimplificationQueue.prototype.getSimplifier = function (task) {
  27674. switch (task.simplificationType) {
  27675. case 0 /* QUADRATIC */:
  27676. default:
  27677. return new QuadraticErrorSimplification(task.mesh);
  27678. }
  27679. };
  27680. return SimplificationQueue;
  27681. })();
  27682. BABYLON.SimplificationQueue = SimplificationQueue;
  27683. /**
  27684. * The implemented types of simplification.
  27685. * At the moment only Quadratic Error Decimation is implemented.
  27686. */
  27687. (function (SimplificationType) {
  27688. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  27689. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  27690. var SimplificationType = BABYLON.SimplificationType;
  27691. var DecimationTriangle = (function () {
  27692. function DecimationTriangle(vertices) {
  27693. this.vertices = vertices;
  27694. this.error = new Array(4);
  27695. this.deleted = false;
  27696. this.isDirty = false;
  27697. this.borderFactor = 0;
  27698. }
  27699. return DecimationTriangle;
  27700. })();
  27701. BABYLON.DecimationTriangle = DecimationTriangle;
  27702. var DecimationVertex = (function () {
  27703. function DecimationVertex(position, normal, uv, id) {
  27704. this.position = position;
  27705. this.normal = normal;
  27706. this.uv = uv;
  27707. this.id = id;
  27708. this.isBorder = true;
  27709. this.q = new QuadraticMatrix();
  27710. this.triangleCount = 0;
  27711. this.triangleStart = 0;
  27712. }
  27713. return DecimationVertex;
  27714. })();
  27715. BABYLON.DecimationVertex = DecimationVertex;
  27716. var QuadraticMatrix = (function () {
  27717. function QuadraticMatrix(data) {
  27718. this.data = new Array(10);
  27719. for (var i = 0; i < 10; ++i) {
  27720. if (data && data[i]) {
  27721. this.data[i] = data[i];
  27722. }
  27723. else {
  27724. this.data[i] = 0;
  27725. }
  27726. }
  27727. }
  27728. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27729. 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];
  27730. return det;
  27731. };
  27732. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27733. for (var i = 0; i < 10; ++i) {
  27734. this.data[i] += matrix.data[i];
  27735. }
  27736. };
  27737. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27738. for (var i = 0; i < 10; ++i) {
  27739. this.data[i] += data[i];
  27740. }
  27741. };
  27742. QuadraticMatrix.prototype.add = function (matrix) {
  27743. var m = new QuadraticMatrix();
  27744. for (var i = 0; i < 10; ++i) {
  27745. m.data[i] = this.data[i] + matrix.data[i];
  27746. }
  27747. return m;
  27748. };
  27749. QuadraticMatrix.FromData = function (a, b, c, d) {
  27750. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27751. };
  27752. //returning an array to avoid garbage collection
  27753. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  27754. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  27755. };
  27756. return QuadraticMatrix;
  27757. })();
  27758. BABYLON.QuadraticMatrix = QuadraticMatrix;
  27759. var Reference = (function () {
  27760. function Reference(vertexId, triangleId) {
  27761. this.vertexId = vertexId;
  27762. this.triangleId = triangleId;
  27763. }
  27764. return Reference;
  27765. })();
  27766. BABYLON.Reference = Reference;
  27767. /**
  27768. * An implementation of the Quadratic Error simplification algorithm.
  27769. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  27770. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  27771. * @author RaananW
  27772. */
  27773. var QuadraticErrorSimplification = (function () {
  27774. function QuadraticErrorSimplification(_mesh) {
  27775. this._mesh = _mesh;
  27776. this.initialised = false;
  27777. this.syncIterations = 5000;
  27778. this.aggressiveness = 7;
  27779. this.decimationIterations = 100;
  27780. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  27781. }
  27782. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  27783. var _this = this;
  27784. this.initDecimatedMesh();
  27785. //iterating through the submeshes array, one after the other.
  27786. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  27787. _this.initWithMesh(_this._mesh, loop.index, function () {
  27788. _this.runDecimation(settings, loop.index, function () {
  27789. loop.executeNext();
  27790. });
  27791. });
  27792. }, function () {
  27793. setTimeout(function () {
  27794. _this._reconstructedMesh.isVisible = true;
  27795. successCallback(_this._reconstructedMesh);
  27796. }, 0);
  27797. });
  27798. };
  27799. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  27800. var _this = this;
  27801. var gCount = 0;
  27802. triangle.vertices.forEach(function (vId) {
  27803. var count = 0;
  27804. var vPos = _this.vertices[vId].position;
  27805. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  27806. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  27807. ++count;
  27808. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  27809. ++count;
  27810. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  27811. ++count;
  27812. if (count > 1) {
  27813. ++gCount;
  27814. }
  27815. ;
  27816. });
  27817. if (gCount > 1) {
  27818. console.log(triangle, gCount);
  27819. }
  27820. return gCount > 1;
  27821. };
  27822. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  27823. var _this = this;
  27824. var targetCount = ~~(this.triangles.length * settings.quality);
  27825. var deletedTriangles = 0;
  27826. var triangleCount = this.triangles.length;
  27827. var iterationFunction = function (iteration, callback) {
  27828. setTimeout(function () {
  27829. if (iteration % 5 === 0) {
  27830. _this.updateMesh(iteration === 0);
  27831. }
  27832. for (var i = 0; i < _this.triangles.length; ++i) {
  27833. _this.triangles[i].isDirty = false;
  27834. }
  27835. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  27836. var trianglesIterator = function (i) {
  27837. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  27838. var t = _this.triangles[tIdx];
  27839. if (!t)
  27840. return;
  27841. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  27842. return;
  27843. }
  27844. for (var j = 0; j < 3; ++j) {
  27845. if (t.error[j] < threshold) {
  27846. var deleted0 = [];
  27847. var deleted1 = [];
  27848. var i0 = t.vertices[j];
  27849. var i1 = t.vertices[(j + 1) % 3];
  27850. var v0 = _this.vertices[i0];
  27851. var v1 = _this.vertices[i1];
  27852. if (v0.isBorder !== v1.isBorder)
  27853. continue;
  27854. var p = BABYLON.Vector3.Zero();
  27855. var n = BABYLON.Vector3.Zero();
  27856. var uv = BABYLON.Vector2.Zero();
  27857. var color = new BABYLON.Color4(0, 0, 0, 1);
  27858. _this.calculateError(v0, v1, p, n, uv, color);
  27859. var delTr = [];
  27860. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  27861. continue;
  27862. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  27863. continue;
  27864. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  27865. continue;
  27866. }
  27867. v0.normal = n;
  27868. if (v0.uv)
  27869. v0.uv = uv;
  27870. else if (v0.color)
  27871. v0.color = color;
  27872. v0.q = v1.q.add(v0.q);
  27873. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  27874. continue;
  27875. if (p.equals(v0.position))
  27876. continue;
  27877. v0.position = p;
  27878. var tStart = _this.references.length;
  27879. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  27880. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  27881. var tCount = _this.references.length - tStart;
  27882. if (tCount <= v0.triangleCount) {
  27883. if (tCount) {
  27884. for (var c = 0; c < tCount; c++) {
  27885. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  27886. }
  27887. }
  27888. }
  27889. else {
  27890. v0.triangleStart = tStart;
  27891. }
  27892. v0.triangleCount = tCount;
  27893. break;
  27894. }
  27895. }
  27896. };
  27897. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  27898. return (triangleCount - deletedTriangles <= targetCount);
  27899. });
  27900. }, 0);
  27901. };
  27902. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  27903. if (triangleCount - deletedTriangles <= targetCount)
  27904. loop.breakLoop();
  27905. else {
  27906. iterationFunction(loop.index, function () {
  27907. loop.executeNext();
  27908. });
  27909. }
  27910. }, function () {
  27911. setTimeout(function () {
  27912. //reconstruct this part of the mesh
  27913. _this.reconstructMesh(submeshIndex);
  27914. successCallback();
  27915. }, 0);
  27916. });
  27917. };
  27918. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  27919. var _this = this;
  27920. if (!mesh)
  27921. return;
  27922. this.vertices = [];
  27923. this.triangles = [];
  27924. this._mesh = mesh;
  27925. //It is assumed that a mesh has positions, normals and either uvs or colors.
  27926. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27927. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27928. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27929. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27930. var indices = mesh.getIndices();
  27931. var submesh = mesh.subMeshes[submeshIndex];
  27932. var vertexInit = function (i) {
  27933. var offset = i + submesh.verticesStart;
  27934. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  27935. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27936. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  27937. }
  27938. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27939. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  27940. }
  27941. _this.vertices.push(vertex);
  27942. };
  27943. //var totalVertices = mesh.getTotalVertices();
  27944. var totalVertices = submesh.verticesCount;
  27945. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  27946. var indicesInit = function (i) {
  27947. var offset = (submesh.indexStart / 3) + i;
  27948. var pos = (offset * 3);
  27949. var i0 = indices[pos + 0] - submesh.verticesStart;
  27950. var i1 = indices[pos + 1] - submesh.verticesStart;
  27951. var i2 = indices[pos + 2] - submesh.verticesStart;
  27952. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  27953. _this.triangles.push(triangle);
  27954. };
  27955. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  27956. _this.init(callback);
  27957. });
  27958. });
  27959. };
  27960. QuadraticErrorSimplification.prototype.init = function (callback) {
  27961. var _this = this;
  27962. var triangleInit1 = function (i) {
  27963. var t = _this.triangles[i];
  27964. 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();
  27965. for (var j = 0; j < 3; j++) {
  27966. _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))));
  27967. }
  27968. };
  27969. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  27970. var triangleInit2 = function (i) {
  27971. var t = _this.triangles[i];
  27972. for (var j = 0; j < 3; ++j) {
  27973. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  27974. }
  27975. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27976. };
  27977. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  27978. _this.initialised = true;
  27979. callback();
  27980. });
  27981. });
  27982. };
  27983. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  27984. var newTriangles = [];
  27985. var i;
  27986. for (i = 0; i < this.vertices.length; ++i) {
  27987. this.vertices[i].triangleCount = 0;
  27988. }
  27989. var t;
  27990. var j;
  27991. for (i = 0; i < this.triangles.length; ++i) {
  27992. if (!this.triangles[i].deleted) {
  27993. t = this.triangles[i];
  27994. for (j = 0; j < 3; ++j) {
  27995. this.vertices[t.vertices[j]].triangleCount = 1;
  27996. }
  27997. newTriangles.push(t);
  27998. }
  27999. }
  28000. var newVerticesOrder = [];
  28001. //compact vertices, get the IDs of the vertices used.
  28002. var dst = 0;
  28003. for (i = 0; i < this.vertices.length; ++i) {
  28004. if (this.vertices[i].triangleCount) {
  28005. this.vertices[i].triangleStart = dst;
  28006. this.vertices[dst].position = this.vertices[i].position;
  28007. this.vertices[dst].normal = this.vertices[i].normal;
  28008. this.vertices[dst].uv = this.vertices[i].uv;
  28009. this.vertices[dst].color = this.vertices[i].color;
  28010. newVerticesOrder.push(i);
  28011. dst++;
  28012. }
  28013. }
  28014. for (i = 0; i < newTriangles.length; ++i) {
  28015. t = newTriangles[i];
  28016. for (j = 0; j < 3; ++j) {
  28017. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  28018. }
  28019. }
  28020. this.vertices = this.vertices.slice(0, dst);
  28021. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28022. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28023. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28024. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28025. for (i = 0; i < newVerticesOrder.length; ++i) {
  28026. newPositionData.push(this.vertices[i].position.x);
  28027. newPositionData.push(this.vertices[i].position.y);
  28028. newPositionData.push(this.vertices[i].position.z);
  28029. newNormalData.push(this.vertices[i].normal.x);
  28030. newNormalData.push(this.vertices[i].normal.y);
  28031. newNormalData.push(this.vertices[i].normal.z);
  28032. if (this.vertices[i].uv) {
  28033. newUVsData.push(this.vertices[i].uv.x);
  28034. newUVsData.push(this.vertices[i].uv.y);
  28035. }
  28036. else if (this.vertices[i].color) {
  28037. newColorsData.push(this.vertices[i].color.r);
  28038. newColorsData.push(this.vertices[i].color.g);
  28039. newColorsData.push(this.vertices[i].color.b);
  28040. newColorsData.push(this.vertices[i].color.a);
  28041. }
  28042. }
  28043. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28044. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28045. var submeshesArray = this._reconstructedMesh.subMeshes;
  28046. this._reconstructedMesh.subMeshes = [];
  28047. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28048. for (i = 0; i < newTriangles.length; ++i) {
  28049. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  28050. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  28051. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  28052. }
  28053. //overwriting the old vertex buffers and indices.
  28054. this._reconstructedMesh.setIndices(newIndicesArray);
  28055. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28056. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28057. if (newUVsData.length > 0)
  28058. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28059. if (newColorsData.length > 0)
  28060. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28061. //create submesh
  28062. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28063. if (submeshIndex > 0) {
  28064. this._reconstructedMesh.subMeshes = [];
  28065. submeshesArray.forEach(function (submesh) {
  28066. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28067. });
  28068. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28069. }
  28070. };
  28071. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28072. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28073. this._reconstructedMesh.material = this._mesh.material;
  28074. this._reconstructedMesh.parent = this._mesh.parent;
  28075. this._reconstructedMesh.isVisible = false;
  28076. };
  28077. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  28078. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28079. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28080. if (t.deleted)
  28081. continue;
  28082. var s = this.references[vertex1.triangleStart + i].vertexId;
  28083. var id1 = t.vertices[(s + 1) % 3];
  28084. var id2 = t.vertices[(s + 2) % 3];
  28085. if ((id1 === index2 || id2 === index2)) {
  28086. deletedArray[i] = true;
  28087. delTr.push(t);
  28088. continue;
  28089. }
  28090. var d1 = this.vertices[id1].position.subtract(point);
  28091. d1 = d1.normalize();
  28092. var d2 = this.vertices[id2].position.subtract(point);
  28093. d2 = d2.normalize();
  28094. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28095. return true;
  28096. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28097. deletedArray[i] = false;
  28098. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28099. return true;
  28100. }
  28101. return false;
  28102. };
  28103. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  28104. var newDeleted = deletedTriangles;
  28105. for (var i = 0; i < vertex.triangleCount; ++i) {
  28106. var ref = this.references[vertex.triangleStart + i];
  28107. var t = this.triangles[ref.triangleId];
  28108. if (t.deleted)
  28109. continue;
  28110. if (deletedArray[i]) {
  28111. t.deleted = true;
  28112. newDeleted++;
  28113. continue;
  28114. }
  28115. t.vertices[ref.vertexId] = vertexId;
  28116. t.isDirty = true;
  28117. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  28118. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  28119. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  28120. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28121. this.references.push(ref);
  28122. }
  28123. return newDeleted;
  28124. };
  28125. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28126. for (var i = 0; i < this.vertices.length; ++i) {
  28127. var vCount = [];
  28128. var vId = [];
  28129. var v = this.vertices[i];
  28130. var j;
  28131. for (j = 0; j < v.triangleCount; ++j) {
  28132. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28133. for (var ii = 0; ii < 3; ii++) {
  28134. var ofs = 0;
  28135. var id = triangle.vertices[ii];
  28136. while (ofs < vCount.length) {
  28137. if (vId[ofs] === id)
  28138. break;
  28139. ++ofs;
  28140. }
  28141. if (ofs === vCount.length) {
  28142. vCount.push(1);
  28143. vId.push(id);
  28144. }
  28145. else {
  28146. vCount[ofs]++;
  28147. }
  28148. }
  28149. }
  28150. for (j = 0; j < vCount.length; ++j) {
  28151. if (vCount[j] === 1) {
  28152. this.vertices[vId[j]].isBorder = true;
  28153. }
  28154. else {
  28155. this.vertices[vId[j]].isBorder = false;
  28156. }
  28157. }
  28158. }
  28159. };
  28160. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28161. if (identifyBorders === void 0) { identifyBorders = false; }
  28162. var i;
  28163. if (!identifyBorders) {
  28164. var newTrianglesVector = [];
  28165. for (i = 0; i < this.triangles.length; ++i) {
  28166. if (!this.triangles[i].deleted) {
  28167. newTrianglesVector.push(this.triangles[i]);
  28168. }
  28169. }
  28170. this.triangles = newTrianglesVector;
  28171. }
  28172. for (i = 0; i < this.vertices.length; ++i) {
  28173. this.vertices[i].triangleCount = 0;
  28174. this.vertices[i].triangleStart = 0;
  28175. }
  28176. var t;
  28177. var j;
  28178. var v;
  28179. for (i = 0; i < this.triangles.length; ++i) {
  28180. t = this.triangles[i];
  28181. for (j = 0; j < 3; ++j) {
  28182. v = this.vertices[t.vertices[j]];
  28183. v.triangleCount++;
  28184. }
  28185. }
  28186. var tStart = 0;
  28187. for (i = 0; i < this.vertices.length; ++i) {
  28188. this.vertices[i].triangleStart = tStart;
  28189. tStart += this.vertices[i].triangleCount;
  28190. this.vertices[i].triangleCount = 0;
  28191. }
  28192. var newReferences = new Array(this.triangles.length * 3);
  28193. for (i = 0; i < this.triangles.length; ++i) {
  28194. t = this.triangles[i];
  28195. for (j = 0; j < 3; ++j) {
  28196. v = this.vertices[t.vertices[j]];
  28197. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28198. v.triangleCount++;
  28199. }
  28200. }
  28201. this.references = newReferences;
  28202. if (identifyBorders) {
  28203. this.identifyBorder();
  28204. }
  28205. };
  28206. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28207. var x = point.x;
  28208. var y = point.y;
  28209. var z = point.z;
  28210. 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];
  28211. };
  28212. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28213. var q = vertex1.q.add(vertex2.q);
  28214. var border = vertex1.isBorder && vertex2.isBorder;
  28215. var error = 0;
  28216. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28217. if (qDet !== 0 && !border) {
  28218. if (!pointResult) {
  28219. pointResult = BABYLON.Vector3.Zero();
  28220. }
  28221. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28222. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28223. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28224. error = this.vertexError(q, pointResult);
  28225. //TODO this should be correctly calculated
  28226. if (normalResult) {
  28227. normalResult.copyFrom(vertex1.normal);
  28228. if (vertex1.uv)
  28229. uvResult.copyFrom(vertex1.uv);
  28230. else if (vertex1.color)
  28231. colorResult.copyFrom(vertex1.color);
  28232. }
  28233. }
  28234. else {
  28235. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28236. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28237. var error1 = this.vertexError(q, vertex1.position);
  28238. var error2 = this.vertexError(q, vertex2.position);
  28239. var error3 = this.vertexError(q, p3);
  28240. error = Math.min(error1, error2, error3);
  28241. if (error === error1) {
  28242. if (pointResult) {
  28243. pointResult.copyFrom(vertex1.position);
  28244. normalResult.copyFrom(vertex1.normal);
  28245. if (vertex1.uv)
  28246. uvResult.copyFrom(vertex1.uv);
  28247. else if (vertex1.color)
  28248. colorResult.copyFrom(vertex1.color);
  28249. }
  28250. }
  28251. else if (error === error2) {
  28252. if (pointResult) {
  28253. pointResult.copyFrom(vertex2.position);
  28254. normalResult.copyFrom(vertex2.normal);
  28255. if (vertex2.uv)
  28256. uvResult.copyFrom(vertex2.uv);
  28257. else if (vertex2.color)
  28258. colorResult.copyFrom(vertex2.color);
  28259. }
  28260. }
  28261. else {
  28262. if (pointResult) {
  28263. pointResult.copyFrom(p3);
  28264. normalResult.copyFrom(vertex1.normal);
  28265. if (vertex1.uv)
  28266. uvResult.copyFrom(vertex1.uv);
  28267. else if (vertex1.color)
  28268. colorResult.copyFrom(vertex1.color);
  28269. }
  28270. }
  28271. }
  28272. return error;
  28273. };
  28274. return QuadraticErrorSimplification;
  28275. })();
  28276. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28277. })(BABYLON || (BABYLON = {}));
  28278. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28279. (function (BABYLON) {
  28280. var Analyser = (function () {
  28281. function Analyser(scene) {
  28282. this.SMOOTHING = 0.75;
  28283. this.FFT_SIZE = 512;
  28284. this.BARGRAPHAMPLITUDE = 256;
  28285. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28286. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28287. this._scene = scene;
  28288. this._audioEngine = BABYLON.Engine.audioEngine;
  28289. if (this._audioEngine.canUseWebAudio) {
  28290. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28291. this._webAudioAnalyser.minDecibels = -140;
  28292. this._webAudioAnalyser.maxDecibels = 0;
  28293. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28294. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28295. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28296. }
  28297. }
  28298. Analyser.prototype.getFrequencyBinCount = function () {
  28299. if (this._audioEngine.canUseWebAudio) {
  28300. return this._webAudioAnalyser.frequencyBinCount;
  28301. }
  28302. else {
  28303. return 0;
  28304. }
  28305. };
  28306. Analyser.prototype.getByteFrequencyData = function () {
  28307. if (this._audioEngine.canUseWebAudio) {
  28308. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28309. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28310. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28311. }
  28312. return this._byteFreqs;
  28313. };
  28314. Analyser.prototype.getByteTimeDomainData = function () {
  28315. if (this._audioEngine.canUseWebAudio) {
  28316. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28317. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28318. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28319. }
  28320. return this._byteTime;
  28321. };
  28322. Analyser.prototype.getFloatFrequencyData = function () {
  28323. if (this._audioEngine.canUseWebAudio) {
  28324. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28325. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28326. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28327. }
  28328. return this._floatFreqs;
  28329. };
  28330. Analyser.prototype.drawDebugCanvas = function () {
  28331. var _this = this;
  28332. if (this._audioEngine.canUseWebAudio) {
  28333. if (!this._debugCanvas) {
  28334. this._debugCanvas = document.createElement("canvas");
  28335. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28336. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28337. this._debugCanvas.style.position = "absolute";
  28338. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28339. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28340. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28341. document.body.appendChild(this._debugCanvas);
  28342. this._registerFunc = function () {
  28343. _this.drawDebugCanvas();
  28344. };
  28345. this._scene.registerBeforeRender(this._registerFunc);
  28346. }
  28347. if (this._registerFunc) {
  28348. var workingArray = this.getByteFrequencyData();
  28349. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28350. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28351. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28352. var value = workingArray[i];
  28353. var percent = value / this.BARGRAPHAMPLITUDE;
  28354. var height = this.DEBUGCANVASSIZE.height * percent;
  28355. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28356. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28357. var hue = i / this.getFrequencyBinCount() * 360;
  28358. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28359. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28360. }
  28361. }
  28362. }
  28363. };
  28364. Analyser.prototype.stopDebugCanvas = function () {
  28365. if (this._debugCanvas) {
  28366. this._scene.unregisterBeforeRender(this._registerFunc);
  28367. this._registerFunc = null;
  28368. document.body.removeChild(this._debugCanvas);
  28369. this._debugCanvas = null;
  28370. this._debugCanvasContext = null;
  28371. }
  28372. };
  28373. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28374. if (this._audioEngine.canUseWebAudio) {
  28375. inputAudioNode.connect(this._webAudioAnalyser);
  28376. this._webAudioAnalyser.connect(outputAudioNode);
  28377. }
  28378. };
  28379. Analyser.prototype.dispose = function () {
  28380. if (this._audioEngine.canUseWebAudio) {
  28381. this._webAudioAnalyser.disconnect();
  28382. }
  28383. };
  28384. return Analyser;
  28385. })();
  28386. BABYLON.Analyser = Analyser;
  28387. })(BABYLON || (BABYLON = {}));
  28388. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28389. (function (BABYLON) {
  28390. var DepthRenderer = (function () {
  28391. function DepthRenderer(scene, type) {
  28392. var _this = this;
  28393. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28394. this._viewMatrix = BABYLON.Matrix.Zero();
  28395. this._projectionMatrix = BABYLON.Matrix.Zero();
  28396. this._transformMatrix = BABYLON.Matrix.Zero();
  28397. this._worldViewProjection = BABYLON.Matrix.Zero();
  28398. this._scene = scene;
  28399. var engine = scene.getEngine();
  28400. // Render target
  28401. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28402. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28403. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28404. this._depthMap.refreshRate = 1;
  28405. this._depthMap.renderParticles = false;
  28406. this._depthMap.renderList = null;
  28407. // Custom render function
  28408. var renderSubMesh = function (subMesh) {
  28409. var mesh = subMesh.getRenderingMesh();
  28410. var scene = _this._scene;
  28411. var engine = scene.getEngine();
  28412. // Culling
  28413. engine.setState(subMesh.getMaterial().backFaceCulling);
  28414. // Managing instances
  28415. var batch = mesh._getInstancesRenderList(subMesh._id);
  28416. if (batch.mustReturn) {
  28417. return;
  28418. }
  28419. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28420. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28421. engine.enableEffect(_this._effect);
  28422. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28423. var material = subMesh.getMaterial();
  28424. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28425. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28426. // Alpha test
  28427. if (material && material.needAlphaTesting()) {
  28428. var alphaTexture = material.getAlphaTestTexture();
  28429. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28430. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28431. }
  28432. // Bones
  28433. if (mesh.useBones) {
  28434. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28435. }
  28436. // Draw
  28437. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28438. }
  28439. };
  28440. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28441. var index;
  28442. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28443. renderSubMesh(opaqueSubMeshes.data[index]);
  28444. }
  28445. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28446. renderSubMesh(alphaTestSubMeshes.data[index]);
  28447. }
  28448. };
  28449. }
  28450. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  28451. var defines = [];
  28452. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28453. var mesh = subMesh.getMesh();
  28454. var scene = mesh.getScene();
  28455. var material = subMesh.getMaterial();
  28456. // Alpha test
  28457. if (material && material.needAlphaTesting()) {
  28458. defines.push("#define ALPHATEST");
  28459. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28460. attribs.push(BABYLON.VertexBuffer.UVKind);
  28461. defines.push("#define UV1");
  28462. }
  28463. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28464. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28465. defines.push("#define UV2");
  28466. }
  28467. }
  28468. // Bones
  28469. if (mesh.useBones) {
  28470. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28471. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28472. defines.push("#define BONES");
  28473. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28474. }
  28475. // Instances
  28476. if (useInstances) {
  28477. defines.push("#define INSTANCES");
  28478. attribs.push("world0");
  28479. attribs.push("world1");
  28480. attribs.push("world2");
  28481. attribs.push("world3");
  28482. }
  28483. // Get correct effect
  28484. var join = defines.join("\n");
  28485. if (this._cachedDefines !== join) {
  28486. this._cachedDefines = join;
  28487. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  28488. }
  28489. return this._effect.isReady();
  28490. };
  28491. DepthRenderer.prototype.getDepthMap = function () {
  28492. return this._depthMap;
  28493. };
  28494. // Methods
  28495. DepthRenderer.prototype.dispose = function () {
  28496. this._depthMap.dispose();
  28497. };
  28498. return DepthRenderer;
  28499. })();
  28500. BABYLON.DepthRenderer = DepthRenderer;
  28501. })(BABYLON || (BABYLON = {}));
  28502. //# sourceMappingURL=babylon.depthRenderer.js.map
  28503. var BABYLON;
  28504. (function (BABYLON) {
  28505. var SSAORenderingPipeline = (function (_super) {
  28506. __extends(SSAORenderingPipeline, _super);
  28507. /**
  28508. * @constructor
  28509. * @param {string} name - The rendering pipeline name
  28510. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28511. * @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)
  28512. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28513. */
  28514. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  28515. var _this = this;
  28516. _super.call(this, scene.getEngine(), name);
  28517. // Members
  28518. /**
  28519. * The PassPostProcess id in the pipeline that contains the original scene color
  28520. * @type {string}
  28521. */
  28522. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  28523. /**
  28524. * The SSAO PostProcess id in the pipeline
  28525. * @type {string}
  28526. */
  28527. this.SSAORenderEffect = "SSAORenderEffect";
  28528. /**
  28529. * The horizontal blur PostProcess id in the pipeline
  28530. * @type {string}
  28531. */
  28532. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  28533. /**
  28534. * The vertical blur PostProcess id in the pipeline
  28535. * @type {string}
  28536. */
  28537. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  28538. /**
  28539. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  28540. * @type {string}
  28541. */
  28542. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  28543. this._firstUpdate = true;
  28544. this._scene = scene;
  28545. // Set up assets
  28546. this._createRandomTexture();
  28547. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28548. var ssaoRatio = ratio.ssaoRatio || ratio;
  28549. var combineRatio = ratio.combineRatio || ratio;
  28550. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28551. this._createSSAOPostProcess(ssaoRatio);
  28552. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28553. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28554. this._createSSAOCombinePostProcess(combineRatio);
  28555. // Set up pipeline
  28556. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  28557. return _this._originalColorPostProcess;
  28558. }, true));
  28559. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  28560. return _this._ssaoPostProcess;
  28561. }, true));
  28562. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  28563. return _this._blurHPostProcess;
  28564. }, true));
  28565. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  28566. return _this._blurVPostProcess;
  28567. }, true));
  28568. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  28569. return _this._ssaoCombinePostProcess;
  28570. }, true));
  28571. // Finish
  28572. scene.postProcessRenderPipelineManager.addPipeline(this);
  28573. if (cameras)
  28574. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28575. }
  28576. // Public Methods
  28577. /**
  28578. * Returns the horizontal blur PostProcess
  28579. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  28580. */
  28581. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  28582. return this._blurHPostProcess;
  28583. };
  28584. /**
  28585. * Returns the vertical blur PostProcess
  28586. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  28587. */
  28588. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  28589. return this._blurVPostProcess;
  28590. };
  28591. /**
  28592. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  28593. */
  28594. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28595. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28596. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28597. this._originalColorPostProcess = undefined;
  28598. this._ssaoPostProcess = undefined;
  28599. this._blurHPostProcess = undefined;
  28600. this._blurVPostProcess = undefined;
  28601. this._ssaoCombinePostProcess = undefined;
  28602. this._randomTexture.dispose();
  28603. if (disableDepthRender)
  28604. this._scene.disableDepthRenderer();
  28605. };
  28606. // Private Methods
  28607. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28608. var _this = this;
  28609. var sampleSphere = [
  28610. 0.5381,
  28611. 0.1856,
  28612. -0.4319,
  28613. 0.1379,
  28614. 0.2486,
  28615. 0.4430,
  28616. 0.3371,
  28617. 0.5679,
  28618. -0.0057,
  28619. -0.6999,
  28620. -0.0451,
  28621. -0.0019,
  28622. 0.0689,
  28623. -0.1598,
  28624. -0.8547,
  28625. 0.0560,
  28626. 0.0069,
  28627. -0.1843,
  28628. -0.0146,
  28629. 0.1402,
  28630. 0.0762,
  28631. 0.0100,
  28632. -0.1924,
  28633. -0.0344,
  28634. -0.3577,
  28635. -0.5301,
  28636. -0.4358,
  28637. -0.3169,
  28638. 0.1063,
  28639. 0.0158,
  28640. 0.0103,
  28641. -0.5869,
  28642. 0.0046,
  28643. -0.0897,
  28644. -0.4940,
  28645. 0.3287,
  28646. 0.7119,
  28647. -0.0154,
  28648. -0.0918,
  28649. -0.0533,
  28650. 0.0596,
  28651. -0.5411,
  28652. 0.0352,
  28653. -0.0631,
  28654. 0.5460,
  28655. -0.4776,
  28656. 0.2847,
  28657. -0.0271
  28658. ];
  28659. var samplesFactor = 1.0 / 16.0;
  28660. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28661. this._ssaoPostProcess.onApply = function (effect) {
  28662. if (_this._firstUpdate) {
  28663. effect.setArray3("sampleSphere", sampleSphere);
  28664. effect.setFloat("samplesFactor", samplesFactor);
  28665. effect.setFloat("randTextureTiles", 4.0 / ratio);
  28666. _this._firstUpdate = false;
  28667. }
  28668. effect.setTexture("textureSampler", _this._depthTexture);
  28669. effect.setTexture("randomSampler", _this._randomTexture);
  28670. };
  28671. };
  28672. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  28673. var _this = this;
  28674. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28675. this._ssaoCombinePostProcess.onApply = function (effect) {
  28676. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  28677. };
  28678. };
  28679. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  28680. var size = 512;
  28681. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28682. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28683. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28684. var context = this._randomTexture.getContext();
  28685. var rand = function (min, max) {
  28686. return Math.random() * (max - min) + min;
  28687. };
  28688. for (var x = 0; x < size; x++) {
  28689. for (var y = 0; y < size; y++) {
  28690. var randVector = BABYLON.Vector3.Zero();
  28691. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  28692. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  28693. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  28694. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  28695. context.fillRect(x, y, 1, 1);
  28696. }
  28697. }
  28698. this._randomTexture.update(false);
  28699. };
  28700. return SSAORenderingPipeline;
  28701. })(BABYLON.PostProcessRenderPipeline);
  28702. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  28703. })(BABYLON || (BABYLON = {}));
  28704. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  28705. var BABYLON;
  28706. (function (BABYLON) {
  28707. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  28708. var VolumetricLightScatteringPostProcess = (function (_super) {
  28709. __extends(VolumetricLightScatteringPostProcess, _super);
  28710. /**
  28711. * @constructor
  28712. * @param {string} name - The post-process name
  28713. * @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)
  28714. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  28715. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  28716. * @param {number} samples - The post-process quality, default 100
  28717. * @param {number} samplingMode - The post-process filtering mode
  28718. * @param {BABYLON.Engine} engine - The babylon engine
  28719. * @param {boolean} reusable - If the post-process is reusable
  28720. */
  28721. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  28722. var _this = this;
  28723. if (samples === void 0) { samples = 100; }
  28724. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28725. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28726. this._screenCoordinates = BABYLON.Vector2.Zero();
  28727. /**
  28728. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  28729. * @type {boolean}
  28730. */
  28731. this.useCustomMeshPosition = false;
  28732. /**
  28733. * If the post-process should inverse the light scattering direction
  28734. * @type {boolean}
  28735. */
  28736. this.invert = true;
  28737. /**
  28738. * Array containing the excluded meshes not rendered in the internal pass
  28739. */
  28740. this.excludedMeshes = new Array();
  28741. this.exposure = 0.3;
  28742. this.decay = 0.96815;
  28743. this.weight = 0.58767;
  28744. this.density = 0.926;
  28745. var scene = camera.getScene();
  28746. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  28747. // Configure mesh
  28748. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  28749. // Configure
  28750. this._createPass(scene, ratio.passRatio || ratio);
  28751. this.onApply = function (effect) {
  28752. _this._updateMeshScreenCoordinates(scene);
  28753. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  28754. effect.setFloat("exposure", _this.exposure);
  28755. effect.setFloat("decay", _this.decay);
  28756. effect.setFloat("weight", _this.weight);
  28757. effect.setFloat("density", _this.density);
  28758. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  28759. };
  28760. }
  28761. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  28762. var mesh = subMesh.getMesh();
  28763. var defines = [];
  28764. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28765. var material = subMesh.getMaterial();
  28766. // Render this.mesh as default
  28767. if (mesh === this.mesh) {
  28768. defines.push("#define BASIC_RENDER");
  28769. }
  28770. // Alpha test
  28771. if (material) {
  28772. if (material.needAlphaTesting() || mesh === this.mesh)
  28773. defines.push("#define ALPHATEST");
  28774. if (material.opacityTexture !== undefined)
  28775. defines.push("#define OPACITY");
  28776. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28777. attribs.push(BABYLON.VertexBuffer.UVKind);
  28778. defines.push("#define UV1");
  28779. }
  28780. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28781. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28782. defines.push("#define UV2");
  28783. }
  28784. }
  28785. // Bones
  28786. if (mesh.useBones) {
  28787. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28788. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28789. defines.push("#define BONES");
  28790. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28791. }
  28792. // Instances
  28793. if (useInstances) {
  28794. defines.push("#define INSTANCES");
  28795. attribs.push("world0");
  28796. attribs.push("world1");
  28797. attribs.push("world2");
  28798. attribs.push("world3");
  28799. }
  28800. // Get correct effect
  28801. var join = defines.join("\n");
  28802. if (this._cachedDefines !== join) {
  28803. this._cachedDefines = join;
  28804. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler", "opacitySampler"], join);
  28805. }
  28806. return this._volumetricLightScatteringPass.isReady();
  28807. };
  28808. /**
  28809. * Sets the new light position for light scattering effect
  28810. * @param {BABYLON.Vector3} The new custom light position
  28811. */
  28812. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  28813. this._customMeshPosition = position;
  28814. };
  28815. /**
  28816. * Returns the light position for light scattering effect
  28817. * @return {BABYLON.Vector3} The custom light position
  28818. */
  28819. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  28820. return this._customMeshPosition;
  28821. };
  28822. /**
  28823. * Disposes the internal assets and detaches the post-process from the camera
  28824. */
  28825. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  28826. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  28827. if (rttIndex !== -1) {
  28828. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  28829. }
  28830. this._volumetricLightScatteringRTT.dispose();
  28831. _super.prototype.dispose.call(this, camera);
  28832. };
  28833. /**
  28834. * Returns the render target texture used by the post-process
  28835. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  28836. */
  28837. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  28838. return this._volumetricLightScatteringRTT;
  28839. };
  28840. // Private methods
  28841. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  28842. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  28843. return true;
  28844. }
  28845. return false;
  28846. };
  28847. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  28848. var _this = this;
  28849. var engine = scene.getEngine();
  28850. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  28851. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28852. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28853. this._volumetricLightScatteringRTT.renderList = null;
  28854. this._volumetricLightScatteringRTT.renderParticles = false;
  28855. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  28856. // Custom render function for submeshes
  28857. var renderSubMesh = function (subMesh) {
  28858. var mesh = subMesh.getRenderingMesh();
  28859. if (_this._meshExcluded(mesh)) {
  28860. return;
  28861. }
  28862. var scene = mesh.getScene();
  28863. var engine = scene.getEngine();
  28864. // Culling
  28865. engine.setState(subMesh.getMaterial().backFaceCulling);
  28866. // Managing instances
  28867. var batch = mesh._getInstancesRenderList(subMesh._id);
  28868. if (batch.mustReturn) {
  28869. return;
  28870. }
  28871. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28872. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28873. engine.enableEffect(_this._volumetricLightScatteringPass);
  28874. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  28875. var material = subMesh.getMaterial();
  28876. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  28877. // Alpha test
  28878. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  28879. var alphaTexture = material.getAlphaTestTexture();
  28880. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  28881. if (_this.mesh.material && alphaTexture)
  28882. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28883. if (material.opacityTexture !== undefined)
  28884. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  28885. }
  28886. // Bones
  28887. if (mesh.useBones) {
  28888. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28889. }
  28890. // Draw
  28891. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  28892. }
  28893. };
  28894. // Render target texture callbacks
  28895. var savedSceneClearColor;
  28896. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28897. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  28898. savedSceneClearColor = scene.clearColor;
  28899. scene.clearColor = sceneClearColor;
  28900. };
  28901. this._volumetricLightScatteringRTT.onAfterRender = function () {
  28902. scene.clearColor = savedSceneClearColor;
  28903. };
  28904. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  28905. var index;
  28906. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28907. renderSubMesh(opaqueSubMeshes.data[index]);
  28908. }
  28909. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28910. renderSubMesh(alphaTestSubMeshes.data[index]);
  28911. }
  28912. for (index = 0; index < transparentSubMeshes.length; index++) {
  28913. renderSubMesh(transparentSubMeshes.data[index]);
  28914. }
  28915. };
  28916. };
  28917. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  28918. var transform = scene.getTransformMatrix();
  28919. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  28920. this._screenCoordinates.x = pos.x / this._viewPort.width;
  28921. this._screenCoordinates.y = pos.y / this._viewPort.height;
  28922. if (this.invert)
  28923. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  28924. };
  28925. // Static methods
  28926. /**
  28927. * Creates a default mesh for the Volumeric Light Scattering post-process
  28928. * @param {string} The mesh name
  28929. * @param {BABYLON.Scene} The scene where to create the mesh
  28930. * @return {BABYLON.Mesh} the default mesh
  28931. */
  28932. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  28933. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  28934. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  28935. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  28936. return mesh;
  28937. };
  28938. return VolumetricLightScatteringPostProcess;
  28939. })(BABYLON.PostProcess);
  28940. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  28941. })(BABYLON || (BABYLON = {}));
  28942. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  28943. var BABYLON;
  28944. (function (BABYLON) {
  28945. var LensRenderingPipeline = (function (_super) {
  28946. __extends(LensRenderingPipeline, _super);
  28947. /**
  28948. * @constructor
  28949. * @param {string} name - The rendering pipeline name
  28950. * @param {object} parameters - An object containing all parameters (see below)
  28951. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28952. * @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)
  28953. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28954. Effect parameters are as follow:
  28955. {
  28956. chromatic_aberration: number; // from 0 to x (1 for realism)
  28957. edge_blur: number; // from 0 to x (1 for realism)
  28958. distortion: number; // from 0 to x (1 for realism)
  28959. grain_amount: number; // from 0 to 1
  28960. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  28961. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  28962. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  28963. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  28964. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  28965. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  28966. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  28967. }
  28968. Note: if an effect parameter is unset, effect is disabled
  28969. */
  28970. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  28971. var _this = this;
  28972. if (ratio === void 0) { ratio = 1.0; }
  28973. _super.call(this, scene.getEngine(), name);
  28974. // Lens effects can be of the following:
  28975. // - chromatic aberration (slight shift of RGB colors)
  28976. // - blur on the edge of the lens
  28977. // - lens distortion
  28978. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  28979. // - grain/dust-on-lens effect
  28980. // Two additional texture samplers are needed:
  28981. // - depth map (for depth-of-field)
  28982. // - grain texture
  28983. /**
  28984. * The chromatic aberration PostProcess id in the pipeline
  28985. * @type {string}
  28986. */
  28987. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  28988. /**
  28989. * The depth-of-field PostProcess id in the pipeline
  28990. * @type {string}
  28991. */
  28992. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  28993. this._scene = scene;
  28994. // Fetch texture samplers
  28995. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28996. if (parameters.grain_texture) {
  28997. this._grainTexture = parameters.grain_texture;
  28998. }
  28999. else {
  29000. this._createGrainTexture();
  29001. }
  29002. // save parameters
  29003. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29004. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29005. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29006. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29007. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29008. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29009. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29010. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29011. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29012. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29013. // Create effects
  29014. this._createChromaticAberrationPostProcess(ratio);
  29015. this._createDepthOfFieldPostProcess(ratio);
  29016. // Set up pipeline
  29017. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29018. return _this._chromaticAberrationPostProcess;
  29019. }, true));
  29020. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29021. return _this._depthOfFieldPostProcess;
  29022. }, true));
  29023. // Finish
  29024. scene.postProcessRenderPipelineManager.addPipeline(this);
  29025. if (cameras) {
  29026. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29027. }
  29028. }
  29029. // public methods
  29030. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29031. this._edgeBlur = amount;
  29032. };
  29033. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29034. this._edgeBlur = 0;
  29035. };
  29036. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29037. this._grainAmount = amount;
  29038. };
  29039. LensRenderingPipeline.prototype.disableGrain = function () {
  29040. this._grainAmount = 0;
  29041. };
  29042. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29043. this._chromaticAberration = amount;
  29044. };
  29045. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29046. this._chromaticAberration = 0;
  29047. };
  29048. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29049. this._distortion = amount;
  29050. };
  29051. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29052. this._distortion = 0;
  29053. };
  29054. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29055. this._highlightsGain = amount;
  29056. };
  29057. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29058. this._highlightsThreshold = amount;
  29059. };
  29060. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29061. this._dofDepth = amount;
  29062. };
  29063. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29064. this._dofDepth = -1;
  29065. };
  29066. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29067. this._dofAperture = amount;
  29068. };
  29069. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29070. this._dofPentagon = true;
  29071. };
  29072. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29073. this._dofPentagon = false;
  29074. };
  29075. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29076. this._blurNoise = true;
  29077. };
  29078. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29079. this._blurNoise = false;
  29080. };
  29081. /**
  29082. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29083. */
  29084. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29085. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29086. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29087. this._chromaticAberrationPostProcess = undefined;
  29088. this._depthOfFieldPostProcess = undefined;
  29089. this._grainTexture.dispose();
  29090. if (disableDepthRender)
  29091. this._scene.disableDepthRenderer();
  29092. };
  29093. // colors shifting and distortion
  29094. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29095. var _this = this;
  29096. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29097. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29098. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29099. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29100. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29101. };
  29102. };
  29103. // colors shifting and distortion
  29104. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29105. var _this = this;
  29106. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29107. "gain",
  29108. "threshold",
  29109. "focus_depth",
  29110. "aperture",
  29111. "pentagon",
  29112. "maxZ",
  29113. "edge_blur",
  29114. "chromatic_aberration",
  29115. "distortion",
  29116. "blur_noise",
  29117. "grain_amount",
  29118. "screen_width",
  29119. "screen_height"
  29120. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29121. this._depthOfFieldPostProcess.onApply = function (effect) {
  29122. effect.setBool('pentagon', _this._dofPentagon);
  29123. effect.setBool('blur_noise', _this._blurNoise);
  29124. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29125. effect.setFloat('grain_amount', _this._grainAmount);
  29126. effect.setTexture("depthSampler", _this._depthTexture);
  29127. effect.setTexture("grainSampler", _this._grainTexture);
  29128. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29129. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29130. effect.setFloat('distortion', _this._distortion);
  29131. effect.setFloat('focus_depth', _this._dofDepth);
  29132. effect.setFloat('aperture', _this._dofAperture);
  29133. effect.setFloat('gain', _this._highlightsGain);
  29134. effect.setFloat('threshold', _this._highlightsThreshold);
  29135. effect.setFloat('edge_blur', _this._edgeBlur);
  29136. };
  29137. };
  29138. // creates a black and white random noise texture, 512x512
  29139. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29140. var size = 512;
  29141. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29142. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29143. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29144. var context = this._grainTexture.getContext();
  29145. var rand = function (min, max) {
  29146. return Math.random() * (max - min) + min;
  29147. };
  29148. var value;
  29149. for (var x = 0; x < size; x++) {
  29150. for (var y = 0; y < size; y++) {
  29151. value = Math.floor(rand(0.42, 0.58) * 255);
  29152. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29153. context.fillRect(x, y, 1, 1);
  29154. }
  29155. }
  29156. this._grainTexture.update(false);
  29157. };
  29158. return LensRenderingPipeline;
  29159. })(BABYLON.PostProcessRenderPipeline);
  29160. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29161. })(BABYLON || (BABYLON = {}));
  29162. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map