babylon.2.0-alpha.debug.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521
  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 (typeof r === "undefined") { r = 0; }
  11. if (typeof g === "undefined") { g = 0; }
  12. if (typeof b === "undefined") { 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. };
  29. Color3.prototype.toColor4 = function (alpha) {
  30. if (typeof alpha === "undefined") { alpha = 1; }
  31. return new Color4(this.r, this.g, this.b, alpha);
  32. };
  33. Color3.prototype.asArray = function () {
  34. var result = [];
  35. this.toArray(result, 0);
  36. return result;
  37. };
  38. Color3.prototype.toLuminance = function () {
  39. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  40. };
  41. Color3.prototype.multiply = function (otherColor) {
  42. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  43. };
  44. Color3.prototype.multiplyToRef = function (otherColor, result) {
  45. result.r = this.r * otherColor.r;
  46. result.g = this.g * otherColor.g;
  47. result.b = this.b * otherColor.b;
  48. };
  49. Color3.prototype.equals = function (otherColor) {
  50. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  51. };
  52. Color3.prototype.scale = function (scale) {
  53. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  54. };
  55. Color3.prototype.scaleToRef = function (scale, result) {
  56. result.r = this.r * scale;
  57. result.g = this.g * scale;
  58. result.b = this.b * scale;
  59. };
  60. Color3.prototype.add = function (otherColor) {
  61. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  62. };
  63. Color3.prototype.addToRef = function (otherColor, result) {
  64. result.r = this.r + otherColor.r;
  65. result.g = this.g + otherColor.g;
  66. result.b = this.b + otherColor.b;
  67. };
  68. Color3.prototype.subtract = function (otherColor) {
  69. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  70. };
  71. Color3.prototype.subtractToRef = function (otherColor, result) {
  72. result.r = this.r - otherColor.r;
  73. result.g = this.g - otherColor.g;
  74. result.b = this.b - otherColor.b;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. };
  84. Color3.prototype.copyFromFloats = function (r, g, b) {
  85. this.r = r;
  86. this.g = g;
  87. this.b = b;
  88. };
  89. // Statics
  90. Color3.FromArray = function (array) {
  91. return new Color3(array[0], array[1], array[2]);
  92. };
  93. Color3.FromInts = function (r, g, b) {
  94. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  95. };
  96. Color3.Lerp = function (start, end, amount) {
  97. var r = start.r + ((end.r - start.r) * amount);
  98. var g = start.g + ((end.g - start.g) * amount);
  99. var b = start.b + ((end.b - start.b) * amount);
  100. return new Color3(r, g, b);
  101. };
  102. Color3.Red = function () {
  103. return new Color3(1, 0, 0);
  104. };
  105. Color3.Green = function () {
  106. return new Color3(0, 1, 0);
  107. };
  108. Color3.Blue = function () {
  109. return new Color3(0, 0, 1);
  110. };
  111. Color3.Black = function () {
  112. return new Color3(0, 0, 0);
  113. };
  114. Color3.White = function () {
  115. return new Color3(1, 1, 1);
  116. };
  117. Color3.Purple = function () {
  118. return new Color3(0.5, 0, 0.5);
  119. };
  120. Color3.Magenta = function () {
  121. return new Color3(1, 0, 1);
  122. };
  123. Color3.Yellow = function () {
  124. return new Color3(1, 1, 0);
  125. };
  126. Color3.Gray = function () {
  127. return new Color3(0.5, 0.5, 0.5);
  128. };
  129. return Color3;
  130. })();
  131. BABYLON.Color3 = Color3;
  132. var Color4 = (function () {
  133. function Color4(r, g, b, a) {
  134. this.r = r;
  135. this.g = g;
  136. this.b = b;
  137. this.a = a;
  138. }
  139. // Operators
  140. Color4.prototype.addInPlace = function (right) {
  141. this.r += right.r;
  142. this.g += right.g;
  143. this.b += right.b;
  144. this.a += right.a;
  145. };
  146. Color4.prototype.asArray = function () {
  147. var result = [];
  148. this.toArray(result, 0);
  149. return result;
  150. };
  151. Color4.prototype.toArray = function (array, index) {
  152. if (index === undefined) {
  153. index = 0;
  154. }
  155. array[index] = this.r;
  156. array[index + 1] = this.g;
  157. array[index + 2] = this.b;
  158. array[index + 3] = this.a;
  159. };
  160. Color4.prototype.add = function (right) {
  161. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  162. };
  163. Color4.prototype.subtract = function (right) {
  164. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  165. };
  166. Color4.prototype.subtractToRef = function (right, result) {
  167. result.r = this.r - right.r;
  168. result.g = this.g - right.g;
  169. result.b = this.b - right.b;
  170. result.a = this.a - right.a;
  171. };
  172. Color4.prototype.scale = function (scale) {
  173. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  174. };
  175. Color4.prototype.scaleToRef = function (scale, result) {
  176. result.r = this.r * scale;
  177. result.g = this.g * scale;
  178. result.b = this.b * scale;
  179. result.a = this.a * scale;
  180. };
  181. Color4.prototype.toString = function () {
  182. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  183. };
  184. Color4.prototype.clone = function () {
  185. return new Color4(this.r, this.g, this.b, this.a);
  186. };
  187. Color4.prototype.copyFrom = function (source) {
  188. this.r = source.r;
  189. this.g = source.g;
  190. this.b = source.b;
  191. this.a = source.a;
  192. };
  193. // Statics
  194. Color4.Lerp = function (left, right, amount) {
  195. var result = new Color4(0, 0, 0, 0);
  196. Color4.LerpToRef(left, right, amount, result);
  197. return result;
  198. };
  199. Color4.LerpToRef = function (left, right, amount, result) {
  200. result.r = left.r + (right.r - left.r) * amount;
  201. result.g = left.g + (right.g - left.g) * amount;
  202. result.b = left.b + (right.b - left.b) * amount;
  203. result.a = left.a + (right.a - left.a) * amount;
  204. };
  205. Color4.FromArray = function (array, offset) {
  206. if (typeof offset === "undefined") { offset = 0; }
  207. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  208. };
  209. Color4.FromInts = function (r, g, b, a) {
  210. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  211. };
  212. return Color4;
  213. })();
  214. BABYLON.Color4 = Color4;
  215. var Vector2 = (function () {
  216. function Vector2(x, y) {
  217. this.x = x;
  218. this.y = y;
  219. }
  220. Vector2.prototype.toString = function () {
  221. return "{X: " + this.x + " Y:" + this.y + "}";
  222. };
  223. // Operators
  224. Vector2.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.x;
  229. array[index + 1] = this.y;
  230. };
  231. Vector2.prototype.asArray = function () {
  232. var result = [];
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. Vector2.prototype.copyFrom = function (source) {
  237. this.x = source.x;
  238. this.y = source.y;
  239. };
  240. Vector2.prototype.copyFromFloats = function (x, y) {
  241. this.x = x;
  242. this.y = y;
  243. };
  244. Vector2.prototype.add = function (otherVector) {
  245. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  246. };
  247. Vector2.prototype.addVector3 = function (otherVector) {
  248. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  249. };
  250. Vector2.prototype.subtract = function (otherVector) {
  251. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  252. };
  253. Vector2.prototype.subtractInPlace = function (otherVector) {
  254. this.x -= otherVector.x;
  255. this.y -= otherVector.y;
  256. };
  257. Vector2.prototype.multiplyInPlace = function (otherVector) {
  258. this.x *= otherVector.x;
  259. this.y *= otherVector.y;
  260. };
  261. Vector2.prototype.multiply = function (otherVector) {
  262. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  263. };
  264. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  265. result.x = this.x * otherVector.x;
  266. result.y = this.y * otherVector.y;
  267. };
  268. Vector2.prototype.multiplyByFloats = function (x, y) {
  269. return new Vector2(this.x * x, this.y * y);
  270. };
  271. Vector2.prototype.divide = function (otherVector) {
  272. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  273. };
  274. Vector2.prototype.divideToRef = function (otherVector, result) {
  275. result.x = this.x / otherVector.x;
  276. result.y = this.y / otherVector.y;
  277. };
  278. Vector2.prototype.negate = function () {
  279. return new Vector2(-this.x, -this.y);
  280. };
  281. Vector2.prototype.scaleInPlace = function (scale) {
  282. this.x *= scale;
  283. this.y *= scale;
  284. return this;
  285. };
  286. Vector2.prototype.scale = function (scale) {
  287. return new Vector2(this.x * scale, this.y * scale);
  288. };
  289. Vector2.prototype.equals = function (otherVector) {
  290. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  291. };
  292. // Properties
  293. Vector2.prototype.length = function () {
  294. return Math.sqrt(this.x * this.x + this.y * this.y);
  295. };
  296. Vector2.prototype.lengthSquared = function () {
  297. return (this.x * this.x + this.y * this.y);
  298. };
  299. // Methods
  300. Vector2.prototype.normalize = function () {
  301. var len = this.length();
  302. if (len === 0)
  303. return this;
  304. var num = 1.0 / len;
  305. this.x *= num;
  306. this.y *= num;
  307. return this;
  308. };
  309. Vector2.prototype.clone = function () {
  310. return new Vector2(this.x, this.y);
  311. };
  312. // Statics
  313. Vector2.Zero = function () {
  314. return new Vector2(0, 0);
  315. };
  316. Vector2.FromArray = function (array, offset) {
  317. if (!offset) {
  318. offset = 0;
  319. }
  320. return new Vector2(array[offset], array[offset + 1]);
  321. };
  322. Vector2.FromArrayToRef = function (array, offset, result) {
  323. result.x = array[offset];
  324. result.y = array[offset + 1];
  325. };
  326. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  327. var squared = amount * amount;
  328. var cubed = amount * squared;
  329. 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));
  330. 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));
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Clamp = function (value, min, max) {
  334. var x = value.x;
  335. x = (x > max.x) ? max.x : x;
  336. x = (x < min.x) ? min.x : x;
  337. var y = value.y;
  338. y = (y > max.y) ? max.y : y;
  339. y = (y < min.y) ? min.y : y;
  340. return new Vector2(x, y);
  341. };
  342. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  346. var part2 = (-2.0 * cubed) + (3.0 * squared);
  347. var part3 = (cubed - (2.0 * squared)) + amount;
  348. var part4 = cubed - squared;
  349. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  350. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  351. return new Vector2(x, y);
  352. };
  353. Vector2.Lerp = function (start, end, amount) {
  354. var x = start.x + ((end.x - start.x) * amount);
  355. var y = start.y + ((end.y - start.y) * amount);
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Dot = function (left, right) {
  359. return left.x * right.x + left.y * right.y;
  360. };
  361. Vector2.Normalize = function (vector) {
  362. var newVector = vector.clone();
  363. newVector.normalize();
  364. return newVector;
  365. };
  366. Vector2.Minimize = function (left, right) {
  367. var x = (left.x < right.x) ? left.x : right.x;
  368. var y = (left.y < right.y) ? left.y : right.y;
  369. return new Vector2(x, y);
  370. };
  371. Vector2.Maximize = function (left, right) {
  372. var x = (left.x > right.x) ? left.x : right.x;
  373. var y = (left.y > right.y) ? left.y : right.y;
  374. return new Vector2(x, y);
  375. };
  376. Vector2.Transform = function (vector, transformation) {
  377. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  378. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  379. return new Vector2(x, y);
  380. };
  381. Vector2.Distance = function (value1, value2) {
  382. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  383. };
  384. Vector2.DistanceSquared = function (value1, value2) {
  385. var x = value1.x - value2.x;
  386. var y = value1.y - value2.y;
  387. return (x * x) + (y * y);
  388. };
  389. return Vector2;
  390. })();
  391. BABYLON.Vector2 = Vector2;
  392. var Vector3 = (function () {
  393. function Vector3(x, y, z) {
  394. this.x = x;
  395. this.y = y;
  396. this.z = z;
  397. }
  398. Vector3.prototype.toString = function () {
  399. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  400. };
  401. // Operators
  402. Vector3.prototype.asArray = function () {
  403. var result = [];
  404. this.toArray(result, 0);
  405. return result;
  406. };
  407. Vector3.prototype.toArray = function (array, index) {
  408. if (index === undefined) {
  409. index = 0;
  410. }
  411. array[index] = this.x;
  412. array[index + 1] = this.y;
  413. array[index + 2] = this.z;
  414. };
  415. Vector3.prototype.addInPlace = function (otherVector) {
  416. this.x += otherVector.x;
  417. this.y += otherVector.y;
  418. this.z += otherVector.z;
  419. };
  420. Vector3.prototype.add = function (otherVector) {
  421. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  422. };
  423. Vector3.prototype.addToRef = function (otherVector, result) {
  424. result.x = this.x + otherVector.x;
  425. result.y = this.y + otherVector.y;
  426. result.z = this.z + otherVector.z;
  427. };
  428. Vector3.prototype.subtractInPlace = function (otherVector) {
  429. this.x -= otherVector.x;
  430. this.y -= otherVector.y;
  431. this.z -= otherVector.z;
  432. };
  433. Vector3.prototype.subtract = function (otherVector) {
  434. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  435. };
  436. Vector3.prototype.subtractToRef = function (otherVector, result) {
  437. result.x = this.x - otherVector.x;
  438. result.y = this.y - otherVector.y;
  439. result.z = this.z - otherVector.z;
  440. };
  441. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  442. return new Vector3(this.x - x, this.y - y, this.z - z);
  443. };
  444. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  445. result.x = this.x - x;
  446. result.y = this.y - y;
  447. result.z = this.z - z;
  448. };
  449. Vector3.prototype.negate = function () {
  450. return new Vector3(-this.x, -this.y, -this.z);
  451. };
  452. Vector3.prototype.scaleInPlace = function (scale) {
  453. this.x *= scale;
  454. this.y *= scale;
  455. this.z *= scale;
  456. return this;
  457. };
  458. Vector3.prototype.scale = function (scale) {
  459. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  460. };
  461. Vector3.prototype.scaleToRef = function (scale, result) {
  462. result.x = this.x * scale;
  463. result.y = this.y * scale;
  464. result.z = this.z * scale;
  465. };
  466. Vector3.prototype.equals = function (otherVector) {
  467. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  468. };
  469. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  470. 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;
  471. };
  472. Vector3.prototype.equalsToFloats = function (x, y, z) {
  473. return this.x === x && this.y === y && this.z === z;
  474. };
  475. Vector3.prototype.multiplyInPlace = function (otherVector) {
  476. this.x *= otherVector.x;
  477. this.y *= otherVector.y;
  478. this.z *= otherVector.z;
  479. };
  480. Vector3.prototype.multiply = function (otherVector) {
  481. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  482. };
  483. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  484. result.x = this.x * otherVector.x;
  485. result.y = this.y * otherVector.y;
  486. result.z = this.z * otherVector.z;
  487. };
  488. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  489. return new Vector3(this.x * x, this.y * y, this.z * z);
  490. };
  491. Vector3.prototype.divide = function (otherVector) {
  492. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  493. };
  494. Vector3.prototype.divideToRef = function (otherVector, result) {
  495. result.x = this.x / otherVector.x;
  496. result.y = this.y / otherVector.y;
  497. result.z = this.z / otherVector.z;
  498. };
  499. Vector3.prototype.MinimizeInPlace = function (other) {
  500. if (other.x < this.x)
  501. this.x = other.x;
  502. if (other.y < this.y)
  503. this.y = other.y;
  504. if (other.z < this.z)
  505. this.z = other.z;
  506. };
  507. Vector3.prototype.MaximizeInPlace = function (other) {
  508. if (other.x > this.x)
  509. this.x = other.x;
  510. if (other.y > this.y)
  511. this.y = other.y;
  512. if (other.z > this.z)
  513. this.z = other.z;
  514. };
  515. // Properties
  516. Vector3.prototype.length = function () {
  517. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  518. };
  519. Vector3.prototype.lengthSquared = function () {
  520. return (this.x * this.x + this.y * this.y + this.z * this.z);
  521. };
  522. // Methods
  523. Vector3.prototype.normalize = function () {
  524. var len = this.length();
  525. if (len === 0)
  526. return this;
  527. var num = 1.0 / len;
  528. this.x *= num;
  529. this.y *= num;
  530. this.z *= num;
  531. return this;
  532. };
  533. Vector3.prototype.clone = function () {
  534. return new Vector3(this.x, this.y, this.z);
  535. };
  536. Vector3.prototype.copyFrom = function (source) {
  537. this.x = source.x;
  538. this.y = source.y;
  539. this.z = source.z;
  540. };
  541. Vector3.prototype.copyFromFloats = function (x, y, z) {
  542. this.x = x;
  543. this.y = y;
  544. this.z = z;
  545. };
  546. // Statics
  547. Vector3.FromArray = function (array, offset) {
  548. if (!offset) {
  549. offset = 0;
  550. }
  551. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  552. };
  553. Vector3.FromArrayToRef = function (array, offset, result) {
  554. result.x = array[offset];
  555. result.y = array[offset + 1];
  556. result.z = array[offset + 2];
  557. };
  558. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  559. result.x = array[offset];
  560. result.y = array[offset + 1];
  561. result.z = array[offset + 2];
  562. };
  563. Vector3.FromFloatsToRef = function (x, y, z, result) {
  564. result.x = x;
  565. result.y = y;
  566. result.z = z;
  567. };
  568. Vector3.Zero = function () {
  569. return new Vector3(0, 0, 0);
  570. };
  571. Vector3.Up = function () {
  572. return new Vector3(0, 1.0, 0);
  573. };
  574. Vector3.TransformCoordinates = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  580. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  581. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  582. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  583. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  584. result.x = x / w;
  585. result.y = y / w;
  586. result.z = z / w;
  587. };
  588. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  589. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  590. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  591. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  592. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  593. result.x = rx / rw;
  594. result.y = ry / rw;
  595. result.z = rz / rw;
  596. };
  597. Vector3.TransformNormal = function (vector, transformation) {
  598. var result = Vector3.Zero();
  599. Vector3.TransformNormalToRef(vector, transformation, result);
  600. return result;
  601. };
  602. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  603. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  604. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  605. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  606. };
  607. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  608. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  609. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  610. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  611. };
  612. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  613. var squared = amount * amount;
  614. var cubed = amount * squared;
  615. 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));
  616. 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));
  617. 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));
  618. return new Vector3(x, y, z);
  619. };
  620. Vector3.Clamp = function (value, min, max) {
  621. var x = value.x;
  622. x = (x > max.x) ? max.x : x;
  623. x = (x < min.x) ? min.x : x;
  624. var y = value.y;
  625. y = (y > max.y) ? max.y : y;
  626. y = (y < min.y) ? min.y : y;
  627. var z = value.z;
  628. z = (z > max.z) ? max.z : z;
  629. z = (z < min.z) ? min.z : z;
  630. return new Vector3(x, y, z);
  631. };
  632. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  633. var squared = amount * amount;
  634. var cubed = amount * squared;
  635. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  636. var part2 = (-2.0 * cubed) + (3.0 * squared);
  637. var part3 = (cubed - (2.0 * squared)) + amount;
  638. var part4 = cubed - squared;
  639. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  640. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  641. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  642. return new Vector3(x, y, z);
  643. };
  644. Vector3.Lerp = function (start, end, amount) {
  645. var x = start.x + ((end.x - start.x) * amount);
  646. var y = start.y + ((end.y - start.y) * amount);
  647. var z = start.z + ((end.z - start.z) * amount);
  648. return new Vector3(x, y, z);
  649. };
  650. Vector3.Dot = function (left, right) {
  651. return (left.x * right.x + left.y * right.y + left.z * right.z);
  652. };
  653. Vector3.Cross = function (left, right) {
  654. var result = Vector3.Zero();
  655. Vector3.CrossToRef(left, right, result);
  656. return result;
  657. };
  658. Vector3.CrossToRef = function (left, right, result) {
  659. result.x = left.y * right.z - left.z * right.y;
  660. result.y = left.z * right.x - left.x * right.z;
  661. result.z = left.x * right.y - left.y * right.x;
  662. };
  663. Vector3.Normalize = function (vector) {
  664. var result = Vector3.Zero();
  665. Vector3.NormalizeToRef(vector, result);
  666. return result;
  667. };
  668. Vector3.NormalizeToRef = function (vector, result) {
  669. result.copyFrom(vector);
  670. result.normalize();
  671. };
  672. Vector3.Project = function (vector, world, transform, viewport) {
  673. var cw = viewport.width;
  674. var ch = viewport.height;
  675. var cx = viewport.x;
  676. var cy = viewport.y;
  677. 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);
  678. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  679. return Vector3.TransformCoordinates(vector, finalMatrix);
  680. };
  681. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  682. var matrix = world.multiply(transform);
  683. matrix.invert();
  684. source.x = source.x / viewportWidth * 2 - 1;
  685. source.y = -(source.y / viewportHeight * 2 - 1);
  686. var vector = Vector3.TransformCoordinates(source, matrix);
  687. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  688. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  689. vector = vector.scale(1.0 / num);
  690. }
  691. return vector;
  692. };
  693. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  694. var matrix = world.multiply(view).multiply(projection);
  695. matrix.invert();
  696. source.x = source.x / viewportWidth * 2 - 1;
  697. source.y = -(source.y / viewportHeight * 2 - 1);
  698. var vector = Vector3.TransformCoordinates(source, matrix);
  699. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  700. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  701. vector = vector.scale(1.0 / num);
  702. }
  703. return vector;
  704. };
  705. Vector3.Minimize = function (left, right) {
  706. var min = left.clone();
  707. min.MinimizeInPlace(right);
  708. return min;
  709. };
  710. Vector3.Maximize = function (left, right) {
  711. var max = left.clone();
  712. max.MaximizeInPlace(right);
  713. return max;
  714. };
  715. Vector3.Distance = function (value1, value2) {
  716. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  717. };
  718. Vector3.DistanceSquared = function (value1, value2) {
  719. var x = value1.x - value2.x;
  720. var y = value1.y - value2.y;
  721. var z = value1.z - value2.z;
  722. return (x * x) + (y * y) + (z * z);
  723. };
  724. Vector3.Center = function (value1, value2) {
  725. var center = value1.add(value2);
  726. center.scaleInPlace(0.5);
  727. return center;
  728. };
  729. return Vector3;
  730. })();
  731. BABYLON.Vector3 = Vector3;
  732. //Vector4 class created for EulerAngle class conversion to Quaternion
  733. var Vector4 = (function () {
  734. function Vector4(x, y, z, w) {
  735. this.x = x;
  736. this.y = y;
  737. this.z = z;
  738. this.w = w;
  739. }
  740. Vector4.prototype.toString = function () {
  741. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  742. };
  743. // Operators
  744. Vector4.prototype.asArray = function () {
  745. var result = [];
  746. this.toArray(result, 0);
  747. return result;
  748. };
  749. Vector4.prototype.toArray = function (array, index) {
  750. if (index === undefined) {
  751. index = 0;
  752. }
  753. array[index] = this.x;
  754. array[index + 1] = this.y;
  755. array[index + 2] = this.z;
  756. array[index + 3] = this.w;
  757. };
  758. Vector4.prototype.addInPlace = function (otherVector) {
  759. this.x += otherVector.x;
  760. this.y += otherVector.y;
  761. this.z += otherVector.z;
  762. this.w += otherVector.w;
  763. };
  764. Vector4.prototype.add = function (otherVector) {
  765. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  766. };
  767. Vector4.prototype.addToRef = function (otherVector, result) {
  768. result.x = this.x + otherVector.x;
  769. result.y = this.y + otherVector.y;
  770. result.z = this.z + otherVector.z;
  771. result.w = this.w + otherVector.w;
  772. };
  773. Vector4.prototype.subtractInPlace = function (otherVector) {
  774. this.x -= otherVector.x;
  775. this.y -= otherVector.y;
  776. this.z -= otherVector.z;
  777. this.w -= otherVector.w;
  778. };
  779. Vector4.prototype.subtract = function (otherVector) {
  780. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  781. };
  782. Vector4.prototype.subtractToRef = function (otherVector, result) {
  783. result.x = this.x - otherVector.x;
  784. result.y = this.y - otherVector.y;
  785. result.z = this.z - otherVector.z;
  786. result.w = this.w - otherVector.w;
  787. };
  788. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  789. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  790. };
  791. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  792. result.x = this.x - x;
  793. result.y = this.y - y;
  794. result.z = this.z - z;
  795. result.w = this.w - w;
  796. };
  797. Vector4.prototype.negate = function () {
  798. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  799. };
  800. Vector4.prototype.scaleInPlace = function (scale) {
  801. this.x *= scale;
  802. this.y *= scale;
  803. this.z *= scale;
  804. this.w *= scale;
  805. return this;
  806. };
  807. Vector4.prototype.scale = function (scale) {
  808. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  809. };
  810. Vector4.prototype.scaleToRef = function (scale, result) {
  811. result.x = this.x * scale;
  812. result.y = this.y * scale;
  813. result.z = this.z * scale;
  814. result.w = this.w * scale;
  815. };
  816. Vector4.prototype.equals = function (otherVector) {
  817. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  818. };
  819. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  820. 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;
  821. };
  822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  823. return this.x === x && this.y === y && this.z === z && this.w === w;
  824. };
  825. Vector4.prototype.multiplyInPlace = function (otherVector) {
  826. this.x *= otherVector.x;
  827. this.y *= otherVector.y;
  828. this.z *= otherVector.z;
  829. this.w *= otherVector.w;
  830. };
  831. Vector4.prototype.multiply = function (otherVector) {
  832. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  833. };
  834. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  835. result.x = this.x * otherVector.x;
  836. result.y = this.y * otherVector.y;
  837. result.z = this.z * otherVector.z;
  838. result.w = this.w * otherVector.w;
  839. };
  840. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  841. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  842. };
  843. Vector4.prototype.divide = function (otherVector) {
  844. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  845. };
  846. Vector4.prototype.divideToRef = function (otherVector, result) {
  847. result.x = this.x / otherVector.x;
  848. result.y = this.y / otherVector.y;
  849. result.z = this.z / otherVector.z;
  850. result.w = this.w / otherVector.w;
  851. };
  852. Vector4.prototype.MinimizeInPlace = function (other) {
  853. if (other.x < this.x)
  854. this.x = other.x;
  855. if (other.y < this.y)
  856. this.y = other.y;
  857. if (other.z < this.z)
  858. this.z = other.z;
  859. if (other.w < this.w)
  860. this.w = other.w;
  861. };
  862. Vector4.prototype.MaximizeInPlace = function (other) {
  863. if (other.x > this.x)
  864. this.x = other.x;
  865. if (other.y > this.y)
  866. this.y = other.y;
  867. if (other.z > this.z)
  868. this.z = other.z;
  869. if (other.w > this.w)
  870. this.w = other.w;
  871. };
  872. // Properties
  873. Vector4.prototype.length = function () {
  874. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  875. };
  876. Vector4.prototype.lengthSquared = function () {
  877. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  878. };
  879. // Methods
  880. Vector4.prototype.normalize = function () {
  881. var len = this.length();
  882. if (len === 0)
  883. return this;
  884. var num = 1.0 / len;
  885. this.x *= num;
  886. this.y *= num;
  887. this.z *= num;
  888. this.w *= num;
  889. return this;
  890. };
  891. Vector4.prototype.clone = function () {
  892. return new Vector4(this.x, this.y, this.z, this.w);
  893. };
  894. Vector4.prototype.copyFrom = function (source) {
  895. this.x = source.x;
  896. this.y = source.y;
  897. this.z = source.z;
  898. this.w = source.w;
  899. };
  900. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  901. this.x = x;
  902. this.y = y;
  903. this.z = z;
  904. this.w = w;
  905. };
  906. // Statics
  907. Vector4.FromArray = function (array, offset) {
  908. if (!offset) {
  909. offset = 0;
  910. }
  911. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  912. };
  913. Vector4.FromArrayToRef = function (array, offset, result) {
  914. result.x = array[offset];
  915. result.y = array[offset + 1];
  916. result.z = array[offset + 2];
  917. result.w = array[offset + 3];
  918. };
  919. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  920. result.x = array[offset];
  921. result.y = array[offset + 1];
  922. result.z = array[offset + 2];
  923. result.w = array[offset + 3];
  924. };
  925. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  926. result.x = x;
  927. result.y = y;
  928. result.z = z;
  929. result.w = w;
  930. };
  931. Vector4.Zero = function () {
  932. return new Vector4(0, 0, 0, 0);
  933. };
  934. Vector4.Normalize = function (vector) {
  935. var result = Vector4.Zero();
  936. Vector4.NormalizeToRef(vector, result);
  937. return result;
  938. };
  939. Vector4.NormalizeToRef = function (vector, result) {
  940. result.copyFrom(vector);
  941. result.normalize();
  942. };
  943. Vector4.Minimize = function (left, right) {
  944. var min = left.clone();
  945. min.MinimizeInPlace(right);
  946. return min;
  947. };
  948. Vector4.Maximize = function (left, right) {
  949. var max = left.clone();
  950. max.MaximizeInPlace(right);
  951. return max;
  952. };
  953. Vector4.Distance = function (value1, value2) {
  954. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  955. };
  956. Vector4.DistanceSquared = function (value1, value2) {
  957. var x = value1.x - value2.x;
  958. var y = value1.y - value2.y;
  959. var z = value1.z - value2.z;
  960. var w = value1.w - value2.w;
  961. return (x * x) + (y * y) + (z * z) + (w * w);
  962. };
  963. Vector4.Center = function (value1, value2) {
  964. var center = value1.add(value2);
  965. center.scaleInPlace(0.5);
  966. return center;
  967. };
  968. return Vector4;
  969. })();
  970. BABYLON.Vector4 = Vector4;
  971. var Quaternion = (function () {
  972. function Quaternion(x, y, z, w) {
  973. if (typeof x === "undefined") { x = 0; }
  974. if (typeof y === "undefined") { y = 0; }
  975. if (typeof z === "undefined") { z = 0; }
  976. if (typeof w === "undefined") { w = 1; }
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Quaternion.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  984. };
  985. Quaternion.prototype.asArray = function () {
  986. return [this.x, this.y, this.z, this.w];
  987. };
  988. Quaternion.prototype.equals = function (otherQuaternion) {
  989. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  990. };
  991. Quaternion.prototype.clone = function () {
  992. return new Quaternion(this.x, this.y, this.z, this.w);
  993. };
  994. Quaternion.prototype.copyFrom = function (other) {
  995. this.x = other.x;
  996. this.y = other.y;
  997. this.z = other.z;
  998. this.w = other.w;
  999. };
  1000. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1001. this.x = x;
  1002. this.y = y;
  1003. this.z = z;
  1004. this.w = w;
  1005. };
  1006. Quaternion.prototype.add = function (other) {
  1007. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1008. };
  1009. Quaternion.prototype.subtract = function (other) {
  1010. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1011. };
  1012. Quaternion.prototype.scale = function (value) {
  1013. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1014. };
  1015. Quaternion.prototype.multiply = function (q1) {
  1016. var result = new Quaternion(0, 0, 0, 1.0);
  1017. this.multiplyToRef(q1, result);
  1018. return result;
  1019. };
  1020. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1021. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1022. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1023. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1024. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1025. };
  1026. Quaternion.prototype.length = function () {
  1027. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1028. };
  1029. Quaternion.prototype.normalize = function () {
  1030. var length = 1.0 / this.length();
  1031. this.x *= length;
  1032. this.y *= length;
  1033. this.z *= length;
  1034. this.w *= length;
  1035. };
  1036. Quaternion.prototype.toEulerAngles = function () {
  1037. var result = Vector3.Zero();
  1038. this.toEulerAnglesToRef(result);
  1039. return result;
  1040. };
  1041. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1042. //result is an EulerAngles in the in the z-x-z convention
  1043. var qx = this.x;
  1044. var qy = this.y;
  1045. var qz = this.z;
  1046. var qw = this.w;
  1047. var qxy = qx * qy;
  1048. var qxz = qx * qz;
  1049. var qwy = qw * qy;
  1050. var qwz = qw * qz;
  1051. var qwx = qw * qx;
  1052. var qyz = qy * qz;
  1053. var sqx = qx * qx;
  1054. var sqy = qy * qy;
  1055. var determinant = sqx + sqy;
  1056. if (determinant !== 0.000 && determinant !== 1.000) {
  1057. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1058. result.y = Math.acos(1 - 2 * determinant);
  1059. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1060. } else {
  1061. if (determinant === 0.0) {
  1062. result.x = 0.0;
  1063. result.y = 0.0;
  1064. 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)
  1065. } else {
  1066. 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)
  1067. result.y = Math.PI;
  1068. result.z = 0.0;
  1069. }
  1070. }
  1071. };
  1072. Quaternion.prototype.toRotationMatrix = function (result) {
  1073. var xx = this.x * this.x;
  1074. var yy = this.y * this.y;
  1075. var zz = this.z * this.z;
  1076. var xy = this.x * this.y;
  1077. var zw = this.z * this.w;
  1078. var zx = this.z * this.x;
  1079. var yw = this.y * this.w;
  1080. var yz = this.y * this.z;
  1081. var xw = this.x * this.w;
  1082. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1083. result.m[1] = 2.0 * (xy + zw);
  1084. result.m[2] = 2.0 * (zx - yw);
  1085. result.m[3] = 0;
  1086. result.m[4] = 2.0 * (xy - zw);
  1087. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1088. result.m[6] = 2.0 * (yz + xw);
  1089. result.m[7] = 0;
  1090. result.m[8] = 2.0 * (zx + yw);
  1091. result.m[9] = 2.0 * (yz - xw);
  1092. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1093. result.m[11] = 0;
  1094. result.m[12] = 0;
  1095. result.m[13] = 0;
  1096. result.m[14] = 0;
  1097. result.m[15] = 1.0;
  1098. };
  1099. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1100. var data = matrix.m;
  1101. var m11 = data[0], m12 = data[4], m13 = data[8];
  1102. var m21 = data[1], m22 = data[5], m23 = data[9];
  1103. var m31 = data[2], m32 = data[6], m33 = data[10];
  1104. var trace = m11 + m22 + m33;
  1105. var s;
  1106. if (trace > 0) {
  1107. s = 0.5 / Math.sqrt(trace + 1.0);
  1108. this.w = 0.25 / s;
  1109. this.x = (m32 - m23) * s;
  1110. this.y = (m13 - m31) * s;
  1111. this.z = (m21 - m12) * s;
  1112. return;
  1113. }
  1114. if (m11 > m22 && m11 > m33) {
  1115. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1116. this.w = (m32 - m23) / s;
  1117. this.x = 0.25 * s;
  1118. this.y = (m12 + m21) / s;
  1119. this.z = (m13 + m31) / s;
  1120. return;
  1121. }
  1122. if (m22 > m33) {
  1123. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1124. this.w = (m13 - m31) / s;
  1125. this.x = (m12 + m21) / s;
  1126. this.y = 0.25 * s;
  1127. this.z = (m23 + m32) / s;
  1128. return;
  1129. }
  1130. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1131. this.w = (m21 - m12) / s;
  1132. this.x = (m13 + m31) / s;
  1133. this.y = (m23 + m32) / s;
  1134. this.z = 0.25 * s;
  1135. };
  1136. // Statics
  1137. Quaternion.Inverse = function (q) {
  1138. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1139. };
  1140. Quaternion.RotationAxis = function (axis, angle) {
  1141. var result = new Quaternion();
  1142. var sin = Math.sin(angle / 2);
  1143. result.w = Math.cos(angle / 2);
  1144. result.x = axis.x * sin;
  1145. result.y = axis.y * sin;
  1146. result.z = axis.z * sin;
  1147. return result;
  1148. };
  1149. Quaternion.FromArray = function (array, offset) {
  1150. if (!offset) {
  1151. offset = 0;
  1152. }
  1153. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1154. };
  1155. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1156. var result = new Quaternion();
  1157. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1158. return result;
  1159. };
  1160. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1161. var halfRoll = roll * 0.5;
  1162. var halfPitch = pitch * 0.5;
  1163. var halfYaw = yaw * 0.5;
  1164. var sinRoll = Math.sin(halfRoll);
  1165. var cosRoll = Math.cos(halfRoll);
  1166. var sinPitch = Math.sin(halfPitch);
  1167. var cosPitch = Math.cos(halfPitch);
  1168. var sinYaw = Math.sin(halfYaw);
  1169. var cosYaw = Math.cos(halfYaw);
  1170. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1171. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1172. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1173. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1174. };
  1175. Quaternion.Slerp = function (left, right, amount) {
  1176. var num2;
  1177. var num3;
  1178. var num = amount;
  1179. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1180. var flag = false;
  1181. if (num4 < 0) {
  1182. flag = true;
  1183. num4 = -num4;
  1184. }
  1185. if (num4 > 0.999999) {
  1186. num3 = 1 - num;
  1187. num2 = flag ? -num : num;
  1188. } else {
  1189. var num5 = Math.acos(num4);
  1190. var num6 = (1.0 / Math.sin(num5));
  1191. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1192. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1193. }
  1194. 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));
  1195. };
  1196. return Quaternion;
  1197. })();
  1198. BABYLON.Quaternion = Quaternion;
  1199. var Matrix = (function () {
  1200. function Matrix() {
  1201. this.m = new Float32Array(16);
  1202. }
  1203. // Properties
  1204. Matrix.prototype.isIdentity = function () {
  1205. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1206. return false;
  1207. 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)
  1208. return false;
  1209. return true;
  1210. };
  1211. Matrix.prototype.determinant = function () {
  1212. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1213. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1214. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1215. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1216. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1217. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1218. 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))));
  1219. };
  1220. // Methods
  1221. Matrix.prototype.toArray = function () {
  1222. return this.m;
  1223. };
  1224. Matrix.prototype.asArray = function () {
  1225. return this.toArray();
  1226. };
  1227. Matrix.prototype.invert = function () {
  1228. this.invertToRef(this);
  1229. };
  1230. Matrix.prototype.invertToRef = function (other) {
  1231. var l1 = this.m[0];
  1232. var l2 = this.m[1];
  1233. var l3 = this.m[2];
  1234. var l4 = this.m[3];
  1235. var l5 = this.m[4];
  1236. var l6 = this.m[5];
  1237. var l7 = this.m[6];
  1238. var l8 = this.m[7];
  1239. var l9 = this.m[8];
  1240. var l10 = this.m[9];
  1241. var l11 = this.m[10];
  1242. var l12 = this.m[11];
  1243. var l13 = this.m[12];
  1244. var l14 = this.m[13];
  1245. var l15 = this.m[14];
  1246. var l16 = this.m[15];
  1247. var l17 = (l11 * l16) - (l12 * l15);
  1248. var l18 = (l10 * l16) - (l12 * l14);
  1249. var l19 = (l10 * l15) - (l11 * l14);
  1250. var l20 = (l9 * l16) - (l12 * l13);
  1251. var l21 = (l9 * l15) - (l11 * l13);
  1252. var l22 = (l9 * l14) - (l10 * l13);
  1253. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1254. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1255. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1256. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1257. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1258. var l28 = (l7 * l16) - (l8 * l15);
  1259. var l29 = (l6 * l16) - (l8 * l14);
  1260. var l30 = (l6 * l15) - (l7 * l14);
  1261. var l31 = (l5 * l16) - (l8 * l13);
  1262. var l32 = (l5 * l15) - (l7 * l13);
  1263. var l33 = (l5 * l14) - (l6 * l13);
  1264. var l34 = (l7 * l12) - (l8 * l11);
  1265. var l35 = (l6 * l12) - (l8 * l10);
  1266. var l36 = (l6 * l11) - (l7 * l10);
  1267. var l37 = (l5 * l12) - (l8 * l9);
  1268. var l38 = (l5 * l11) - (l7 * l9);
  1269. var l39 = (l5 * l10) - (l6 * l9);
  1270. other.m[0] = l23 * l27;
  1271. other.m[4] = l24 * l27;
  1272. other.m[8] = l25 * l27;
  1273. other.m[12] = l26 * l27;
  1274. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1275. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1276. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1277. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1278. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1279. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1280. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1281. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1282. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1283. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1284. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1285. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1286. };
  1287. Matrix.prototype.setTranslation = function (vector3) {
  1288. this.m[12] = vector3.x;
  1289. this.m[13] = vector3.y;
  1290. this.m[14] = vector3.z;
  1291. };
  1292. Matrix.prototype.multiply = function (other) {
  1293. var result = new Matrix();
  1294. this.multiplyToRef(other, result);
  1295. return result;
  1296. };
  1297. Matrix.prototype.copyFrom = function (other) {
  1298. for (var index = 0; index < 16; index++) {
  1299. this.m[index] = other.m[index];
  1300. }
  1301. };
  1302. Matrix.prototype.copyToArray = function (array, offset) {
  1303. if (typeof offset === "undefined") { offset = 0; }
  1304. for (var index = 0; index < 16; index++) {
  1305. array[offset + index] = this.m[index];
  1306. }
  1307. };
  1308. Matrix.prototype.multiplyToRef = function (other, result) {
  1309. this.multiplyToArray(other, result.m, 0);
  1310. };
  1311. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1312. var tm0 = this.m[0];
  1313. var tm1 = this.m[1];
  1314. var tm2 = this.m[2];
  1315. var tm3 = this.m[3];
  1316. var tm4 = this.m[4];
  1317. var tm5 = this.m[5];
  1318. var tm6 = this.m[6];
  1319. var tm7 = this.m[7];
  1320. var tm8 = this.m[8];
  1321. var tm9 = this.m[9];
  1322. var tm10 = this.m[10];
  1323. var tm11 = this.m[11];
  1324. var tm12 = this.m[12];
  1325. var tm13 = this.m[13];
  1326. var tm14 = this.m[14];
  1327. var tm15 = this.m[15];
  1328. var om0 = other.m[0];
  1329. var om1 = other.m[1];
  1330. var om2 = other.m[2];
  1331. var om3 = other.m[3];
  1332. var om4 = other.m[4];
  1333. var om5 = other.m[5];
  1334. var om6 = other.m[6];
  1335. var om7 = other.m[7];
  1336. var om8 = other.m[8];
  1337. var om9 = other.m[9];
  1338. var om10 = other.m[10];
  1339. var om11 = other.m[11];
  1340. var om12 = other.m[12];
  1341. var om13 = other.m[13];
  1342. var om14 = other.m[14];
  1343. var om15 = other.m[15];
  1344. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1345. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1346. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1347. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1348. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1349. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1350. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1351. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1352. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1353. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1354. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1355. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1356. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1357. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1358. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1359. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1360. };
  1361. Matrix.prototype.equals = function (value) {
  1362. 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]);
  1363. };
  1364. Matrix.prototype.clone = function () {
  1365. 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]);
  1366. };
  1367. // Statics
  1368. Matrix.FromArray = function (array, offset) {
  1369. var result = new Matrix();
  1370. if (!offset) {
  1371. offset = 0;
  1372. }
  1373. Matrix.FromArrayToRef(array, offset, result);
  1374. return result;
  1375. };
  1376. Matrix.FromArrayToRef = function (array, offset, result) {
  1377. for (var index = 0; index < 16; index++) {
  1378. result.m[index] = array[index + offset];
  1379. }
  1380. };
  1381. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1382. result.m[0] = initialM11;
  1383. result.m[1] = initialM12;
  1384. result.m[2] = initialM13;
  1385. result.m[3] = initialM14;
  1386. result.m[4] = initialM21;
  1387. result.m[5] = initialM22;
  1388. result.m[6] = initialM23;
  1389. result.m[7] = initialM24;
  1390. result.m[8] = initialM31;
  1391. result.m[9] = initialM32;
  1392. result.m[10] = initialM33;
  1393. result.m[11] = initialM34;
  1394. result.m[12] = initialM41;
  1395. result.m[13] = initialM42;
  1396. result.m[14] = initialM43;
  1397. result.m[15] = initialM44;
  1398. };
  1399. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1400. var result = new Matrix();
  1401. result.m[0] = initialM11;
  1402. result.m[1] = initialM12;
  1403. result.m[2] = initialM13;
  1404. result.m[3] = initialM14;
  1405. result.m[4] = initialM21;
  1406. result.m[5] = initialM22;
  1407. result.m[6] = initialM23;
  1408. result.m[7] = initialM24;
  1409. result.m[8] = initialM31;
  1410. result.m[9] = initialM32;
  1411. result.m[10] = initialM33;
  1412. result.m[11] = initialM34;
  1413. result.m[12] = initialM41;
  1414. result.m[13] = initialM42;
  1415. result.m[14] = initialM43;
  1416. result.m[15] = initialM44;
  1417. return result;
  1418. };
  1419. Matrix.Identity = function () {
  1420. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1421. };
  1422. Matrix.IdentityToRef = function (result) {
  1423. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1424. };
  1425. Matrix.Zero = function () {
  1426. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1427. };
  1428. Matrix.RotationX = function (angle) {
  1429. var result = new Matrix();
  1430. Matrix.RotationXToRef(angle, result);
  1431. return result;
  1432. };
  1433. Matrix.Invert = function (source) {
  1434. var result = new Matrix();
  1435. source.invertToRef(result);
  1436. return result;
  1437. };
  1438. Matrix.RotationXToRef = function (angle, result) {
  1439. var s = Math.sin(angle);
  1440. var c = Math.cos(angle);
  1441. result.m[0] = 1.0;
  1442. result.m[15] = 1.0;
  1443. result.m[5] = c;
  1444. result.m[10] = c;
  1445. result.m[9] = -s;
  1446. result.m[6] = s;
  1447. result.m[1] = 0;
  1448. result.m[2] = 0;
  1449. result.m[3] = 0;
  1450. result.m[4] = 0;
  1451. result.m[7] = 0;
  1452. result.m[8] = 0;
  1453. result.m[11] = 0;
  1454. result.m[12] = 0;
  1455. result.m[13] = 0;
  1456. result.m[14] = 0;
  1457. };
  1458. Matrix.RotationY = function (angle) {
  1459. var result = new Matrix();
  1460. Matrix.RotationYToRef(angle, result);
  1461. return result;
  1462. };
  1463. Matrix.RotationYToRef = function (angle, result) {
  1464. var s = Math.sin(angle);
  1465. var c = Math.cos(angle);
  1466. result.m[5] = 1.0;
  1467. result.m[15] = 1.0;
  1468. result.m[0] = c;
  1469. result.m[2] = -s;
  1470. result.m[8] = s;
  1471. result.m[10] = c;
  1472. result.m[1] = 0;
  1473. result.m[3] = 0;
  1474. result.m[4] = 0;
  1475. result.m[6] = 0;
  1476. result.m[7] = 0;
  1477. result.m[9] = 0;
  1478. result.m[11] = 0;
  1479. result.m[12] = 0;
  1480. result.m[13] = 0;
  1481. result.m[14] = 0;
  1482. };
  1483. Matrix.RotationZ = function (angle) {
  1484. var result = new Matrix();
  1485. Matrix.RotationZToRef(angle, result);
  1486. return result;
  1487. };
  1488. Matrix.RotationZToRef = function (angle, result) {
  1489. var s = Math.sin(angle);
  1490. var c = Math.cos(angle);
  1491. result.m[10] = 1.0;
  1492. result.m[15] = 1.0;
  1493. result.m[0] = c;
  1494. result.m[1] = s;
  1495. result.m[4] = -s;
  1496. result.m[5] = c;
  1497. result.m[2] = 0;
  1498. result.m[3] = 0;
  1499. result.m[6] = 0;
  1500. result.m[7] = 0;
  1501. result.m[8] = 0;
  1502. result.m[9] = 0;
  1503. result.m[11] = 0;
  1504. result.m[12] = 0;
  1505. result.m[13] = 0;
  1506. result.m[14] = 0;
  1507. };
  1508. Matrix.RotationAxis = function (axis, angle) {
  1509. var s = Math.sin(-angle);
  1510. var c = Math.cos(-angle);
  1511. var c1 = 1 - c;
  1512. axis.normalize();
  1513. var result = Matrix.Zero();
  1514. result.m[0] = (axis.x * axis.x) * c1 + c;
  1515. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1516. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1517. result.m[3] = 0.0;
  1518. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1519. result.m[5] = (axis.y * axis.y) * c1 + c;
  1520. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1521. result.m[7] = 0.0;
  1522. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1523. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1524. result.m[10] = (axis.z * axis.z) * c1 + c;
  1525. result.m[11] = 0.0;
  1526. result.m[15] = 1.0;
  1527. return result;
  1528. };
  1529. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1530. var result = new Matrix();
  1531. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1532. return result;
  1533. };
  1534. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1535. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1536. this._tempQuaternion.toRotationMatrix(result);
  1537. };
  1538. Matrix.Scaling = function (x, y, z) {
  1539. var result = Matrix.Zero();
  1540. Matrix.ScalingToRef(x, y, z, result);
  1541. return result;
  1542. };
  1543. Matrix.ScalingToRef = function (x, y, z, result) {
  1544. result.m[0] = x;
  1545. result.m[1] = 0;
  1546. result.m[2] = 0;
  1547. result.m[3] = 0;
  1548. result.m[4] = 0;
  1549. result.m[5] = y;
  1550. result.m[6] = 0;
  1551. result.m[7] = 0;
  1552. result.m[8] = 0;
  1553. result.m[9] = 0;
  1554. result.m[10] = z;
  1555. result.m[11] = 0;
  1556. result.m[12] = 0;
  1557. result.m[13] = 0;
  1558. result.m[14] = 0;
  1559. result.m[15] = 1.0;
  1560. };
  1561. Matrix.Translation = function (x, y, z) {
  1562. var result = Matrix.Identity();
  1563. Matrix.TranslationToRef(x, y, z, result);
  1564. return result;
  1565. };
  1566. Matrix.TranslationToRef = function (x, y, z, result) {
  1567. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1568. };
  1569. Matrix.LookAtLH = function (eye, target, up) {
  1570. var result = Matrix.Zero();
  1571. Matrix.LookAtLHToRef(eye, target, up, result);
  1572. return result;
  1573. };
  1574. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1575. // Z axis
  1576. target.subtractToRef(eye, this._zAxis);
  1577. this._zAxis.normalize();
  1578. // X axis
  1579. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1580. this._xAxis.normalize();
  1581. // Y axis
  1582. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1583. this._yAxis.normalize();
  1584. // Eye angles
  1585. var ex = -Vector3.Dot(this._xAxis, eye);
  1586. var ey = -Vector3.Dot(this._yAxis, eye);
  1587. var ez = -Vector3.Dot(this._zAxis, eye);
  1588. 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);
  1589. };
  1590. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1591. var hw = 2.0 / width;
  1592. var hh = 2.0 / height;
  1593. var id = 1.0 / (zfar - znear);
  1594. var nid = znear / (znear - zfar);
  1595. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1596. };
  1597. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1598. var matrix = Matrix.Zero();
  1599. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1600. return matrix;
  1601. };
  1602. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1603. result.m[0] = 2.0 / (right - left);
  1604. result.m[1] = result.m[2] = result.m[3] = 0;
  1605. result.m[5] = 2.0 / (top - bottom);
  1606. result.m[4] = result.m[6] = result.m[7] = 0;
  1607. result.m[10] = -1.0 / (znear - zfar);
  1608. result.m[8] = result.m[9] = result.m[11] = 0;
  1609. result.m[12] = (left + right) / (left - right);
  1610. result.m[13] = (top + bottom) / (bottom - top);
  1611. result.m[14] = znear / (znear - zfar);
  1612. result.m[15] = 1.0;
  1613. };
  1614. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1615. var matrix = Matrix.Zero();
  1616. matrix.m[0] = (2.0 * znear) / width;
  1617. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1618. matrix.m[5] = (2.0 * znear) / height;
  1619. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1620. matrix.m[10] = -zfar / (znear - zfar);
  1621. matrix.m[8] = matrix.m[9] = 0.0;
  1622. matrix.m[11] = 1.0;
  1623. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1624. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1625. return matrix;
  1626. };
  1627. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1628. var matrix = Matrix.Zero();
  1629. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1630. return matrix;
  1631. };
  1632. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1633. var tan = 1.0 / (Math.tan(fov * 0.5));
  1634. result.m[0] = tan / aspect;
  1635. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1636. result.m[5] = tan;
  1637. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1638. result.m[8] = result.m[9] = 0.0;
  1639. result.m[10] = -zfar / (znear - zfar);
  1640. result.m[11] = 1.0;
  1641. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1642. result.m[14] = (znear * zfar) / (znear - zfar);
  1643. };
  1644. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1645. var cw = viewport.width;
  1646. var ch = viewport.height;
  1647. var cx = viewport.x;
  1648. var cy = viewport.y;
  1649. 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);
  1650. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1651. };
  1652. Matrix.Transpose = function (matrix) {
  1653. var result = new Matrix();
  1654. result.m[0] = matrix.m[0];
  1655. result.m[1] = matrix.m[4];
  1656. result.m[2] = matrix.m[8];
  1657. result.m[3] = matrix.m[12];
  1658. result.m[4] = matrix.m[1];
  1659. result.m[5] = matrix.m[5];
  1660. result.m[6] = matrix.m[9];
  1661. result.m[7] = matrix.m[13];
  1662. result.m[8] = matrix.m[2];
  1663. result.m[9] = matrix.m[6];
  1664. result.m[10] = matrix.m[10];
  1665. result.m[11] = matrix.m[14];
  1666. result.m[12] = matrix.m[3];
  1667. result.m[13] = matrix.m[7];
  1668. result.m[14] = matrix.m[11];
  1669. result.m[15] = matrix.m[15];
  1670. return result;
  1671. };
  1672. Matrix.Reflection = function (plane) {
  1673. var matrix = new Matrix();
  1674. Matrix.ReflectionToRef(plane, matrix);
  1675. return matrix;
  1676. };
  1677. Matrix.ReflectionToRef = function (plane, result) {
  1678. plane.normalize();
  1679. var x = plane.normal.x;
  1680. var y = plane.normal.y;
  1681. var z = plane.normal.z;
  1682. var temp = -2 * x;
  1683. var temp2 = -2 * y;
  1684. var temp3 = -2 * z;
  1685. result.m[0] = (temp * x) + 1;
  1686. result.m[1] = temp2 * x;
  1687. result.m[2] = temp3 * x;
  1688. result.m[3] = 0.0;
  1689. result.m[4] = temp * y;
  1690. result.m[5] = (temp2 * y) + 1;
  1691. result.m[6] = temp3 * y;
  1692. result.m[7] = 0.0;
  1693. result.m[8] = temp * z;
  1694. result.m[9] = temp2 * z;
  1695. result.m[10] = (temp3 * z) + 1;
  1696. result.m[11] = 0.0;
  1697. result.m[12] = temp * plane.d;
  1698. result.m[13] = temp2 * plane.d;
  1699. result.m[14] = temp3 * plane.d;
  1700. result.m[15] = 1.0;
  1701. };
  1702. Matrix._tempQuaternion = new Quaternion();
  1703. Matrix._xAxis = Vector3.Zero();
  1704. Matrix._yAxis = Vector3.Zero();
  1705. Matrix._zAxis = Vector3.Zero();
  1706. return Matrix;
  1707. })();
  1708. BABYLON.Matrix = Matrix;
  1709. var Plane = (function () {
  1710. function Plane(a, b, c, d) {
  1711. this.normal = new Vector3(a, b, c);
  1712. this.d = d;
  1713. }
  1714. Plane.prototype.asArray = function () {
  1715. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1716. };
  1717. // Methods
  1718. Plane.prototype.clone = function () {
  1719. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1720. };
  1721. Plane.prototype.normalize = function () {
  1722. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1723. var magnitude = 0;
  1724. if (norm !== 0) {
  1725. magnitude = 1.0 / norm;
  1726. }
  1727. this.normal.x *= magnitude;
  1728. this.normal.y *= magnitude;
  1729. this.normal.z *= magnitude;
  1730. this.d *= magnitude;
  1731. };
  1732. Plane.prototype.transform = function (transformation) {
  1733. var transposedMatrix = Matrix.Transpose(transformation);
  1734. var x = this.normal.x;
  1735. var y = this.normal.y;
  1736. var z = this.normal.z;
  1737. var d = this.d;
  1738. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1739. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1740. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1741. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1742. return new Plane(normalX, normalY, normalZ, finalD);
  1743. };
  1744. Plane.prototype.dotCoordinate = function (point) {
  1745. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1746. };
  1747. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1748. var x1 = point2.x - point1.x;
  1749. var y1 = point2.y - point1.y;
  1750. var z1 = point2.z - point1.z;
  1751. var x2 = point3.x - point1.x;
  1752. var y2 = point3.y - point1.y;
  1753. var z2 = point3.z - point1.z;
  1754. var yz = (y1 * z2) - (z1 * y2);
  1755. var xz = (z1 * x2) - (x1 * z2);
  1756. var xy = (x1 * y2) - (y1 * x2);
  1757. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1758. var invPyth;
  1759. if (pyth !== 0) {
  1760. invPyth = 1.0 / pyth;
  1761. } else {
  1762. invPyth = 0;
  1763. }
  1764. this.normal.x = yz * invPyth;
  1765. this.normal.y = xz * invPyth;
  1766. this.normal.z = xy * invPyth;
  1767. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1768. };
  1769. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1770. var dot = Vector3.Dot(this.normal, direction);
  1771. return (dot <= epsilon);
  1772. };
  1773. Plane.prototype.signedDistanceTo = function (point) {
  1774. return Vector3.Dot(point, this.normal) + this.d;
  1775. };
  1776. // Statics
  1777. Plane.FromArray = function (array) {
  1778. return new Plane(array[0], array[1], array[2], array[3]);
  1779. };
  1780. Plane.FromPoints = function (point1, point2, point3) {
  1781. var result = new Plane(0, 0, 0, 0);
  1782. result.copyFromPoints(point1, point2, point3);
  1783. return result;
  1784. };
  1785. Plane.FromPositionAndNormal = function (origin, normal) {
  1786. var result = new Plane(0, 0, 0, 0);
  1787. normal.normalize();
  1788. result.normal = normal;
  1789. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1790. return result;
  1791. };
  1792. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1793. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1794. return Vector3.Dot(point, normal) + d;
  1795. };
  1796. return Plane;
  1797. })();
  1798. BABYLON.Plane = Plane;
  1799. var Viewport = (function () {
  1800. function Viewport(x, y, width, height) {
  1801. this.x = x;
  1802. this.y = y;
  1803. this.width = width;
  1804. this.height = height;
  1805. }
  1806. Viewport.prototype.toGlobal = function (engine) {
  1807. var width = engine.getRenderWidth();
  1808. var height = engine.getRenderHeight();
  1809. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1810. };
  1811. return Viewport;
  1812. })();
  1813. BABYLON.Viewport = Viewport;
  1814. var Frustum = (function () {
  1815. function Frustum() {
  1816. }
  1817. Frustum.GetPlanes = function (transform) {
  1818. var frustumPlanes = [];
  1819. for (var index = 0; index < 6; index++) {
  1820. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1821. }
  1822. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1823. return frustumPlanes;
  1824. };
  1825. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1826. // Near
  1827. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1828. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1829. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1830. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1831. frustumPlanes[0].normalize();
  1832. // Far
  1833. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1834. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1835. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1836. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1837. frustumPlanes[1].normalize();
  1838. // Left
  1839. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1840. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1841. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1842. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1843. frustumPlanes[2].normalize();
  1844. // Right
  1845. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1846. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1847. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1848. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1849. frustumPlanes[3].normalize();
  1850. // Top
  1851. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1852. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1853. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1854. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1855. frustumPlanes[4].normalize();
  1856. // Bottom
  1857. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1858. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1859. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1860. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1861. frustumPlanes[5].normalize();
  1862. };
  1863. return Frustum;
  1864. })();
  1865. BABYLON.Frustum = Frustum;
  1866. var Ray = (function () {
  1867. function Ray(origin, direction, length) {
  1868. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1869. this.origin = origin;
  1870. this.direction = direction;
  1871. this.length = length;
  1872. }
  1873. // Methods
  1874. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1875. var d = 0.0;
  1876. var maxValue = Number.MAX_VALUE;
  1877. if (Math.abs(this.direction.x) < 0.0000001) {
  1878. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1879. return false;
  1880. }
  1881. } else {
  1882. var inv = 1.0 / this.direction.x;
  1883. var min = (minimum.x - this.origin.x) * inv;
  1884. var max = (maximum.x - this.origin.x) * inv;
  1885. if (max === -Infinity) {
  1886. max = Infinity;
  1887. }
  1888. if (min > max) {
  1889. var temp = min;
  1890. min = max;
  1891. max = temp;
  1892. }
  1893. d = Math.max(min, d);
  1894. maxValue = Math.min(max, maxValue);
  1895. if (d > maxValue) {
  1896. return false;
  1897. }
  1898. }
  1899. if (Math.abs(this.direction.y) < 0.0000001) {
  1900. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1901. return false;
  1902. }
  1903. } else {
  1904. inv = 1.0 / this.direction.y;
  1905. min = (minimum.y - this.origin.y) * inv;
  1906. max = (maximum.y - this.origin.y) * inv;
  1907. if (max === -Infinity) {
  1908. max = Infinity;
  1909. }
  1910. if (min > max) {
  1911. temp = min;
  1912. min = max;
  1913. max = temp;
  1914. }
  1915. d = Math.max(min, d);
  1916. maxValue = Math.min(max, maxValue);
  1917. if (d > maxValue) {
  1918. return false;
  1919. }
  1920. }
  1921. if (Math.abs(this.direction.z) < 0.0000001) {
  1922. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1923. return false;
  1924. }
  1925. } else {
  1926. inv = 1.0 / this.direction.z;
  1927. min = (minimum.z - this.origin.z) * inv;
  1928. max = (maximum.z - this.origin.z) * inv;
  1929. if (max === -Infinity) {
  1930. max = Infinity;
  1931. }
  1932. if (min > max) {
  1933. temp = min;
  1934. min = max;
  1935. max = temp;
  1936. }
  1937. d = Math.max(min, d);
  1938. maxValue = Math.min(max, maxValue);
  1939. if (d > maxValue) {
  1940. return false;
  1941. }
  1942. }
  1943. return true;
  1944. };
  1945. Ray.prototype.intersectsBox = function (box) {
  1946. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1947. };
  1948. Ray.prototype.intersectsSphere = function (sphere) {
  1949. var x = sphere.center.x - this.origin.x;
  1950. var y = sphere.center.y - this.origin.y;
  1951. var z = sphere.center.z - this.origin.z;
  1952. var pyth = (x * x) + (y * y) + (z * z);
  1953. var rr = sphere.radius * sphere.radius;
  1954. if (pyth <= rr) {
  1955. return true;
  1956. }
  1957. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1958. if (dot < 0.0) {
  1959. return false;
  1960. }
  1961. var temp = pyth - (dot * dot);
  1962. return temp <= rr;
  1963. };
  1964. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1965. if (!this._edge1) {
  1966. this._edge1 = Vector3.Zero();
  1967. this._edge2 = Vector3.Zero();
  1968. this._pvec = Vector3.Zero();
  1969. this._tvec = Vector3.Zero();
  1970. this._qvec = Vector3.Zero();
  1971. }
  1972. vertex1.subtractToRef(vertex0, this._edge1);
  1973. vertex2.subtractToRef(vertex0, this._edge2);
  1974. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1975. var det = Vector3.Dot(this._edge1, this._pvec);
  1976. if (det === 0) {
  1977. return null;
  1978. }
  1979. var invdet = 1 / det;
  1980. this.origin.subtractToRef(vertex0, this._tvec);
  1981. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1982. if (bu < 0 || bu > 1.0) {
  1983. return null;
  1984. }
  1985. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1986. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1987. if (bv < 0 || bu + bv > 1.0) {
  1988. return null;
  1989. }
  1990. //check if the distance is longer than the predefined length.
  1991. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  1992. if (distance > this.length) {
  1993. return null;
  1994. }
  1995. return new BABYLON.IntersectionInfo(bu, bv, distance);
  1996. };
  1997. // Statics
  1998. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1999. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2000. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2001. var direction = end.subtract(start);
  2002. direction.normalize();
  2003. return new Ray(start, direction);
  2004. };
  2005. /**
  2006. * 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
  2007. * transformed to the given world matrix.
  2008. * @param origin The origin point
  2009. * @param end The end point
  2010. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2011. */
  2012. Ray.CreateNewFromTo = function (origin, end, world) {
  2013. if (typeof world === "undefined") { world = Matrix.Identity(); }
  2014. var direction = end.subtract(origin);
  2015. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2016. direction.normalize();
  2017. return Ray.Transform(new Ray(origin, direction, length), world);
  2018. };
  2019. Ray.Transform = function (ray, matrix) {
  2020. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2021. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2022. return new Ray(newOrigin, newDirection, ray.length);
  2023. };
  2024. return Ray;
  2025. })();
  2026. BABYLON.Ray = Ray;
  2027. (function (Space) {
  2028. Space[Space["LOCAL"] = 0] = "LOCAL";
  2029. Space[Space["WORLD"] = 1] = "WORLD";
  2030. })(BABYLON.Space || (BABYLON.Space = {}));
  2031. var Space = BABYLON.Space;
  2032. var Axis = (function () {
  2033. function Axis() {
  2034. }
  2035. Axis.X = new Vector3(1, 0, 0);
  2036. Axis.Y = new Vector3(0, 1, 0);
  2037. Axis.Z = new Vector3(0, 0, 1);
  2038. return Axis;
  2039. })();
  2040. BABYLON.Axis = Axis;
  2041. ;
  2042. var BezierCurve = (function () {
  2043. function BezierCurve() {
  2044. }
  2045. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2046. // Extract X (which is equal to time here)
  2047. var f0 = 1 - 3 * x2 + 3 * x1;
  2048. var f1 = 3 * x2 - 6 * x1;
  2049. var f2 = 3 * x1;
  2050. var refinedT = t;
  2051. for (var i = 0; i < 5; i++) {
  2052. var refinedT2 = refinedT * refinedT;
  2053. var refinedT3 = refinedT2 * refinedT;
  2054. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2055. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2056. refinedT -= (x - t) * slope;
  2057. refinedT = Math.min(1, Math.max(0, refinedT));
  2058. }
  2059. // Resolve cubic bezier for the given x
  2060. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2061. };
  2062. return BezierCurve;
  2063. })();
  2064. BABYLON.BezierCurve = BezierCurve;
  2065. (function (Orientation) {
  2066. Orientation[Orientation["CW"] = 0] = "CW";
  2067. Orientation[Orientation["CCW"] = 1] = "CCW";
  2068. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2069. var Orientation = BABYLON.Orientation;
  2070. var Angle = (function () {
  2071. function Angle(radians) {
  2072. var _this = this;
  2073. this.degrees = function () {
  2074. return _this._radians * 180 / Math.PI;
  2075. };
  2076. this.radians = function () {
  2077. return _this._radians;
  2078. };
  2079. this._radians = radians;
  2080. if (this._radians < 0)
  2081. this._radians += (2 * Math.PI);
  2082. }
  2083. Angle.BetweenTwoPoints = function (a, b) {
  2084. var delta = b.subtract(a);
  2085. var theta = Math.atan2(delta.y, delta.x);
  2086. return new Angle(theta);
  2087. };
  2088. Angle.FromRadians = function (radians) {
  2089. return new Angle(radians);
  2090. };
  2091. Angle.FromDegrees = function (degrees) {
  2092. return new Angle(degrees * Math.PI / 180);
  2093. };
  2094. return Angle;
  2095. })();
  2096. BABYLON.Angle = Angle;
  2097. var Arc2 = (function () {
  2098. function Arc2(startPoint, midPoint, endPoint) {
  2099. this.startPoint = startPoint;
  2100. this.midPoint = midPoint;
  2101. this.endPoint = endPoint;
  2102. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2103. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2104. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2105. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2106. 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);
  2107. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2108. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2109. var a1 = this.startAngle.degrees();
  2110. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2111. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2112. // angles correction
  2113. if (a2 - a1 > +180.0)
  2114. a2 -= 360.0;
  2115. if (a2 - a1 < -180.0)
  2116. a2 += 360.0;
  2117. if (a3 - a2 > +180.0)
  2118. a3 -= 360.0;
  2119. if (a3 - a2 < -180.0)
  2120. a3 += 360.0;
  2121. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2122. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2123. }
  2124. return Arc2;
  2125. })();
  2126. BABYLON.Arc2 = Arc2;
  2127. var PathCursor = (function () {
  2128. function PathCursor(path) {
  2129. this.path = path;
  2130. this._onchange = new Array();
  2131. this.value = 0;
  2132. this.animations = new Array();
  2133. }
  2134. PathCursor.prototype.getPoint = function () {
  2135. var point = this.path.getPointAtLengthPosition(this.value);
  2136. return new Vector3(point.x, 0, point.y);
  2137. };
  2138. PathCursor.prototype.moveAhead = function (step) {
  2139. if (typeof step === "undefined") { step = 0.002; }
  2140. this.move(step);
  2141. };
  2142. PathCursor.prototype.moveBack = function (step) {
  2143. if (typeof step === "undefined") { step = 0.002; }
  2144. this.move(-step);
  2145. };
  2146. PathCursor.prototype.move = function (step) {
  2147. if (Math.abs(step) > 1) {
  2148. throw "step size should be less than 1.";
  2149. }
  2150. this.value += step;
  2151. this.ensureLimits();
  2152. this.raiseOnChange();
  2153. };
  2154. PathCursor.prototype.ensureLimits = function () {
  2155. while (this.value > 1) {
  2156. this.value -= 1;
  2157. }
  2158. while (this.value < 0) {
  2159. this.value += 1;
  2160. }
  2161. };
  2162. // used by animation engine
  2163. PathCursor.prototype.markAsDirty = function (propertyName) {
  2164. this.ensureLimits();
  2165. this.raiseOnChange();
  2166. };
  2167. PathCursor.prototype.raiseOnChange = function () {
  2168. var _this = this;
  2169. this._onchange.forEach(function (f) {
  2170. return f(_this);
  2171. });
  2172. };
  2173. PathCursor.prototype.onchange = function (f) {
  2174. this._onchange.push(f);
  2175. };
  2176. return PathCursor;
  2177. })();
  2178. BABYLON.PathCursor = PathCursor;
  2179. var Path2 = (function () {
  2180. function Path2(x, y) {
  2181. this._points = [];
  2182. this._length = 0;
  2183. this.closed = false;
  2184. this._points.push(new Vector2(x, y));
  2185. }
  2186. Path2.prototype.addLineTo = function (x, y) {
  2187. if (closed) {
  2188. BABYLON.Tools.Error("cannot add lines to closed paths");
  2189. return this;
  2190. }
  2191. var newPoint = new Vector2(x, y);
  2192. var previousPoint = this._points[this._points.length - 1];
  2193. this._points.push(newPoint);
  2194. this._length += newPoint.subtract(previousPoint).length();
  2195. return this;
  2196. };
  2197. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2198. if (typeof numberOfSegments === "undefined") { numberOfSegments = 36; }
  2199. if (closed) {
  2200. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2201. return this;
  2202. }
  2203. var startPoint = this._points[this._points.length - 1];
  2204. var midPoint = new Vector2(midX, midY);
  2205. var endPoint = new Vector2(endX, endY);
  2206. var arc = new Arc2(startPoint, midPoint, endPoint);
  2207. var increment = arc.angle.radians() / numberOfSegments;
  2208. if (arc.orientation === 0 /* CW */)
  2209. increment *= -1;
  2210. var currentAngle = arc.startAngle.radians() + increment;
  2211. for (var i = 0; i < numberOfSegments; i++) {
  2212. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2213. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2214. this.addLineTo(x, y);
  2215. currentAngle += increment;
  2216. }
  2217. return this;
  2218. };
  2219. Path2.prototype.close = function () {
  2220. this.closed = true;
  2221. return this;
  2222. };
  2223. Path2.prototype.length = function () {
  2224. var result = this._length;
  2225. if (!this.closed) {
  2226. var lastPoint = this._points[this._points.length - 1];
  2227. var firstPoint = this._points[0];
  2228. result += (firstPoint.subtract(lastPoint).length());
  2229. }
  2230. return result;
  2231. };
  2232. Path2.prototype.getPoints = function () {
  2233. return this._points;
  2234. };
  2235. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2236. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2237. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2238. return;
  2239. }
  2240. var lengthPosition = normalizedLengthPosition * this.length();
  2241. var previousOffset = 0;
  2242. for (var i = 0; i < this._points.length; i++) {
  2243. var j = (i + 1) % this._points.length;
  2244. var a = this._points[i];
  2245. var b = this._points[j];
  2246. var bToA = b.subtract(a);
  2247. var nextOffset = (bToA.length() + previousOffset);
  2248. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2249. var dir = bToA.normalize();
  2250. var localOffset = lengthPosition - previousOffset;
  2251. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2252. }
  2253. previousOffset = nextOffset;
  2254. }
  2255. BABYLON.Tools.Error("internal error");
  2256. };
  2257. Path2.StartingAt = function (x, y) {
  2258. return new Path2(x, y);
  2259. };
  2260. return Path2;
  2261. })();
  2262. BABYLON.Path2 = Path2;
  2263. })(BABYLON || (BABYLON = {}));
  2264. //# sourceMappingURL=babylon.math.js.map
  2265. var BABYLON;
  2266. (function (BABYLON) {
  2267. // Screenshots
  2268. var screenshotCanvas;
  2269. var cloneValue = function (source, destinationObject) {
  2270. if (!source)
  2271. return null;
  2272. if (source instanceof BABYLON.Mesh) {
  2273. return null;
  2274. }
  2275. if (source instanceof BABYLON.SubMesh) {
  2276. return source.clone(destinationObject);
  2277. } else if (source.clone) {
  2278. return source.clone();
  2279. }
  2280. return null;
  2281. };
  2282. var Tools = (function () {
  2283. function Tools() {
  2284. }
  2285. Tools.GetFilename = function (path) {
  2286. var index = path.lastIndexOf("/");
  2287. if (index < 0)
  2288. return path;
  2289. return path.substring(index + 1);
  2290. };
  2291. Tools.GetDOMTextContent = function (element) {
  2292. var result = "";
  2293. var child = element.firstChild;
  2294. while (child) {
  2295. if (child.nodeType == 3) {
  2296. result += child.textContent;
  2297. }
  2298. child = child.nextSibling;
  2299. }
  2300. return result;
  2301. };
  2302. Tools.ToDegrees = function (angle) {
  2303. return angle * 180 / Math.PI;
  2304. };
  2305. Tools.ToRadians = function (angle) {
  2306. return angle * Math.PI / 180;
  2307. };
  2308. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2309. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2310. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2311. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2312. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2313. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2314. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2315. }
  2316. return {
  2317. minimum: minimum,
  2318. maximum: maximum
  2319. };
  2320. };
  2321. Tools.ExtractMinAndMax = function (positions, start, count) {
  2322. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2323. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2324. for (var index = start; index < start + count; index++) {
  2325. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2326. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2327. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2328. }
  2329. return {
  2330. minimum: minimum,
  2331. maximum: maximum
  2332. };
  2333. };
  2334. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2335. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2336. return undefined;
  2337. return Array.isArray(obj) ? obj : [obj];
  2338. };
  2339. // Misc.
  2340. Tools.GetPointerPrefix = function () {
  2341. var eventPrefix = "pointer";
  2342. // Check if hand.js is referenced or if the browser natively supports pointer events
  2343. if (!navigator.pointerEnabled) {
  2344. eventPrefix = "mouse";
  2345. }
  2346. return eventPrefix;
  2347. };
  2348. Tools.QueueNewFrame = function (func) {
  2349. if (window.requestAnimationFrame)
  2350. window.requestAnimationFrame(func);
  2351. else if (window.msRequestAnimationFrame)
  2352. window.msRequestAnimationFrame(func);
  2353. else if (window.webkitRequestAnimationFrame)
  2354. window.webkitRequestAnimationFrame(func);
  2355. else if (window.mozRequestAnimationFrame)
  2356. window.mozRequestAnimationFrame(func);
  2357. else if (window.oRequestAnimationFrame)
  2358. window.oRequestAnimationFrame(func);
  2359. else {
  2360. window.setTimeout(func, 16);
  2361. }
  2362. };
  2363. Tools.RequestFullscreen = function (element) {
  2364. if (element.requestFullscreen)
  2365. element.requestFullscreen();
  2366. else if (element.msRequestFullscreen)
  2367. element.msRequestFullscreen();
  2368. else if (element.webkitRequestFullscreen)
  2369. element.webkitRequestFullscreen();
  2370. else if (element.mozRequestFullScreen)
  2371. element.mozRequestFullScreen();
  2372. };
  2373. Tools.ExitFullscreen = function () {
  2374. if (document.exitFullscreen) {
  2375. document.exitFullscreen();
  2376. } else if (document.mozCancelFullScreen) {
  2377. document.mozCancelFullScreen();
  2378. } else if (document.webkitCancelFullScreen) {
  2379. document.webkitCancelFullScreen();
  2380. } else if (document.msCancelFullScreen) {
  2381. document.msCancelFullScreen();
  2382. }
  2383. };
  2384. // External files
  2385. Tools.CleanUrl = function (url) {
  2386. url = url.replace(/#/mg, "%23");
  2387. return url;
  2388. };
  2389. Tools.LoadImage = function (url, onload, onerror, database) {
  2390. url = Tools.CleanUrl(url);
  2391. var img = new Image();
  2392. if (url.substr(0, 5) != "data:")
  2393. img.crossOrigin = 'anonymous';
  2394. img.onload = function () {
  2395. onload(img);
  2396. };
  2397. img.onerror = function (err) {
  2398. onerror(img, err);
  2399. };
  2400. var noIndexedDB = function () {
  2401. img.src = url;
  2402. };
  2403. var loadFromIndexedDB = function () {
  2404. database.loadImageFromDB(url, img);
  2405. };
  2406. //ANY database to do!
  2407. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2408. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2409. } else {
  2410. if (url.indexOf("file:") === -1) {
  2411. noIndexedDB();
  2412. } else {
  2413. try {
  2414. var textureName = url.substring(5);
  2415. var blobURL;
  2416. try {
  2417. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2418. } catch (ex) {
  2419. // Chrome doesn't support oneTimeOnly parameter
  2420. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2421. }
  2422. img.src = blobURL;
  2423. } catch (e) {
  2424. Tools.Log("Error while trying to load texture: " + textureName);
  2425. img.src = null;
  2426. }
  2427. }
  2428. }
  2429. return img;
  2430. };
  2431. //ANY
  2432. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2433. url = Tools.CleanUrl(url);
  2434. var noIndexedDB = function () {
  2435. var request = new XMLHttpRequest();
  2436. var loadUrl = Tools.BaseUrl + url;
  2437. request.open('GET', loadUrl, true);
  2438. if (useArrayBuffer) {
  2439. request.responseType = "arraybuffer";
  2440. }
  2441. request.onprogress = progressCallBack;
  2442. request.onreadystatechange = function () {
  2443. if (request.readyState == 4) {
  2444. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2445. callback(!useArrayBuffer ? request.responseText : request.response);
  2446. } else {
  2447. if (onError) {
  2448. onError();
  2449. } else {
  2450. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2451. }
  2452. }
  2453. }
  2454. };
  2455. request.send(null);
  2456. };
  2457. var loadFromIndexedDB = function () {
  2458. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2459. };
  2460. if (url.indexOf("file:") !== -1) {
  2461. var fileName = url.substring(5);
  2462. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2463. } else {
  2464. // Caching all files
  2465. if (database && database.enableSceneOffline) {
  2466. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2467. } else {
  2468. noIndexedDB();
  2469. }
  2470. }
  2471. };
  2472. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2473. var reader = new FileReader();
  2474. reader.onload = function (e) {
  2475. callback(e.target.result);
  2476. };
  2477. reader.onprogress = progressCallback;
  2478. reader.readAsDataURL(fileToLoad);
  2479. };
  2480. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2481. var reader = new FileReader();
  2482. reader.onload = function (e) {
  2483. callback(e.target.result);
  2484. };
  2485. reader.onprogress = progressCallBack;
  2486. if (!useArrayBuffer) {
  2487. // Asynchronous read
  2488. reader.readAsText(fileToLoad);
  2489. } else {
  2490. reader.readAsArrayBuffer(fileToLoad);
  2491. }
  2492. };
  2493. // Misc.
  2494. Tools.Clamp = function (value, min, max) {
  2495. if (typeof min === "undefined") { min = 0; }
  2496. if (typeof max === "undefined") { max = 1; }
  2497. return Math.min(max, Math.max(min, value));
  2498. };
  2499. Tools.Format = function (value, decimals) {
  2500. if (typeof decimals === "undefined") { decimals = 2; }
  2501. return value.toFixed(decimals);
  2502. };
  2503. Tools.CheckExtends = function (v, min, max) {
  2504. if (v.x < min.x)
  2505. min.x = v.x;
  2506. if (v.y < min.y)
  2507. min.y = v.y;
  2508. if (v.z < min.z)
  2509. min.z = v.z;
  2510. if (v.x > max.x)
  2511. max.x = v.x;
  2512. if (v.y > max.y)
  2513. max.y = v.y;
  2514. if (v.z > max.z)
  2515. max.z = v.z;
  2516. };
  2517. Tools.WithinEpsilon = function (a, b, epsilon) {
  2518. if (typeof epsilon === "undefined") { epsilon = 1.401298E-45; }
  2519. var num = a - b;
  2520. return -epsilon <= num && num <= epsilon;
  2521. };
  2522. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2523. for (var prop in source) {
  2524. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2525. continue;
  2526. }
  2527. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2528. continue;
  2529. }
  2530. var sourceValue = source[prop];
  2531. var typeOfSourceValue = typeof sourceValue;
  2532. if (typeOfSourceValue == "function") {
  2533. continue;
  2534. }
  2535. if (typeOfSourceValue == "object") {
  2536. if (sourceValue instanceof Array) {
  2537. destination[prop] = [];
  2538. if (sourceValue.length > 0) {
  2539. if (typeof sourceValue[0] == "object") {
  2540. for (var index = 0; index < sourceValue.length; index++) {
  2541. var clonedValue = cloneValue(sourceValue[index], destination);
  2542. if (destination[prop].indexOf(clonedValue) === -1) {
  2543. destination[prop].push(clonedValue);
  2544. }
  2545. }
  2546. } else {
  2547. destination[prop] = sourceValue.slice(0);
  2548. }
  2549. }
  2550. } else {
  2551. destination[prop] = cloneValue(sourceValue, destination);
  2552. }
  2553. } else {
  2554. destination[prop] = sourceValue;
  2555. }
  2556. }
  2557. };
  2558. Tools.IsEmpty = function (obj) {
  2559. for (var i in obj) {
  2560. return false;
  2561. }
  2562. return true;
  2563. };
  2564. Tools.RegisterTopRootEvents = function (events) {
  2565. for (var index = 0; index < events.length; index++) {
  2566. var event = events[index];
  2567. window.addEventListener(event.name, event.handler, false);
  2568. try {
  2569. if (window.parent) {
  2570. window.parent.addEventListener(event.name, event.handler, false);
  2571. }
  2572. } catch (e) {
  2573. // Silently fails...
  2574. }
  2575. }
  2576. };
  2577. Tools.UnregisterTopRootEvents = function (events) {
  2578. for (var index = 0; index < events.length; index++) {
  2579. var event = events[index];
  2580. window.removeEventListener(event.name, event.handler);
  2581. try {
  2582. if (window.parent) {
  2583. window.parent.removeEventListener(event.name, event.handler);
  2584. }
  2585. } catch (e) {
  2586. // Silently fails...
  2587. }
  2588. }
  2589. };
  2590. Tools.CreateScreenshot = function (engine, camera, size) {
  2591. var width;
  2592. var height;
  2593. var scene = camera.getScene();
  2594. var previousCamera = null;
  2595. if (scene.activeCamera !== camera) {
  2596. previousCamera = scene.activeCamera;
  2597. scene.activeCamera = camera;
  2598. }
  2599. //If a precision value is specified
  2600. if (size.precision) {
  2601. width = Math.round(engine.getRenderWidth() * size.precision);
  2602. height = Math.round(width / engine.getAspectRatio(camera));
  2603. size = { width: width, height: height };
  2604. } else if (size.width && size.height) {
  2605. width = size.width;
  2606. height = size.height;
  2607. } else if (size.width && !size.height) {
  2608. width = size.width;
  2609. height = Math.round(width / engine.getAspectRatio(camera));
  2610. size = { width: width, height: height };
  2611. } else if (size.height && !size.width) {
  2612. height = size.height;
  2613. width = Math.round(height * engine.getAspectRatio(camera));
  2614. size = { width: width, height: height };
  2615. } else if (!isNaN(size)) {
  2616. height = size;
  2617. width = size;
  2618. } else {
  2619. Tools.Error("Invalid 'size' parameter !");
  2620. return;
  2621. }
  2622. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2623. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2624. texture.renderList = engine.scenes[0].meshes;
  2625. texture.onAfterRender = function () {
  2626. // Read the contents of the framebuffer
  2627. var numberOfChannelsByLine = width * 4;
  2628. var halfHeight = height / 2;
  2629. //Reading datas from WebGL
  2630. var data = engine.readPixels(0, 0, width, height);
  2631. for (var i = 0; i < halfHeight; i++) {
  2632. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2633. var currentCell = j + i * numberOfChannelsByLine;
  2634. var targetLine = height - i - 1;
  2635. var targetCell = j + targetLine * numberOfChannelsByLine;
  2636. var temp = data[currentCell];
  2637. data[currentCell] = data[targetCell];
  2638. data[targetCell] = temp;
  2639. }
  2640. }
  2641. // Create a 2D canvas to store the result
  2642. if (!screenshotCanvas) {
  2643. screenshotCanvas = document.createElement('canvas');
  2644. }
  2645. screenshotCanvas.width = width;
  2646. screenshotCanvas.height = height;
  2647. var context = screenshotCanvas.getContext('2d');
  2648. // Copy the pixels to a 2D canvas
  2649. var imageData = context.createImageData(width, height);
  2650. imageData.data.set(data);
  2651. context.putImageData(imageData, 0, 0);
  2652. var base64Image = screenshotCanvas.toDataURL();
  2653. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2654. if (("download" in document.createElement("a"))) {
  2655. var a = window.document.createElement("a");
  2656. a.href = base64Image;
  2657. var date = new Date();
  2658. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2659. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2660. window.document.body.appendChild(a);
  2661. a.addEventListener("click", function () {
  2662. a.parentElement.removeChild(a);
  2663. });
  2664. a.click();
  2665. //Or opening a new tab with the image if it is not possible to automatically start download.
  2666. } else {
  2667. var newWindow = window.open("");
  2668. var img = newWindow.document.createElement("img");
  2669. img.src = base64Image;
  2670. newWindow.document.body.appendChild(img);
  2671. }
  2672. };
  2673. texture.render(true);
  2674. texture.dispose();
  2675. if (previousCamera) {
  2676. scene.activeCamera = previousCamera;
  2677. }
  2678. };
  2679. // XHR response validator for local file scenario
  2680. Tools.ValidateXHRData = function (xhr, dataType) {
  2681. if (typeof dataType === "undefined") { dataType = 7; }
  2682. try {
  2683. if (dataType & 1) {
  2684. if (xhr.responseText && xhr.responseText.length > 0) {
  2685. return true;
  2686. } else if (dataType === 1) {
  2687. return false;
  2688. }
  2689. }
  2690. if (dataType & 2) {
  2691. // Check header width and height since there is no "TGA" magic number
  2692. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2693. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2694. return true;
  2695. } else if (dataType === 2) {
  2696. return false;
  2697. }
  2698. }
  2699. if (dataType & 4) {
  2700. // Check for the "DDS" magic number
  2701. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2702. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2703. return true;
  2704. } else {
  2705. return false;
  2706. }
  2707. }
  2708. } catch (e) {
  2709. // Global protection
  2710. }
  2711. return false;
  2712. };
  2713. Object.defineProperty(Tools, "NoneLogLevel", {
  2714. get: function () {
  2715. return Tools._NoneLogLevel;
  2716. },
  2717. enumerable: true,
  2718. configurable: true
  2719. });
  2720. Object.defineProperty(Tools, "MessageLogLevel", {
  2721. get: function () {
  2722. return Tools._MessageLogLevel;
  2723. },
  2724. enumerable: true,
  2725. configurable: true
  2726. });
  2727. Object.defineProperty(Tools, "WarningLogLevel", {
  2728. get: function () {
  2729. return Tools._WarningLogLevel;
  2730. },
  2731. enumerable: true,
  2732. configurable: true
  2733. });
  2734. Object.defineProperty(Tools, "ErrorLogLevel", {
  2735. get: function () {
  2736. return Tools._ErrorLogLevel;
  2737. },
  2738. enumerable: true,
  2739. configurable: true
  2740. });
  2741. Object.defineProperty(Tools, "AllLogLevel", {
  2742. get: function () {
  2743. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2744. },
  2745. enumerable: true,
  2746. configurable: true
  2747. });
  2748. Tools._AddLogEntry = function (entry) {
  2749. Tools._LogCache = entry + Tools._LogCache;
  2750. if (Tools.OnNewCacheEntry) {
  2751. Tools.OnNewCacheEntry(entry);
  2752. }
  2753. };
  2754. Tools._FormatMessage = function (message) {
  2755. var padStr = function (i) {
  2756. return (i < 10) ? "0" + i : "" + i;
  2757. };
  2758. var date = new Date();
  2759. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2760. };
  2761. Tools._LogDisabled = function (message) {
  2762. // nothing to do
  2763. };
  2764. Tools._LogEnabled = function (message) {
  2765. var formattedMessage = Tools._FormatMessage(message);
  2766. console.log("BJS - " + formattedMessage);
  2767. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2768. Tools._AddLogEntry(entry);
  2769. };
  2770. Tools._WarnDisabled = function (message) {
  2771. // nothing to do
  2772. };
  2773. Tools._WarnEnabled = function (message) {
  2774. var formattedMessage = Tools._FormatMessage(message);
  2775. console.warn("BJS - " + formattedMessage);
  2776. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2777. Tools._AddLogEntry(entry);
  2778. };
  2779. Tools._ErrorDisabled = function (message) {
  2780. // nothing to do
  2781. };
  2782. Tools._ErrorEnabled = function (message) {
  2783. var formattedMessage = Tools._FormatMessage(message);
  2784. console.error("BJS - " + formattedMessage);
  2785. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2786. Tools._AddLogEntry(entry);
  2787. };
  2788. Object.defineProperty(Tools, "LogCache", {
  2789. get: function () {
  2790. return Tools._LogCache;
  2791. },
  2792. enumerable: true,
  2793. configurable: true
  2794. });
  2795. Object.defineProperty(Tools, "LogLevels", {
  2796. set: function (level) {
  2797. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2798. Tools.Log = Tools._LogEnabled;
  2799. } else {
  2800. Tools.Log = Tools._LogDisabled;
  2801. }
  2802. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2803. Tools.Warn = Tools._WarnEnabled;
  2804. } else {
  2805. Tools.Warn = Tools._WarnDisabled;
  2806. }
  2807. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2808. Tools.Error = Tools._ErrorEnabled;
  2809. } else {
  2810. Tools.Error = Tools._ErrorDisabled;
  2811. }
  2812. },
  2813. enumerable: true,
  2814. configurable: true
  2815. });
  2816. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2817. get: function () {
  2818. return Tools._PerformanceNoneLogLevel;
  2819. },
  2820. enumerable: true,
  2821. configurable: true
  2822. });
  2823. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2824. get: function () {
  2825. return Tools._PerformanceUserMarkLogLevel;
  2826. },
  2827. enumerable: true,
  2828. configurable: true
  2829. });
  2830. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2831. get: function () {
  2832. return Tools._PerformanceConsoleLogLevel;
  2833. },
  2834. enumerable: true,
  2835. configurable: true
  2836. });
  2837. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2838. set: function (level) {
  2839. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2840. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2841. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2842. return;
  2843. }
  2844. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2845. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2846. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2847. return;
  2848. }
  2849. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2850. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2851. },
  2852. enumerable: true,
  2853. configurable: true
  2854. });
  2855. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2856. };
  2857. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2858. };
  2859. Tools._StartUserMark = function (counterName, condition) {
  2860. if (typeof condition === "undefined") { condition = true; }
  2861. if (!condition || !Tools._performance.mark) {
  2862. return;
  2863. }
  2864. Tools._performance.mark(counterName + "-Begin");
  2865. };
  2866. Tools._EndUserMark = function (counterName, condition) {
  2867. if (typeof condition === "undefined") { condition = true; }
  2868. if (!condition || !Tools._performance.mark) {
  2869. return;
  2870. }
  2871. Tools._performance.mark(counterName + "-End");
  2872. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2873. };
  2874. Tools._StartPerformanceConsole = function (counterName, condition) {
  2875. if (typeof condition === "undefined") { condition = true; }
  2876. if (!condition) {
  2877. return;
  2878. }
  2879. Tools._StartUserMark(counterName, condition);
  2880. if (console.time) {
  2881. console.time(counterName);
  2882. }
  2883. };
  2884. Tools._EndPerformanceConsole = function (counterName, condition) {
  2885. if (typeof condition === "undefined") { condition = true; }
  2886. if (!condition) {
  2887. return;
  2888. }
  2889. Tools._EndUserMark(counterName, condition);
  2890. if (console.time) {
  2891. console.timeEnd(counterName);
  2892. }
  2893. };
  2894. Object.defineProperty(Tools, "Now", {
  2895. get: function () {
  2896. if (window.performance && window.performance.now) {
  2897. return window.performance.now();
  2898. }
  2899. return new Date().getTime();
  2900. },
  2901. enumerable: true,
  2902. configurable: true
  2903. });
  2904. // Deprecated
  2905. Tools.GetFps = function () {
  2906. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2907. return 0;
  2908. };
  2909. Tools.BaseUrl = "";
  2910. Tools.GetExponantOfTwo = function (value, max) {
  2911. var count = 1;
  2912. do {
  2913. count *= 2;
  2914. } while(count < value);
  2915. if (count > max)
  2916. count = max;
  2917. return count;
  2918. };
  2919. Tools._NoneLogLevel = 0;
  2920. Tools._MessageLogLevel = 1;
  2921. Tools._WarningLogLevel = 2;
  2922. Tools._ErrorLogLevel = 4;
  2923. Tools._LogCache = "";
  2924. Tools.Log = Tools._LogEnabled;
  2925. Tools.Warn = Tools._WarnEnabled;
  2926. Tools.Error = Tools._ErrorEnabled;
  2927. Tools._PerformanceNoneLogLevel = 0;
  2928. Tools._PerformanceUserMarkLogLevel = 1;
  2929. Tools._PerformanceConsoleLogLevel = 2;
  2930. Tools._performance = window.performance;
  2931. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2932. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2933. return Tools;
  2934. })();
  2935. BABYLON.Tools = Tools;
  2936. /**
  2937. * An implementation of a loop for asynchronous functions.
  2938. */
  2939. var AsyncLoop = (function () {
  2940. /**
  2941. * Constroctor.
  2942. * @param iterations the number of iterations.
  2943. * @param _fn the function to run each iteration
  2944. * @param _successCallback the callback that will be called upon succesful execution
  2945. * @param offset starting offset.
  2946. */
  2947. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  2948. if (typeof offset === "undefined") { offset = 0; }
  2949. this.iterations = iterations;
  2950. this._fn = _fn;
  2951. this._successCallback = _successCallback;
  2952. this.index = offset - 1;
  2953. this._done = false;
  2954. }
  2955. /**
  2956. * Execute the next iteration. Must be called after the last iteration was finished.
  2957. */
  2958. AsyncLoop.prototype.executeNext = function () {
  2959. if (!this._done) {
  2960. if (this.index < this.iterations) {
  2961. ++this.index;
  2962. this._fn(this);
  2963. } else {
  2964. this.breakLoop();
  2965. }
  2966. }
  2967. };
  2968. /**
  2969. * Break the loop and run the success callback.
  2970. */
  2971. AsyncLoop.prototype.breakLoop = function () {
  2972. this._done = true;
  2973. this._successCallback();
  2974. };
  2975. /**
  2976. * Helper function
  2977. */
  2978. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  2979. if (typeof offset === "undefined") { offset = 0; }
  2980. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  2981. loop.executeNext();
  2982. return loop;
  2983. };
  2984. /**
  2985. * A for-loop that will run a given number of iterations synchronous and the rest async.
  2986. * @param iterations total number of iterations
  2987. * @param syncedIterations number of synchronous iterations in each async iteration.
  2988. * @param fn the function to call each iteration.
  2989. * @param callback a success call back that will be called when iterating stops.
  2990. * @param breakFunction a break condition (optional)
  2991. * @param timeout timeout settings for the setTimeout function. default - 0.
  2992. * @constructor
  2993. */
  2994. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  2995. if (typeof timeout === "undefined") { timeout = 0; }
  2996. var asyncLoop = new AsyncLoop(Math.ceil(iterations / syncedIterations), function (loop) {
  2997. if (breakFunction && breakFunction())
  2998. loop.breakLoop();
  2999. else {
  3000. setTimeout(function () {
  3001. for (var i = 0; i < syncedIterations; ++i) {
  3002. var iteration = (loop.index * syncedIterations) + i;
  3003. if (iteration >= iterations)
  3004. break;
  3005. fn(iteration);
  3006. if (breakFunction && breakFunction()) {
  3007. loop.breakLoop();
  3008. break;
  3009. }
  3010. }
  3011. loop.executeNext();
  3012. }, timeout);
  3013. }
  3014. }, callback);
  3015. };
  3016. return AsyncLoop;
  3017. })();
  3018. BABYLON.AsyncLoop = AsyncLoop;
  3019. })(BABYLON || (BABYLON = {}));
  3020. //# sourceMappingURL=babylon.tools.js.map
  3021. var BABYLON;
  3022. (function (BABYLON) {
  3023. var _DepthCullingState = (function () {
  3024. function _DepthCullingState() {
  3025. this._isDepthTestDirty = false;
  3026. this._isDepthMaskDirty = false;
  3027. this._isDepthFuncDirty = false;
  3028. this._isCullFaceDirty = false;
  3029. this._isCullDirty = false;
  3030. }
  3031. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3032. get: function () {
  3033. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3034. },
  3035. enumerable: true,
  3036. configurable: true
  3037. });
  3038. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3039. get: function () {
  3040. return this._cullFace;
  3041. },
  3042. set: function (value) {
  3043. if (this._cullFace === value) {
  3044. return;
  3045. }
  3046. this._cullFace = value;
  3047. this._isCullFaceDirty = true;
  3048. },
  3049. enumerable: true,
  3050. configurable: true
  3051. });
  3052. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3053. get: function () {
  3054. return this._cull;
  3055. },
  3056. set: function (value) {
  3057. if (this._cull === value) {
  3058. return;
  3059. }
  3060. this._cull = value;
  3061. this._isCullDirty = true;
  3062. },
  3063. enumerable: true,
  3064. configurable: true
  3065. });
  3066. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3067. get: function () {
  3068. return this._depthFunc;
  3069. },
  3070. set: function (value) {
  3071. if (this._depthFunc === value) {
  3072. return;
  3073. }
  3074. this._depthFunc = value;
  3075. this._isDepthFuncDirty = true;
  3076. },
  3077. enumerable: true,
  3078. configurable: true
  3079. });
  3080. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3081. get: function () {
  3082. return this._depthMask;
  3083. },
  3084. set: function (value) {
  3085. if (this._depthMask === value) {
  3086. return;
  3087. }
  3088. this._depthMask = value;
  3089. this._isDepthMaskDirty = true;
  3090. },
  3091. enumerable: true,
  3092. configurable: true
  3093. });
  3094. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3095. get: function () {
  3096. return this._depthTest;
  3097. },
  3098. set: function (value) {
  3099. if (this._depthTest === value) {
  3100. return;
  3101. }
  3102. this._depthTest = value;
  3103. this._isDepthTestDirty = true;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. _DepthCullingState.prototype.reset = function () {
  3109. this._depthMask = true;
  3110. this._depthTest = true;
  3111. this._depthFunc = null;
  3112. this._cull = null;
  3113. this._cullFace = null;
  3114. this._isDepthTestDirty = true;
  3115. this._isDepthMaskDirty = true;
  3116. this._isDepthFuncDirty = false;
  3117. this._isCullFaceDirty = false;
  3118. this._isCullDirty = false;
  3119. };
  3120. _DepthCullingState.prototype.apply = function (gl) {
  3121. if (!this.isDirty) {
  3122. return;
  3123. }
  3124. // Cull
  3125. if (this._isCullDirty) {
  3126. if (this.cull) {
  3127. gl.enable(gl.CULL_FACE);
  3128. } else {
  3129. gl.disable(gl.CULL_FACE);
  3130. }
  3131. this._isCullDirty = false;
  3132. }
  3133. // Cull face
  3134. if (this._isCullFaceDirty) {
  3135. gl.cullFace(this.cullFace);
  3136. this._isCullFaceDirty = false;
  3137. }
  3138. // Depth mask
  3139. if (this._isDepthMaskDirty) {
  3140. gl.depthMask(this.depthMask);
  3141. this._isDepthMaskDirty = false;
  3142. }
  3143. // Depth test
  3144. if (this._isDepthTestDirty) {
  3145. if (this.depthTest) {
  3146. gl.enable(gl.DEPTH_TEST);
  3147. } else {
  3148. gl.disable(gl.DEPTH_TEST);
  3149. }
  3150. this._isDepthTestDirty = false;
  3151. }
  3152. // Depth func
  3153. if (this._isDepthFuncDirty) {
  3154. gl.depthFunc(this.depthFunc);
  3155. this._isDepthFuncDirty = false;
  3156. }
  3157. };
  3158. return _DepthCullingState;
  3159. })();
  3160. BABYLON._DepthCullingState = _DepthCullingState;
  3161. var _AlphaState = (function () {
  3162. function _AlphaState() {
  3163. this._isAlphaBlendDirty = false;
  3164. this._isBlendFunctionParametersDirty = false;
  3165. this._alphaBlend = false;
  3166. this._blendFunctionParameters = new Array(4);
  3167. }
  3168. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3169. get: function () {
  3170. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3171. },
  3172. enumerable: true,
  3173. configurable: true
  3174. });
  3175. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3176. get: function () {
  3177. return this._alphaBlend;
  3178. },
  3179. set: function (value) {
  3180. if (this._alphaBlend === value) {
  3181. return;
  3182. }
  3183. this._alphaBlend = value;
  3184. this._isAlphaBlendDirty = true;
  3185. },
  3186. enumerable: true,
  3187. configurable: true
  3188. });
  3189. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3190. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3191. return;
  3192. }
  3193. this._blendFunctionParameters[0] = value0;
  3194. this._blendFunctionParameters[1] = value1;
  3195. this._blendFunctionParameters[2] = value2;
  3196. this._blendFunctionParameters[3] = value3;
  3197. this._isBlendFunctionParametersDirty = true;
  3198. };
  3199. _AlphaState.prototype.reset = function () {
  3200. this._alphaBlend = false;
  3201. this._blendFunctionParameters[0] = null;
  3202. this._blendFunctionParameters[1] = null;
  3203. this._blendFunctionParameters[2] = null;
  3204. this._blendFunctionParameters[3] = null;
  3205. this._isAlphaBlendDirty = true;
  3206. this._isBlendFunctionParametersDirty = false;
  3207. };
  3208. _AlphaState.prototype.apply = function (gl) {
  3209. if (!this.isDirty) {
  3210. return;
  3211. }
  3212. // Alpha blend
  3213. if (this._isAlphaBlendDirty) {
  3214. if (this._alphaBlend) {
  3215. gl.enable(gl.BLEND);
  3216. } else {
  3217. gl.disable(gl.BLEND);
  3218. }
  3219. this._isAlphaBlendDirty = false;
  3220. }
  3221. // Alpha function
  3222. if (this._isBlendFunctionParametersDirty) {
  3223. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3224. this._isBlendFunctionParametersDirty = false;
  3225. }
  3226. };
  3227. return _AlphaState;
  3228. })();
  3229. BABYLON._AlphaState = _AlphaState;
  3230. var compileShader = function (gl, source, type, defines) {
  3231. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3232. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3233. gl.compileShader(shader);
  3234. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3235. throw new Error(gl.getShaderInfoLog(shader));
  3236. }
  3237. return shader;
  3238. };
  3239. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3240. var magFilter = gl.NEAREST;
  3241. var minFilter = gl.NEAREST;
  3242. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3243. magFilter = gl.LINEAR;
  3244. if (generateMipMaps) {
  3245. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3246. } else {
  3247. minFilter = gl.LINEAR;
  3248. }
  3249. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3250. magFilter = gl.LINEAR;
  3251. if (generateMipMaps) {
  3252. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3253. } else {
  3254. minFilter = gl.LINEAR;
  3255. }
  3256. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3257. magFilter = gl.NEAREST;
  3258. if (generateMipMaps) {
  3259. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3260. } else {
  3261. minFilter = gl.NEAREST;
  3262. }
  3263. }
  3264. return {
  3265. min: minFilter,
  3266. mag: magFilter
  3267. };
  3268. };
  3269. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3270. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3271. var engine = scene.getEngine();
  3272. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3273. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3274. gl.bindTexture(gl.TEXTURE_2D, texture);
  3275. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3276. processFunction(potWidth, potHeight);
  3277. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3278. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3279. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3280. if (!noMipmap && !isCompressed) {
  3281. gl.generateMipmap(gl.TEXTURE_2D);
  3282. }
  3283. gl.bindTexture(gl.TEXTURE_2D, null);
  3284. engine._activeTexturesCache = [];
  3285. texture._baseWidth = width;
  3286. texture._baseHeight = height;
  3287. texture._width = potWidth;
  3288. texture._height = potHeight;
  3289. texture.isReady = true;
  3290. texture.samplingMode = samplingMode;
  3291. scene._removePendingData(texture);
  3292. };
  3293. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3294. var onload = function () {
  3295. loadedImages[index] = img;
  3296. loadedImages._internalCount++;
  3297. scene._removePendingData(img);
  3298. if (loadedImages._internalCount === 6) {
  3299. onfinish(loadedImages);
  3300. }
  3301. };
  3302. var onerror = function () {
  3303. scene._removePendingData(img);
  3304. };
  3305. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3306. scene._addPendingData(img);
  3307. };
  3308. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3309. var loadedImages = [];
  3310. loadedImages._internalCount = 0;
  3311. for (var index = 0; index < 6; index++) {
  3312. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3313. }
  3314. };
  3315. var EngineCapabilities = (function () {
  3316. function EngineCapabilities() {
  3317. }
  3318. return EngineCapabilities;
  3319. })();
  3320. BABYLON.EngineCapabilities = EngineCapabilities;
  3321. var Engine = (function () {
  3322. function Engine(canvas, antialias, options) {
  3323. var _this = this;
  3324. // Public members
  3325. this.isFullscreen = false;
  3326. this.isPointerLock = false;
  3327. this.cullBackFaces = true;
  3328. this.renderEvenInBackground = true;
  3329. this.scenes = new Array();
  3330. this._windowIsBackground = false;
  3331. this._loadingDivBackgroundColor = "black";
  3332. this._drawCalls = 0;
  3333. this._renderingQueueLaunched = false;
  3334. this._activeRenderLoops = [];
  3335. // FPS
  3336. this.fpsRange = 60;
  3337. this.previousFramesDuration = [];
  3338. this.fps = 60;
  3339. this.deltaTime = 0;
  3340. // States
  3341. this._depthCullingState = new _DepthCullingState();
  3342. this._alphaState = new _AlphaState();
  3343. this._alphaMode = Engine.ALPHA_DISABLE;
  3344. // Cache
  3345. this._loadedTexturesCache = new Array();
  3346. this._activeTexturesCache = new Array();
  3347. this._compiledEffects = {};
  3348. this._uintIndicesCurrentlySet = false;
  3349. this._renderingCanvas = canvas;
  3350. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3351. options = options || {};
  3352. options.antialias = antialias;
  3353. try {
  3354. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3355. } catch (e) {
  3356. throw new Error("WebGL not supported");
  3357. }
  3358. if (!this._gl) {
  3359. throw new Error("WebGL not supported");
  3360. }
  3361. this._onBlur = function () {
  3362. _this._windowIsBackground = true;
  3363. };
  3364. this._onFocus = function () {
  3365. _this._windowIsBackground = false;
  3366. };
  3367. window.addEventListener("blur", this._onBlur);
  3368. window.addEventListener("focus", this._onFocus);
  3369. // Textures
  3370. this._workingCanvas = document.createElement("canvas");
  3371. this._workingContext = this._workingCanvas.getContext("2d");
  3372. // Viewport
  3373. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3374. this.resize();
  3375. // Caps
  3376. this._caps = new EngineCapabilities();
  3377. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3378. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3379. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3380. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3381. // Infos
  3382. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3383. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3384. if (rendererInfo != null) {
  3385. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3386. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3387. }
  3388. if (!this._glVendor) {
  3389. this._glVendor = "Unknown vendor";
  3390. }
  3391. if (!this._glRenderer) {
  3392. this._glRenderer = "Unknown renderer";
  3393. }
  3394. // Extensions
  3395. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3396. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3397. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3398. 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');
  3399. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3400. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3401. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3402. // Depth buffer
  3403. this.setDepthBuffer(true);
  3404. this.setDepthFunctionToLessOrEqual();
  3405. this.setDepthWrite(true);
  3406. // Fullscreen
  3407. this._onFullscreenChange = function () {
  3408. if (document.fullscreen !== undefined) {
  3409. _this.isFullscreen = document.fullscreen;
  3410. } else if (document.mozFullScreen !== undefined) {
  3411. _this.isFullscreen = document.mozFullScreen;
  3412. } else if (document.webkitIsFullScreen !== undefined) {
  3413. _this.isFullscreen = document.webkitIsFullScreen;
  3414. } else if (document.msIsFullScreen !== undefined) {
  3415. _this.isFullscreen = document.msIsFullScreen;
  3416. }
  3417. // Pointer lock
  3418. if (_this.isFullscreen && _this._pointerLockRequested) {
  3419. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3420. if (canvas.requestPointerLock) {
  3421. canvas.requestPointerLock();
  3422. }
  3423. }
  3424. };
  3425. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3426. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3427. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3428. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3429. // Pointer lock
  3430. this._onPointerLockChange = function () {
  3431. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3432. };
  3433. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3434. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3435. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3436. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3437. this._audioEngine = new BABYLON.AudioEngine();
  3438. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3439. }
  3440. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3441. get: function () {
  3442. return Engine._ALPHA_DISABLE;
  3443. },
  3444. enumerable: true,
  3445. configurable: true
  3446. });
  3447. Object.defineProperty(Engine, "ALPHA_ADD", {
  3448. get: function () {
  3449. return Engine._ALPHA_ADD;
  3450. },
  3451. enumerable: true,
  3452. configurable: true
  3453. });
  3454. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3455. get: function () {
  3456. return Engine._ALPHA_COMBINE;
  3457. },
  3458. enumerable: true,
  3459. configurable: true
  3460. });
  3461. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3462. get: function () {
  3463. return Engine._DELAYLOADSTATE_NONE;
  3464. },
  3465. enumerable: true,
  3466. configurable: true
  3467. });
  3468. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3469. get: function () {
  3470. return Engine._DELAYLOADSTATE_LOADED;
  3471. },
  3472. enumerable: true,
  3473. configurable: true
  3474. });
  3475. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3476. get: function () {
  3477. return Engine._DELAYLOADSTATE_LOADING;
  3478. },
  3479. enumerable: true,
  3480. configurable: true
  3481. });
  3482. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3483. get: function () {
  3484. return Engine._DELAYLOADSTATE_NOTLOADED;
  3485. },
  3486. enumerable: true,
  3487. configurable: true
  3488. });
  3489. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3490. get: function () {
  3491. return Engine._TEXTUREFORMAT_ALPHA;
  3492. },
  3493. enumerable: true,
  3494. configurable: true
  3495. });
  3496. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3497. get: function () {
  3498. return Engine._TEXTUREFORMAT_LUMINANCE;
  3499. },
  3500. enumerable: true,
  3501. configurable: true
  3502. });
  3503. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3504. get: function () {
  3505. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3506. },
  3507. enumerable: true,
  3508. configurable: true
  3509. });
  3510. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3511. get: function () {
  3512. return Engine._TEXTUREFORMAT_RGB;
  3513. },
  3514. enumerable: true,
  3515. configurable: true
  3516. });
  3517. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3518. get: function () {
  3519. return Engine._TEXTUREFORMAT_RGBA;
  3520. },
  3521. enumerable: true,
  3522. configurable: true
  3523. });
  3524. Object.defineProperty(Engine, "Version", {
  3525. get: function () {
  3526. return "2.0.0";
  3527. },
  3528. enumerable: true,
  3529. configurable: true
  3530. });
  3531. Engine.prototype.getGlInfo = function () {
  3532. return {
  3533. vendor: this._glVendor,
  3534. renderer: this._glRenderer,
  3535. version: this._glVersion
  3536. };
  3537. };
  3538. Engine.prototype.getAudioEngine = function () {
  3539. return this._audioEngine;
  3540. };
  3541. Engine.prototype.getAspectRatio = function (camera) {
  3542. var viewport = camera.viewport;
  3543. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3544. };
  3545. Engine.prototype.getRenderWidth = function () {
  3546. if (this._currentRenderTarget) {
  3547. return this._currentRenderTarget._width;
  3548. }
  3549. return this._renderingCanvas.width;
  3550. };
  3551. Engine.prototype.getRenderHeight = function () {
  3552. if (this._currentRenderTarget) {
  3553. return this._currentRenderTarget._height;
  3554. }
  3555. return this._renderingCanvas.height;
  3556. };
  3557. Engine.prototype.getRenderingCanvas = function () {
  3558. return this._renderingCanvas;
  3559. };
  3560. Engine.prototype.getRenderingCanvasClientRect = function () {
  3561. return this._renderingCanvas.getBoundingClientRect();
  3562. };
  3563. Engine.prototype.setHardwareScalingLevel = function (level) {
  3564. this._hardwareScalingLevel = level;
  3565. this.resize();
  3566. };
  3567. Engine.prototype.getHardwareScalingLevel = function () {
  3568. return this._hardwareScalingLevel;
  3569. };
  3570. Engine.prototype.getLoadedTexturesCache = function () {
  3571. return this._loadedTexturesCache;
  3572. };
  3573. Engine.prototype.getCaps = function () {
  3574. return this._caps;
  3575. };
  3576. Object.defineProperty(Engine.prototype, "drawCalls", {
  3577. get: function () {
  3578. return this._drawCalls;
  3579. },
  3580. enumerable: true,
  3581. configurable: true
  3582. });
  3583. // Methods
  3584. Engine.prototype.resetDrawCalls = function () {
  3585. this._drawCalls = 0;
  3586. };
  3587. Engine.prototype.setDepthFunctionToGreater = function () {
  3588. this._depthCullingState.depthFunc = this._gl.GREATER;
  3589. };
  3590. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3591. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3592. };
  3593. Engine.prototype.setDepthFunctionToLess = function () {
  3594. this._depthCullingState.depthFunc = this._gl.LESS;
  3595. };
  3596. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3597. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3598. };
  3599. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3600. if (!renderFunction) {
  3601. this._activeRenderLoops = [];
  3602. return;
  3603. }
  3604. var index = this._activeRenderLoops.indexOf(renderFunction);
  3605. if (index >= 0) {
  3606. this._activeRenderLoops.splice(index, 1);
  3607. }
  3608. };
  3609. Engine.prototype._renderLoop = function () {
  3610. var _this = this;
  3611. var shouldRender = true;
  3612. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3613. shouldRender = false;
  3614. }
  3615. if (shouldRender) {
  3616. // Start new frame
  3617. this.beginFrame();
  3618. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3619. var renderFunction = this._activeRenderLoops[index];
  3620. renderFunction();
  3621. }
  3622. // Present
  3623. this.endFrame();
  3624. }
  3625. if (this._activeRenderLoops.length > 0) {
  3626. // Register new frame
  3627. BABYLON.Tools.QueueNewFrame(function () {
  3628. _this._renderLoop();
  3629. });
  3630. } else {
  3631. this._renderingQueueLaunched = false;
  3632. }
  3633. };
  3634. Engine.prototype.runRenderLoop = function (renderFunction) {
  3635. var _this = this;
  3636. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3637. return;
  3638. }
  3639. this._activeRenderLoops.push(renderFunction);
  3640. if (!this._renderingQueueLaunched) {
  3641. this._renderingQueueLaunched = true;
  3642. BABYLON.Tools.QueueNewFrame(function () {
  3643. _this._renderLoop();
  3644. });
  3645. }
  3646. };
  3647. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3648. if (this.isFullscreen) {
  3649. BABYLON.Tools.ExitFullscreen();
  3650. } else {
  3651. this._pointerLockRequested = requestPointerLock;
  3652. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3653. }
  3654. };
  3655. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3656. this.applyStates();
  3657. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3658. if (this._depthCullingState.depthMask) {
  3659. this._gl.clearDepth(1.0);
  3660. }
  3661. var mode = 0;
  3662. if (backBuffer)
  3663. mode |= this._gl.COLOR_BUFFER_BIT;
  3664. if (depthStencil && this._depthCullingState.depthMask)
  3665. mode |= this._gl.DEPTH_BUFFER_BIT;
  3666. this._gl.clear(mode);
  3667. };
  3668. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3669. var width = requiredWidth || this._renderingCanvas.width;
  3670. var height = requiredHeight || this._renderingCanvas.height;
  3671. var x = viewport.x || 0;
  3672. var y = viewport.y || 0;
  3673. this._cachedViewport = viewport;
  3674. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3675. };
  3676. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3677. this._cachedViewport = null;
  3678. this._gl.viewport(x, y, width, height);
  3679. };
  3680. Engine.prototype.beginFrame = function () {
  3681. this._measureFps();
  3682. };
  3683. Engine.prototype.endFrame = function () {
  3684. this.flushFramebuffer();
  3685. };
  3686. Engine.prototype.resize = function () {
  3687. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3688. };
  3689. Engine.prototype.setSize = function (width, height) {
  3690. this._renderingCanvas.width = width;
  3691. this._renderingCanvas.height = height;
  3692. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3693. };
  3694. Engine.prototype.bindFramebuffer = function (texture) {
  3695. this._currentRenderTarget = texture;
  3696. var gl = this._gl;
  3697. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3698. this._gl.viewport(0, 0, texture._width, texture._height);
  3699. this.wipeCaches();
  3700. };
  3701. Engine.prototype.unBindFramebuffer = function (texture) {
  3702. this._currentRenderTarget = null;
  3703. if (texture.generateMipMaps) {
  3704. var gl = this._gl;
  3705. gl.bindTexture(gl.TEXTURE_2D, texture);
  3706. gl.generateMipmap(gl.TEXTURE_2D);
  3707. gl.bindTexture(gl.TEXTURE_2D, null);
  3708. }
  3709. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3710. };
  3711. Engine.prototype.flushFramebuffer = function () {
  3712. // this._gl.flush();
  3713. };
  3714. Engine.prototype.restoreDefaultFramebuffer = function () {
  3715. this._currentRenderTarget = null;
  3716. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3717. this.setViewport(this._cachedViewport);
  3718. this.wipeCaches();
  3719. };
  3720. // VBOs
  3721. Engine.prototype._resetVertexBufferBinding = function () {
  3722. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3723. this._cachedVertexBuffers = null;
  3724. };
  3725. Engine.prototype.createVertexBuffer = function (vertices) {
  3726. var vbo = this._gl.createBuffer();
  3727. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3728. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3729. this._resetVertexBufferBinding();
  3730. vbo.references = 1;
  3731. return vbo;
  3732. };
  3733. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3734. var vbo = this._gl.createBuffer();
  3735. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3736. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3737. this._resetVertexBufferBinding();
  3738. vbo.references = 1;
  3739. return vbo;
  3740. };
  3741. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3742. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3743. if (offset === undefined) {
  3744. offset = 0;
  3745. }
  3746. if (vertices instanceof Float32Array) {
  3747. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3748. } else {
  3749. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3750. }
  3751. this._resetVertexBufferBinding();
  3752. };
  3753. Engine.prototype._resetIndexBufferBinding = function () {
  3754. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3755. this._cachedIndexBuffer = null;
  3756. };
  3757. Engine.prototype.createIndexBuffer = function (indices) {
  3758. var vbo = this._gl.createBuffer();
  3759. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3760. // Check for 32 bits indices
  3761. var arrayBuffer;
  3762. var need32Bits = false;
  3763. if (this._caps.uintIndices) {
  3764. for (var index = 0; index < indices.length; index++) {
  3765. if (indices[index] > 65535) {
  3766. need32Bits = true;
  3767. break;
  3768. }
  3769. }
  3770. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3771. } else {
  3772. arrayBuffer = new Uint16Array(indices);
  3773. }
  3774. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3775. this._resetIndexBufferBinding();
  3776. vbo.references = 1;
  3777. vbo.is32Bits = need32Bits;
  3778. return vbo;
  3779. };
  3780. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3781. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3782. this._cachedVertexBuffers = vertexBuffer;
  3783. this._cachedEffectForVertexBuffers = effect;
  3784. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3785. var offset = 0;
  3786. for (var index = 0; index < vertexDeclaration.length; index++) {
  3787. var order = effect.getAttributeLocation(index);
  3788. if (order >= 0) {
  3789. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3790. }
  3791. offset += vertexDeclaration[index] * 4;
  3792. }
  3793. }
  3794. if (this._cachedIndexBuffer !== indexBuffer) {
  3795. this._cachedIndexBuffer = indexBuffer;
  3796. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3797. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3798. }
  3799. };
  3800. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3801. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3802. this._cachedVertexBuffers = vertexBuffers;
  3803. this._cachedEffectForVertexBuffers = effect;
  3804. var attributes = effect.getAttributesNames();
  3805. for (var index = 0; index < attributes.length; index++) {
  3806. var order = effect.getAttributeLocation(index);
  3807. if (order >= 0) {
  3808. var vertexBuffer = vertexBuffers[attributes[index]];
  3809. if (!vertexBuffer) {
  3810. continue;
  3811. }
  3812. var stride = vertexBuffer.getStrideSize();
  3813. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3814. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3815. }
  3816. }
  3817. }
  3818. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3819. this._cachedIndexBuffer = indexBuffer;
  3820. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3821. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3822. }
  3823. };
  3824. Engine.prototype._releaseBuffer = function (buffer) {
  3825. buffer.references--;
  3826. if (buffer.references === 0) {
  3827. this._gl.deleteBuffer(buffer);
  3828. return true;
  3829. }
  3830. return false;
  3831. };
  3832. Engine.prototype.createInstancesBuffer = function (capacity) {
  3833. var buffer = this._gl.createBuffer();
  3834. buffer.capacity = capacity;
  3835. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3836. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3837. return buffer;
  3838. };
  3839. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3840. this._gl.deleteBuffer(buffer);
  3841. };
  3842. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3843. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3844. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3845. for (var index = 0; index < 4; index++) {
  3846. var offsetLocation = offsetLocations[index];
  3847. this._gl.enableVertexAttribArray(offsetLocation);
  3848. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3849. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3850. }
  3851. };
  3852. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3853. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3854. for (var index = 0; index < 4; index++) {
  3855. var offsetLocation = offsetLocations[index];
  3856. this._gl.disableVertexAttribArray(offsetLocation);
  3857. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3858. }
  3859. };
  3860. Engine.prototype.applyStates = function () {
  3861. this._depthCullingState.apply(this._gl);
  3862. this._alphaState.apply(this._gl);
  3863. };
  3864. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3865. // Apply states
  3866. this.applyStates();
  3867. this._drawCalls++;
  3868. // Render
  3869. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3870. if (instancesCount) {
  3871. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3872. return;
  3873. }
  3874. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3875. };
  3876. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3877. // Apply states
  3878. this.applyStates();
  3879. this._drawCalls++;
  3880. if (instancesCount) {
  3881. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3882. return;
  3883. }
  3884. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3885. };
  3886. // Shaders
  3887. Engine.prototype._releaseEffect = function (effect) {
  3888. if (this._compiledEffects[effect._key]) {
  3889. delete this._compiledEffects[effect._key];
  3890. if (effect.getProgram()) {
  3891. this._gl.deleteProgram(effect.getProgram());
  3892. }
  3893. }
  3894. };
  3895. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3896. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3897. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3898. var name = vertex + "+" + fragment + "@" + defines;
  3899. if (this._compiledEffects[name]) {
  3900. return this._compiledEffects[name];
  3901. }
  3902. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3903. effect._key = name;
  3904. this._compiledEffects[name] = effect;
  3905. return effect;
  3906. };
  3907. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3908. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3909. if (typeof samplers === "undefined") { samplers = []; }
  3910. if (typeof defines === "undefined") { defines = ""; }
  3911. return this.createEffect({
  3912. vertex: "particles",
  3913. fragmentElement: fragmentName
  3914. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3915. };
  3916. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3917. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3918. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3919. var shaderProgram = this._gl.createProgram();
  3920. this._gl.attachShader(shaderProgram, vertexShader);
  3921. this._gl.attachShader(shaderProgram, fragmentShader);
  3922. this._gl.linkProgram(shaderProgram);
  3923. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3924. if (!linked) {
  3925. var error = this._gl.getProgramInfoLog(shaderProgram);
  3926. if (error) {
  3927. throw new Error(error);
  3928. }
  3929. }
  3930. this._gl.deleteShader(vertexShader);
  3931. this._gl.deleteShader(fragmentShader);
  3932. return shaderProgram;
  3933. };
  3934. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3935. var results = [];
  3936. for (var index = 0; index < uniformsNames.length; index++) {
  3937. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3938. }
  3939. return results;
  3940. };
  3941. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3942. var results = [];
  3943. for (var index = 0; index < attributesNames.length; index++) {
  3944. try {
  3945. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3946. } catch (e) {
  3947. results.push(-1);
  3948. }
  3949. }
  3950. return results;
  3951. };
  3952. Engine.prototype.enableEffect = function (effect) {
  3953. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3954. if (effect && effect.onBind) {
  3955. effect.onBind(effect);
  3956. }
  3957. return;
  3958. }
  3959. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3960. // Use program
  3961. this._gl.useProgram(effect.getProgram());
  3962. for (var i in this._vertexAttribArrays) {
  3963. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3964. continue;
  3965. }
  3966. this._vertexAttribArrays[i] = false;
  3967. this._gl.disableVertexAttribArray(i);
  3968. }
  3969. var attributesCount = effect.getAttributesCount();
  3970. for (var index = 0; index < attributesCount; index++) {
  3971. // Attributes
  3972. var order = effect.getAttributeLocation(index);
  3973. if (order >= 0) {
  3974. this._vertexAttribArrays[order] = true;
  3975. this._gl.enableVertexAttribArray(order);
  3976. }
  3977. }
  3978. this._currentEffect = effect;
  3979. if (effect.onBind) {
  3980. effect.onBind(effect);
  3981. }
  3982. };
  3983. Engine.prototype.setArray = function (uniform, array) {
  3984. if (!uniform)
  3985. return;
  3986. this._gl.uniform1fv(uniform, array);
  3987. };
  3988. Engine.prototype.setMatrices = function (uniform, matrices) {
  3989. if (!uniform)
  3990. return;
  3991. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3992. };
  3993. Engine.prototype.setMatrix = function (uniform, matrix) {
  3994. if (!uniform)
  3995. return;
  3996. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3997. };
  3998. Engine.prototype.setFloat = function (uniform, value) {
  3999. if (!uniform)
  4000. return;
  4001. this._gl.uniform1f(uniform, value);
  4002. };
  4003. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4004. if (!uniform)
  4005. return;
  4006. this._gl.uniform2f(uniform, x, y);
  4007. };
  4008. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4009. if (!uniform)
  4010. return;
  4011. this._gl.uniform3f(uniform, x, y, z);
  4012. };
  4013. Engine.prototype.setBool = function (uniform, bool) {
  4014. if (!uniform)
  4015. return;
  4016. this._gl.uniform1i(uniform, bool);
  4017. };
  4018. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4019. if (!uniform)
  4020. return;
  4021. this._gl.uniform4f(uniform, x, y, z, w);
  4022. };
  4023. Engine.prototype.setColor3 = function (uniform, color3) {
  4024. if (!uniform)
  4025. return;
  4026. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4027. };
  4028. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4029. if (!uniform)
  4030. return;
  4031. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4032. };
  4033. // States
  4034. Engine.prototype.setState = function (culling, force) {
  4035. // Culling
  4036. if (this._depthCullingState.cull !== culling || force) {
  4037. if (culling) {
  4038. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4039. this._depthCullingState.cull = true;
  4040. } else {
  4041. this._depthCullingState.cull = false;
  4042. }
  4043. }
  4044. };
  4045. Engine.prototype.setDepthBuffer = function (enable) {
  4046. this._depthCullingState.depthTest = enable;
  4047. };
  4048. Engine.prototype.getDepthWrite = function () {
  4049. return this._depthCullingState.depthMask;
  4050. };
  4051. Engine.prototype.setDepthWrite = function (enable) {
  4052. this._depthCullingState.depthMask = enable;
  4053. };
  4054. Engine.prototype.setColorWrite = function (enable) {
  4055. this._gl.colorMask(enable, enable, enable, enable);
  4056. };
  4057. Engine.prototype.setAlphaMode = function (mode) {
  4058. switch (mode) {
  4059. case Engine.ALPHA_DISABLE:
  4060. this.setDepthWrite(true);
  4061. this._alphaState.alphaBlend = false;
  4062. break;
  4063. case Engine.ALPHA_COMBINE:
  4064. this.setDepthWrite(false);
  4065. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4066. this._alphaState.alphaBlend = true;
  4067. break;
  4068. case Engine.ALPHA_ADD:
  4069. this.setDepthWrite(false);
  4070. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4071. this._alphaState.alphaBlend = true;
  4072. break;
  4073. }
  4074. this._alphaMode = mode;
  4075. };
  4076. Engine.prototype.getAlphaMode = function () {
  4077. return this._alphaMode;
  4078. };
  4079. Engine.prototype.setAlphaTesting = function (enable) {
  4080. this._alphaTest = enable;
  4081. };
  4082. Engine.prototype.getAlphaTesting = function () {
  4083. return this._alphaTest;
  4084. };
  4085. // Textures
  4086. Engine.prototype.wipeCaches = function () {
  4087. this._activeTexturesCache = [];
  4088. this._currentEffect = null;
  4089. this._depthCullingState.reset();
  4090. this._alphaState.reset();
  4091. this._cachedVertexBuffers = null;
  4092. this._cachedIndexBuffer = null;
  4093. this._cachedEffectForVertexBuffers = null;
  4094. };
  4095. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4096. var gl = this._gl;
  4097. gl.bindTexture(gl.TEXTURE_2D, texture);
  4098. var magFilter = gl.NEAREST;
  4099. var minFilter = gl.NEAREST;
  4100. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4101. magFilter = gl.LINEAR;
  4102. minFilter = gl.LINEAR;
  4103. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4104. magFilter = gl.LINEAR;
  4105. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4106. }
  4107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4109. gl.bindTexture(gl.TEXTURE_2D, null);
  4110. texture.samplingMode = samplingMode;
  4111. };
  4112. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4113. var _this = this;
  4114. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4115. if (typeof onLoad === "undefined") { onLoad = null; }
  4116. if (typeof onError === "undefined") { onError = null; }
  4117. if (typeof buffer === "undefined") { buffer = null; }
  4118. var texture = this._gl.createTexture();
  4119. var extension;
  4120. var fromData = false;
  4121. if (url.substr(0, 5) === "data:") {
  4122. fromData = true;
  4123. }
  4124. if (!fromData)
  4125. extension = url.substr(url.length - 4, 4).toLowerCase();
  4126. else {
  4127. var oldUrl = url;
  4128. fromData = oldUrl.split(':');
  4129. url = oldUrl;
  4130. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4131. }
  4132. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4133. var isTGA = (extension === ".tga");
  4134. scene._addPendingData(texture);
  4135. texture.url = url;
  4136. texture.noMipmap = noMipmap;
  4137. texture.references = 1;
  4138. this._loadedTexturesCache.push(texture);
  4139. var onerror = function () {
  4140. scene._removePendingData(texture);
  4141. if (onError) {
  4142. onError();
  4143. }
  4144. };
  4145. if (isTGA) {
  4146. var callback = function (arrayBuffer) {
  4147. var data = new Uint8Array(arrayBuffer);
  4148. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4149. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4150. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4151. if (onLoad) {
  4152. onLoad();
  4153. }
  4154. }, samplingMode);
  4155. };
  4156. if (!(fromData instanceof Array))
  4157. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4158. callback(arrayBuffer);
  4159. }, onerror, scene.database, true);
  4160. else
  4161. callback(buffer);
  4162. } else if (isDDS) {
  4163. callback = function (data) {
  4164. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4165. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4166. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4167. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4168. if (onLoad) {
  4169. onLoad();
  4170. }
  4171. }, samplingMode);
  4172. };
  4173. if (!(fromData instanceof Array))
  4174. BABYLON.Tools.LoadFile(url, function (data) {
  4175. callback(data);
  4176. }, onerror, scene.database, true);
  4177. else
  4178. callback(buffer);
  4179. } else {
  4180. var onload = function (img) {
  4181. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4182. var isPot = (img.width === potWidth && img.height === potHeight);
  4183. if (!isPot) {
  4184. _this._workingCanvas.width = potWidth;
  4185. _this._workingCanvas.height = potHeight;
  4186. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4187. _this._workingContext.imageSmoothingEnabled = false;
  4188. _this._workingContext.mozImageSmoothingEnabled = false;
  4189. _this._workingContext.oImageSmoothingEnabled = false;
  4190. _this._workingContext.webkitImageSmoothingEnabled = false;
  4191. _this._workingContext.msImageSmoothingEnabled = false;
  4192. }
  4193. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4194. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4195. _this._workingContext.imageSmoothingEnabled = true;
  4196. _this._workingContext.mozImageSmoothingEnabled = true;
  4197. _this._workingContext.oImageSmoothingEnabled = true;
  4198. _this._workingContext.webkitImageSmoothingEnabled = true;
  4199. _this._workingContext.msImageSmoothingEnabled = true;
  4200. }
  4201. }
  4202. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4203. if (onLoad) {
  4204. onLoad();
  4205. }
  4206. }, samplingMode);
  4207. };
  4208. if (!(fromData instanceof Array))
  4209. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4210. else
  4211. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4212. }
  4213. return texture;
  4214. };
  4215. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4216. var texture = this._gl.createTexture();
  4217. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4218. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4219. // Format
  4220. var internalFormat = this._gl.RGBA;
  4221. switch (format) {
  4222. case Engine.TEXTUREFORMAT_ALPHA:
  4223. internalFormat = this._gl.ALPHA;
  4224. break;
  4225. case Engine.TEXTUREFORMAT_LUMINANCE:
  4226. internalFormat = this._gl.LUMINANCE;
  4227. break;
  4228. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4229. internalFormat = this._gl.LUMINANCE_ALPHA;
  4230. break;
  4231. case Engine.TEXTUREFORMAT_RGB:
  4232. internalFormat = this._gl.RGB;
  4233. break;
  4234. case Engine.TEXTUREFORMAT_RGBA:
  4235. internalFormat = this._gl.RGBA;
  4236. break;
  4237. }
  4238. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4239. if (generateMipMaps) {
  4240. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4241. }
  4242. // Filters
  4243. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4244. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4245. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4246. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4247. this._activeTexturesCache = [];
  4248. texture._baseWidth = width;
  4249. texture._baseHeight = height;
  4250. texture._width = width;
  4251. texture._height = height;
  4252. texture.isReady = true;
  4253. texture.references = 1;
  4254. texture.samplingMode = samplingMode;
  4255. this._loadedTexturesCache.push(texture);
  4256. return texture;
  4257. };
  4258. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4259. var texture = this._gl.createTexture();
  4260. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4261. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4262. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4263. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4264. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4265. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4266. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4267. this._activeTexturesCache = [];
  4268. texture._baseWidth = width;
  4269. texture._baseHeight = height;
  4270. texture._width = width;
  4271. texture._height = height;
  4272. texture.isReady = false;
  4273. texture.generateMipMaps = generateMipMaps;
  4274. texture.references = 1;
  4275. texture.samplingMode = samplingMode;
  4276. this._loadedTexturesCache.push(texture);
  4277. return texture;
  4278. };
  4279. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4280. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4281. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4282. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4283. if (texture.generateMipMaps) {
  4284. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4285. }
  4286. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4287. this._activeTexturesCache = [];
  4288. texture.isReady = true;
  4289. };
  4290. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4291. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4292. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4293. // Scale the video if it is a NPOT using the current working canvas
  4294. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4295. if (!texture._workingCanvas) {
  4296. texture._workingCanvas = document.createElement("canvas");
  4297. texture._workingContext = texture._workingCanvas.getContext("2d");
  4298. texture._workingCanvas.width = texture._width;
  4299. texture._workingCanvas.height = texture._height;
  4300. }
  4301. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4302. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4303. } else {
  4304. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4305. }
  4306. if (texture.generateMipMaps) {
  4307. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4308. }
  4309. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4310. this._activeTexturesCache = [];
  4311. texture.isReady = true;
  4312. };
  4313. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4314. // old version had a "generateMipMaps" arg instead of options.
  4315. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4316. // in the same way, generateDepthBuffer is defaulted to true
  4317. var generateMipMaps = false;
  4318. var generateDepthBuffer = true;
  4319. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4320. if (options !== undefined) {
  4321. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4322. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4323. if (options.samplingMode !== undefined) {
  4324. samplingMode = options.samplingMode;
  4325. }
  4326. }
  4327. var gl = this._gl;
  4328. var texture = gl.createTexture();
  4329. gl.bindTexture(gl.TEXTURE_2D, texture);
  4330. var width = size.width || size;
  4331. var height = size.height || size;
  4332. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4333. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4334. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4335. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4336. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4337. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4338. var depthBuffer;
  4339. // Create the depth buffer
  4340. if (generateDepthBuffer) {
  4341. depthBuffer = gl.createRenderbuffer();
  4342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4343. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4344. }
  4345. // Create the framebuffer
  4346. var framebuffer = gl.createFramebuffer();
  4347. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4348. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4349. if (generateDepthBuffer) {
  4350. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4351. }
  4352. // Unbind
  4353. gl.bindTexture(gl.TEXTURE_2D, null);
  4354. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4355. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4356. texture._framebuffer = framebuffer;
  4357. if (generateDepthBuffer) {
  4358. texture._depthBuffer = depthBuffer;
  4359. }
  4360. texture._width = width;
  4361. texture._height = height;
  4362. texture.isReady = true;
  4363. texture.generateMipMaps = generateMipMaps;
  4364. texture.references = 1;
  4365. texture.samplingMode = samplingMode;
  4366. this._activeTexturesCache = [];
  4367. this._loadedTexturesCache.push(texture);
  4368. return texture;
  4369. };
  4370. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4371. var _this = this;
  4372. var gl = this._gl;
  4373. var texture = gl.createTexture();
  4374. texture.isCube = true;
  4375. texture.url = rootUrl;
  4376. texture.references = 1;
  4377. this._loadedTexturesCache.push(texture);
  4378. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4379. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4380. if (isDDS) {
  4381. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4382. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4383. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4384. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4385. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4386. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4387. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4388. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4389. }
  4390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4391. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4392. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4394. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4395. _this._activeTexturesCache = [];
  4396. texture._width = info.width;
  4397. texture._height = info.height;
  4398. texture.isReady = true;
  4399. }, null, null, true);
  4400. } else {
  4401. cascadeLoad(rootUrl, scene, function (imgs) {
  4402. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4403. var height = width;
  4404. _this._workingCanvas.width = width;
  4405. _this._workingCanvas.height = height;
  4406. var faces = [
  4407. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4408. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4409. ];
  4410. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4411. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4412. for (var index = 0; index < faces.length; index++) {
  4413. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4414. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4415. }
  4416. if (!noMipmap) {
  4417. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4418. }
  4419. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4423. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4424. _this._activeTexturesCache = [];
  4425. texture._width = width;
  4426. texture._height = height;
  4427. texture.isReady = true;
  4428. }, extensions);
  4429. }
  4430. return texture;
  4431. };
  4432. Engine.prototype._releaseTexture = function (texture) {
  4433. var gl = this._gl;
  4434. if (texture._framebuffer) {
  4435. gl.deleteFramebuffer(texture._framebuffer);
  4436. }
  4437. if (texture._depthBuffer) {
  4438. gl.deleteRenderbuffer(texture._depthBuffer);
  4439. }
  4440. gl.deleteTexture(texture);
  4441. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4442. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4443. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4444. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4445. this._activeTexturesCache[channel] = null;
  4446. }
  4447. var index = this._loadedTexturesCache.indexOf(texture);
  4448. if (index !== -1) {
  4449. this._loadedTexturesCache.splice(index, 1);
  4450. }
  4451. };
  4452. Engine.prototype.bindSamplers = function (effect) {
  4453. this._gl.useProgram(effect.getProgram());
  4454. var samplers = effect.getSamplers();
  4455. for (var index = 0; index < samplers.length; index++) {
  4456. var uniform = effect.getUniform(samplers[index]);
  4457. this._gl.uniform1i(uniform, index);
  4458. }
  4459. this._currentEffect = null;
  4460. };
  4461. Engine.prototype._bindTexture = function (channel, texture) {
  4462. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4463. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4464. this._activeTexturesCache[channel] = null;
  4465. };
  4466. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4467. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4468. };
  4469. Engine.prototype.setTexture = function (channel, texture) {
  4470. if (channel < 0) {
  4471. return;
  4472. }
  4473. // Not ready?
  4474. if (!texture || !texture.isReady()) {
  4475. if (this._activeTexturesCache[channel] != null) {
  4476. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4477. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4478. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4479. this._activeTexturesCache[channel] = null;
  4480. }
  4481. return;
  4482. }
  4483. // Video
  4484. if (texture instanceof BABYLON.VideoTexture) {
  4485. if (texture.update()) {
  4486. this._activeTexturesCache[channel] = null;
  4487. }
  4488. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4489. texture.delayLoad();
  4490. return;
  4491. }
  4492. if (this._activeTexturesCache[channel] === texture) {
  4493. return;
  4494. }
  4495. this._activeTexturesCache[channel] = texture;
  4496. var internalTexture = texture.getInternalTexture();
  4497. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4498. if (internalTexture.isCube) {
  4499. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4500. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4501. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4502. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4503. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4504. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4505. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4506. }
  4507. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4508. } else {
  4509. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4510. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4511. internalTexture._cachedWrapU = texture.wrapU;
  4512. switch (texture.wrapU) {
  4513. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4514. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4515. break;
  4516. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4517. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4518. break;
  4519. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4520. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4521. break;
  4522. }
  4523. }
  4524. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4525. internalTexture._cachedWrapV = texture.wrapV;
  4526. switch (texture.wrapV) {
  4527. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4528. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4529. break;
  4530. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4531. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4532. break;
  4533. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4534. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4535. break;
  4536. }
  4537. }
  4538. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4539. }
  4540. };
  4541. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4542. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4543. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4544. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4545. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4546. }
  4547. };
  4548. Engine.prototype.readPixels = function (x, y, width, height) {
  4549. var data = new Uint8Array(height * width * 4);
  4550. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4551. return data;
  4552. };
  4553. // Dispose
  4554. Engine.prototype.dispose = function () {
  4555. this.hideLoadingUI();
  4556. this.stopRenderLoop();
  4557. while (this.scenes.length) {
  4558. this.scenes[0].dispose();
  4559. }
  4560. for (var name in this._compiledEffects) {
  4561. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4562. }
  4563. for (var i in this._vertexAttribArrays) {
  4564. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4565. continue;
  4566. }
  4567. this._gl.disableVertexAttribArray(i);
  4568. }
  4569. // Events
  4570. window.removeEventListener("blur", this._onBlur);
  4571. window.removeEventListener("focus", this._onFocus);
  4572. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4573. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4574. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4575. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4576. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4577. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4578. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4579. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4580. };
  4581. // Loading screen
  4582. Engine.prototype.displayLoadingUI = function () {
  4583. var _this = this;
  4584. this._loadingDiv = document.createElement("div");
  4585. this._loadingDiv.style.opacity = "0";
  4586. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4587. // Loading text
  4588. this._loadingTextDiv = document.createElement("div");
  4589. this._loadingTextDiv.style.position = "absolute";
  4590. this._loadingTextDiv.style.left = "0";
  4591. this._loadingTextDiv.style.top = "50%";
  4592. this._loadingTextDiv.style.marginTop = "80px";
  4593. this._loadingTextDiv.style.width = "100%";
  4594. this._loadingTextDiv.style.height = "20px";
  4595. this._loadingTextDiv.style.fontFamily = "Arial";
  4596. this._loadingTextDiv.style.fontSize = "14px";
  4597. this._loadingTextDiv.style.color = "white";
  4598. this._loadingTextDiv.style.textAlign = "center";
  4599. this._loadingTextDiv.innerHTML = "Loading";
  4600. this._loadingDiv.appendChild(this._loadingTextDiv);
  4601. // Loading img
  4602. var imgBack = new Image();
  4603. 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==";
  4604. imgBack.style.position = "absolute";
  4605. imgBack.style.left = "50%";
  4606. imgBack.style.top = "50%";
  4607. imgBack.style.marginLeft = "-50px";
  4608. imgBack.style.marginTop = "-50px";
  4609. imgBack.style.transition = "transform 1.0s ease";
  4610. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4611. var deg = 360;
  4612. var onTransitionEnd = function () {
  4613. deg += 360;
  4614. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4615. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4616. };
  4617. imgBack.addEventListener("transitionend", onTransitionEnd);
  4618. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4619. this._loadingDiv.appendChild(imgBack);
  4620. // front image
  4621. var imgFront = new Image();
  4622. 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=";
  4623. imgFront.style.position = "absolute";
  4624. imgFront.style.left = "50%";
  4625. imgFront.style.top = "50%";
  4626. imgFront.style.marginLeft = "-50px";
  4627. imgFront.style.marginTop = "-50px";
  4628. this._loadingDiv.appendChild(imgFront);
  4629. // Resize
  4630. this._resizeLoadingUI = function () {
  4631. var canvasRect = _this.getRenderingCanvasClientRect();
  4632. _this._loadingDiv.style.position = "absolute";
  4633. _this._loadingDiv.style.left = canvasRect.left + "px";
  4634. _this._loadingDiv.style.top = canvasRect.top + "px";
  4635. _this._loadingDiv.style.width = canvasRect.width + "px";
  4636. _this._loadingDiv.style.height = canvasRect.height + "px";
  4637. };
  4638. this._resizeLoadingUI();
  4639. window.addEventListener("resize", this._resizeLoadingUI);
  4640. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4641. document.body.appendChild(this._loadingDiv);
  4642. setTimeout(function () {
  4643. _this._loadingDiv.style.opacity = "1";
  4644. imgBack.style.transform = "rotateZ(360deg)";
  4645. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4646. }, 0);
  4647. };
  4648. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4649. set: function (text) {
  4650. if (!this._loadingDiv) {
  4651. return;
  4652. }
  4653. this._loadingTextDiv.innerHTML = text;
  4654. },
  4655. enumerable: true,
  4656. configurable: true
  4657. });
  4658. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4659. get: function () {
  4660. return this._loadingDivBackgroundColor;
  4661. },
  4662. set: function (color) {
  4663. this._loadingDivBackgroundColor = color;
  4664. if (!this._loadingDiv) {
  4665. return;
  4666. }
  4667. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4668. },
  4669. enumerable: true,
  4670. configurable: true
  4671. });
  4672. Engine.prototype.hideLoadingUI = function () {
  4673. var _this = this;
  4674. if (!this._loadingDiv) {
  4675. return;
  4676. }
  4677. var onTransitionEnd = function () {
  4678. if (!_this._loadingDiv) {
  4679. return;
  4680. }
  4681. document.body.removeChild(_this._loadingDiv);
  4682. window.removeEventListener("resize", _this._resizeLoadingUI);
  4683. _this._loadingDiv = null;
  4684. };
  4685. this._loadingDiv.style.opacity = "0";
  4686. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4687. };
  4688. // FPS
  4689. Engine.prototype.getFps = function () {
  4690. return this.fps;
  4691. };
  4692. Engine.prototype.getDeltaTime = function () {
  4693. return this.deltaTime;
  4694. };
  4695. Engine.prototype._measureFps = function () {
  4696. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4697. var length = this.previousFramesDuration.length;
  4698. if (length >= 2) {
  4699. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4700. }
  4701. if (length >= this.fpsRange) {
  4702. if (length > this.fpsRange) {
  4703. this.previousFramesDuration.splice(0, 1);
  4704. length = this.previousFramesDuration.length;
  4705. }
  4706. var sum = 0;
  4707. for (var id = 0; id < length - 1; id++) {
  4708. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4709. }
  4710. this.fps = 1000.0 / (sum / (length - 1));
  4711. }
  4712. };
  4713. // Statics
  4714. Engine.isSupported = function () {
  4715. try {
  4716. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4717. if (navigator.isCocoonJS) {
  4718. return true;
  4719. }
  4720. var tempcanvas = document.createElement("canvas");
  4721. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4722. return gl != null && !!window.WebGLRenderingContext;
  4723. } catch (e) {
  4724. return false;
  4725. }
  4726. };
  4727. Engine._ALPHA_DISABLE = 0;
  4728. Engine._ALPHA_ADD = 1;
  4729. Engine._ALPHA_COMBINE = 2;
  4730. Engine._DELAYLOADSTATE_NONE = 0;
  4731. Engine._DELAYLOADSTATE_LOADED = 1;
  4732. Engine._DELAYLOADSTATE_LOADING = 2;
  4733. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4734. Engine._TEXTUREFORMAT_ALPHA = 0;
  4735. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4736. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4737. Engine._TEXTUREFORMAT_RGB = 4;
  4738. Engine._TEXTUREFORMAT_RGBA = 4;
  4739. Engine.Epsilon = 0.001;
  4740. Engine.CollisionsEpsilon = 0.001;
  4741. Engine.ShadersRepository = "Babylon/Shaders/";
  4742. return Engine;
  4743. })();
  4744. BABYLON.Engine = Engine;
  4745. })(BABYLON || (BABYLON = {}));
  4746. //# sourceMappingURL=babylon.engine.js.map
  4747. var BABYLON;
  4748. (function (BABYLON) {
  4749. var Node = (function () {
  4750. function Node(name, scene) {
  4751. this.state = "";
  4752. this.animations = new Array();
  4753. this._childrenFlag = -1;
  4754. this._isEnabled = true;
  4755. this._isReady = true;
  4756. this._currentRenderId = -1;
  4757. this.name = name;
  4758. this.id = name;
  4759. this._scene = scene;
  4760. this._initCache();
  4761. }
  4762. Node.prototype.getScene = function () {
  4763. return this._scene;
  4764. };
  4765. Node.prototype.getEngine = function () {
  4766. return this._scene.getEngine();
  4767. };
  4768. // override it in derived class
  4769. Node.prototype.getWorldMatrix = function () {
  4770. return BABYLON.Matrix.Identity();
  4771. };
  4772. // override it in derived class if you add new variables to the cache
  4773. // and call the parent class method
  4774. Node.prototype._initCache = function () {
  4775. this._cache = {};
  4776. this._cache.parent = undefined;
  4777. };
  4778. Node.prototype.updateCache = function (force) {
  4779. if (!force && this.isSynchronized())
  4780. return;
  4781. this._cache.parent = this.parent;
  4782. this._updateCache();
  4783. };
  4784. // override it in derived class if you add new variables to the cache
  4785. // and call the parent class method if !ignoreParentClass
  4786. Node.prototype._updateCache = function (ignoreParentClass) {
  4787. };
  4788. // override it in derived class if you add new variables to the cache
  4789. Node.prototype._isSynchronized = function () {
  4790. return true;
  4791. };
  4792. Node.prototype.isSynchronizedWithParent = function () {
  4793. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4794. };
  4795. Node.prototype.isSynchronized = function (updateCache) {
  4796. var check = this.hasNewParent();
  4797. check = check || !this.isSynchronizedWithParent();
  4798. check = check || !this._isSynchronized();
  4799. if (updateCache)
  4800. this.updateCache(true);
  4801. return !check;
  4802. };
  4803. Node.prototype.hasNewParent = function (update) {
  4804. if (this._cache.parent === this.parent)
  4805. return false;
  4806. if (update)
  4807. this._cache.parent = this.parent;
  4808. return true;
  4809. };
  4810. Node.prototype.isReady = function () {
  4811. return this._isReady;
  4812. };
  4813. Node.prototype.isEnabled = function () {
  4814. if (!this._isEnabled) {
  4815. return false;
  4816. }
  4817. if (this.parent) {
  4818. return this.parent.isEnabled();
  4819. }
  4820. return true;
  4821. };
  4822. Node.prototype.setEnabled = function (value) {
  4823. this._isEnabled = value;
  4824. };
  4825. Node.prototype.isDescendantOf = function (ancestor) {
  4826. if (this.parent) {
  4827. if (this.parent === ancestor) {
  4828. return true;
  4829. }
  4830. return this.parent.isDescendantOf(ancestor);
  4831. }
  4832. return false;
  4833. };
  4834. Node.prototype._getDescendants = function (list, results) {
  4835. for (var index = 0; index < list.length; index++) {
  4836. var item = list[index];
  4837. if (item.isDescendantOf(this)) {
  4838. results.push(item);
  4839. }
  4840. }
  4841. };
  4842. Node.prototype.getDescendants = function () {
  4843. var results = [];
  4844. this._getDescendants(this._scene.meshes, results);
  4845. this._getDescendants(this._scene.lights, results);
  4846. this._getDescendants(this._scene.cameras, results);
  4847. return results;
  4848. };
  4849. Node.prototype._setReady = function (state) {
  4850. if (state == this._isReady) {
  4851. return;
  4852. }
  4853. if (!state) {
  4854. this._isReady = false;
  4855. return;
  4856. }
  4857. this._isReady = true;
  4858. if (this.onReady) {
  4859. this.onReady(this);
  4860. }
  4861. };
  4862. return Node;
  4863. })();
  4864. BABYLON.Node = Node;
  4865. })(BABYLON || (BABYLON = {}));
  4866. //# sourceMappingURL=babylon.node.js.map
  4867. var BABYLON;
  4868. (function (BABYLON) {
  4869. var BoundingSphere = (function () {
  4870. function BoundingSphere(minimum, maximum) {
  4871. this.minimum = minimum;
  4872. this.maximum = maximum;
  4873. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4874. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4875. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4876. this.radius = distance * 0.5;
  4877. this.centerWorld = BABYLON.Vector3.Zero();
  4878. this._update(BABYLON.Matrix.Identity());
  4879. }
  4880. // Methods
  4881. BoundingSphere.prototype._update = function (world) {
  4882. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4883. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4884. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4885. };
  4886. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4887. for (var i = 0; i < 6; i++) {
  4888. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4889. return false;
  4890. }
  4891. return true;
  4892. };
  4893. BoundingSphere.prototype.intersectsPoint = function (point) {
  4894. var x = this.centerWorld.x - point.x;
  4895. var y = this.centerWorld.y - point.y;
  4896. var z = this.centerWorld.z - point.z;
  4897. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4898. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4899. return false;
  4900. return true;
  4901. };
  4902. // Statics
  4903. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4904. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4905. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4906. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4907. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4908. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4909. return false;
  4910. return true;
  4911. };
  4912. return BoundingSphere;
  4913. })();
  4914. BABYLON.BoundingSphere = BoundingSphere;
  4915. })(BABYLON || (BABYLON = {}));
  4916. //# sourceMappingURL=babylon.boundingSphere.js.map
  4917. var BABYLON;
  4918. (function (BABYLON) {
  4919. var BoundingBox = (function () {
  4920. function BoundingBox(minimum, maximum) {
  4921. this.minimum = minimum;
  4922. this.maximum = maximum;
  4923. this.vectors = new Array();
  4924. this.vectorsWorld = new Array();
  4925. // Bounding vectors
  4926. this.vectors.push(this.minimum.clone());
  4927. this.vectors.push(this.maximum.clone());
  4928. this.vectors.push(this.minimum.clone());
  4929. this.vectors[2].x = this.maximum.x;
  4930. this.vectors.push(this.minimum.clone());
  4931. this.vectors[3].y = this.maximum.y;
  4932. this.vectors.push(this.minimum.clone());
  4933. this.vectors[4].z = this.maximum.z;
  4934. this.vectors.push(this.maximum.clone());
  4935. this.vectors[5].z = this.minimum.z;
  4936. this.vectors.push(this.maximum.clone());
  4937. this.vectors[6].x = this.minimum.x;
  4938. this.vectors.push(this.maximum.clone());
  4939. this.vectors[7].y = this.minimum.y;
  4940. // OBB
  4941. this.center = this.maximum.add(this.minimum).scale(0.5);
  4942. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4943. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4944. for (var index = 0; index < this.vectors.length; index++) {
  4945. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4946. }
  4947. this.minimumWorld = BABYLON.Vector3.Zero();
  4948. this.maximumWorld = BABYLON.Vector3.Zero();
  4949. this._update(BABYLON.Matrix.Identity());
  4950. }
  4951. // Methods
  4952. BoundingBox.prototype.getWorldMatrix = function () {
  4953. return this._worldMatrix;
  4954. };
  4955. BoundingBox.prototype._update = function (world) {
  4956. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4957. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4958. for (var index = 0; index < this.vectors.length; index++) {
  4959. var v = this.vectorsWorld[index];
  4960. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4961. if (v.x < this.minimumWorld.x)
  4962. this.minimumWorld.x = v.x;
  4963. if (v.y < this.minimumWorld.y)
  4964. this.minimumWorld.y = v.y;
  4965. if (v.z < this.minimumWorld.z)
  4966. this.minimumWorld.z = v.z;
  4967. if (v.x > this.maximumWorld.x)
  4968. this.maximumWorld.x = v.x;
  4969. if (v.y > this.maximumWorld.y)
  4970. this.maximumWorld.y = v.y;
  4971. if (v.z > this.maximumWorld.z)
  4972. this.maximumWorld.z = v.z;
  4973. }
  4974. // OBB
  4975. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4976. this.center.scaleInPlace(0.5);
  4977. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4978. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4979. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4980. this._worldMatrix = world;
  4981. };
  4982. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4983. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4984. };
  4985. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4986. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4987. };
  4988. BoundingBox.prototype.intersectsPoint = function (point) {
  4989. var delta = BABYLON.Engine.Epsilon;
  4990. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4991. return false;
  4992. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4993. return false;
  4994. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4995. return false;
  4996. return true;
  4997. };
  4998. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4999. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5000. };
  5001. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5002. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5003. return false;
  5004. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5005. return false;
  5006. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5007. return false;
  5008. return true;
  5009. };
  5010. // Statics
  5011. BoundingBox.Intersects = function (box0, box1) {
  5012. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5013. return false;
  5014. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5015. return false;
  5016. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5017. return false;
  5018. return true;
  5019. };
  5020. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5021. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5022. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5023. return (num <= (sphereRadius * sphereRadius));
  5024. };
  5025. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5026. for (var p = 0; p < 6; p++) {
  5027. for (var i = 0; i < 8; i++) {
  5028. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5029. return false;
  5030. }
  5031. }
  5032. }
  5033. return true;
  5034. };
  5035. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5036. for (var p = 0; p < 6; p++) {
  5037. var inCount = 8;
  5038. for (var i = 0; i < 8; i++) {
  5039. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5040. --inCount;
  5041. } else {
  5042. break;
  5043. }
  5044. }
  5045. if (inCount == 0)
  5046. return false;
  5047. }
  5048. return true;
  5049. };
  5050. return BoundingBox;
  5051. })();
  5052. BABYLON.BoundingBox = BoundingBox;
  5053. })(BABYLON || (BABYLON = {}));
  5054. //# sourceMappingURL=babylon.boundingBox.js.map
  5055. var BABYLON;
  5056. (function (BABYLON) {
  5057. var computeBoxExtents = function (axis, box) {
  5058. var p = BABYLON.Vector3.Dot(box.center, axis);
  5059. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5060. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5061. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5062. var r = r0 + r1 + r2;
  5063. return {
  5064. min: p - r,
  5065. max: p + r
  5066. };
  5067. };
  5068. var extentsOverlap = function (min0, max0, min1, max1) {
  5069. return !(min0 > max1 || min1 > max0);
  5070. };
  5071. var axisOverlap = function (axis, box0, box1) {
  5072. var result0 = computeBoxExtents(axis, box0);
  5073. var result1 = computeBoxExtents(axis, box1);
  5074. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5075. };
  5076. var BoundingInfo = (function () {
  5077. function BoundingInfo(minimum, maximum) {
  5078. this.minimum = minimum;
  5079. this.maximum = maximum;
  5080. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5081. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5082. }
  5083. // Methods
  5084. BoundingInfo.prototype._update = function (world) {
  5085. this.boundingBox._update(world);
  5086. this.boundingSphere._update(world);
  5087. };
  5088. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5089. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5090. return false;
  5091. return this.boundingBox.isInFrustum(frustumPlanes);
  5092. };
  5093. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5094. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5095. };
  5096. BoundingInfo.prototype._checkCollision = function (collider) {
  5097. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5098. };
  5099. BoundingInfo.prototype.intersectsPoint = function (point) {
  5100. if (!this.boundingSphere.centerWorld) {
  5101. return false;
  5102. }
  5103. if (!this.boundingSphere.intersectsPoint(point)) {
  5104. return false;
  5105. }
  5106. if (!this.boundingBox.intersectsPoint(point)) {
  5107. return false;
  5108. }
  5109. return true;
  5110. };
  5111. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5112. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5113. return false;
  5114. }
  5115. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5116. return false;
  5117. }
  5118. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5119. return false;
  5120. }
  5121. if (!precise) {
  5122. return true;
  5123. }
  5124. var box0 = this.boundingBox;
  5125. var box1 = boundingInfo.boundingBox;
  5126. if (!axisOverlap(box0.directions[0], box0, box1))
  5127. return false;
  5128. if (!axisOverlap(box0.directions[1], box0, box1))
  5129. return false;
  5130. if (!axisOverlap(box0.directions[2], box0, box1))
  5131. return false;
  5132. if (!axisOverlap(box1.directions[0], box0, box1))
  5133. return false;
  5134. if (!axisOverlap(box1.directions[1], box0, box1))
  5135. return false;
  5136. if (!axisOverlap(box1.directions[2], box0, box1))
  5137. return false;
  5138. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5139. return false;
  5140. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5141. return false;
  5142. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5143. return false;
  5144. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5145. return false;
  5146. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5147. return false;
  5148. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5149. return false;
  5150. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5151. return false;
  5152. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5153. return false;
  5154. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5155. return false;
  5156. return true;
  5157. };
  5158. return BoundingInfo;
  5159. })();
  5160. BABYLON.BoundingInfo = BoundingInfo;
  5161. })(BABYLON || (BABYLON = {}));
  5162. //# sourceMappingURL=babylon.boundingInfo.js.map
  5163. var BABYLON;
  5164. (function (BABYLON) {
  5165. var Light = (function (_super) {
  5166. __extends(Light, _super);
  5167. function Light(name, scene) {
  5168. _super.call(this, name, scene);
  5169. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5170. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5171. this.intensity = 1.0;
  5172. this.range = Number.MAX_VALUE;
  5173. this.includedOnlyMeshes = new Array();
  5174. this.excludedMeshes = new Array();
  5175. this._excludedMeshesIds = new Array();
  5176. this._includedOnlyMeshesIds = new Array();
  5177. scene.lights.push(this);
  5178. }
  5179. Light.prototype.getShadowGenerator = function () {
  5180. return this._shadowGenerator;
  5181. };
  5182. Light.prototype.getAbsolutePosition = function () {
  5183. return BABYLON.Vector3.Zero();
  5184. };
  5185. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5186. };
  5187. Light.prototype._getWorldMatrix = function () {
  5188. return BABYLON.Matrix.Identity();
  5189. };
  5190. Light.prototype.canAffectMesh = function (mesh) {
  5191. if (!mesh) {
  5192. return true;
  5193. }
  5194. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5195. return false;
  5196. }
  5197. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5198. return false;
  5199. }
  5200. return true;
  5201. };
  5202. Light.prototype.getWorldMatrix = function () {
  5203. this._currentRenderId = this.getScene().getRenderId();
  5204. var worldMatrix = this._getWorldMatrix();
  5205. if (this.parent && this.parent.getWorldMatrix) {
  5206. if (!this._parentedWorldMatrix) {
  5207. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5208. }
  5209. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5210. return this._parentedWorldMatrix;
  5211. }
  5212. return worldMatrix;
  5213. };
  5214. Light.prototype.dispose = function () {
  5215. if (this._shadowGenerator) {
  5216. this._shadowGenerator.dispose();
  5217. this._shadowGenerator = null;
  5218. }
  5219. // Remove from scene
  5220. var index = this.getScene().lights.indexOf(this);
  5221. this.getScene().lights.splice(index, 1);
  5222. };
  5223. return Light;
  5224. })(BABYLON.Node);
  5225. BABYLON.Light = Light;
  5226. })(BABYLON || (BABYLON = {}));
  5227. //# sourceMappingURL=babylon.light.js.map
  5228. var BABYLON;
  5229. (function (BABYLON) {
  5230. var PointLight = (function (_super) {
  5231. __extends(PointLight, _super);
  5232. function PointLight(name, position, scene) {
  5233. _super.call(this, name, scene);
  5234. this.position = position;
  5235. }
  5236. PointLight.prototype.getAbsolutePosition = function () {
  5237. return this._transformedPosition ? this._transformedPosition : this.position;
  5238. };
  5239. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5240. if (this.parent && this.parent.getWorldMatrix) {
  5241. if (!this._transformedPosition) {
  5242. this._transformedPosition = BABYLON.Vector3.Zero();
  5243. }
  5244. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5245. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5246. return;
  5247. }
  5248. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5249. };
  5250. PointLight.prototype.getShadowGenerator = function () {
  5251. return null;
  5252. };
  5253. PointLight.prototype._getWorldMatrix = function () {
  5254. if (!this._worldMatrix) {
  5255. this._worldMatrix = BABYLON.Matrix.Identity();
  5256. }
  5257. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5258. return this._worldMatrix;
  5259. };
  5260. return PointLight;
  5261. })(BABYLON.Light);
  5262. BABYLON.PointLight = PointLight;
  5263. })(BABYLON || (BABYLON = {}));
  5264. //# sourceMappingURL=babylon.pointLight.js.map
  5265. var BABYLON;
  5266. (function (BABYLON) {
  5267. var SpotLight = (function (_super) {
  5268. __extends(SpotLight, _super);
  5269. function SpotLight(name, position, direction, angle, exponent, scene) {
  5270. _super.call(this, name, scene);
  5271. this.position = position;
  5272. this.direction = direction;
  5273. this.angle = angle;
  5274. this.exponent = exponent;
  5275. }
  5276. SpotLight.prototype.getAbsolutePosition = function () {
  5277. return this.transformedPosition ? this.transformedPosition : this.position;
  5278. };
  5279. SpotLight.prototype.setDirectionToTarget = function (target) {
  5280. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5281. return this.direction;
  5282. };
  5283. SpotLight.prototype.computeTransformedPosition = function () {
  5284. if (this.parent && this.parent.getWorldMatrix) {
  5285. if (!this.transformedPosition) {
  5286. this.transformedPosition = BABYLON.Vector3.Zero();
  5287. }
  5288. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5289. return true;
  5290. }
  5291. return false;
  5292. };
  5293. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5294. var normalizeDirection;
  5295. if (this.parent && this.parent.getWorldMatrix) {
  5296. if (!this._transformedDirection) {
  5297. this._transformedDirection = BABYLON.Vector3.Zero();
  5298. }
  5299. this.computeTransformedPosition();
  5300. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5301. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5302. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5303. } else {
  5304. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5305. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5306. }
  5307. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5308. };
  5309. SpotLight.prototype._getWorldMatrix = function () {
  5310. if (!this._worldMatrix) {
  5311. this._worldMatrix = BABYLON.Matrix.Identity();
  5312. }
  5313. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5314. return this._worldMatrix;
  5315. };
  5316. return SpotLight;
  5317. })(BABYLON.Light);
  5318. BABYLON.SpotLight = SpotLight;
  5319. })(BABYLON || (BABYLON = {}));
  5320. //# sourceMappingURL=babylon.spotLight.js.map
  5321. var BABYLON;
  5322. (function (BABYLON) {
  5323. var DirectionalLight = (function (_super) {
  5324. __extends(DirectionalLight, _super);
  5325. function DirectionalLight(name, direction, scene) {
  5326. _super.call(this, name, scene);
  5327. this.direction = direction;
  5328. this.position = direction.scale(-1);
  5329. }
  5330. DirectionalLight.prototype.getAbsolutePosition = function () {
  5331. return this.transformedPosition ? this.transformedPosition : this.position;
  5332. };
  5333. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5334. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5335. return this.direction;
  5336. };
  5337. DirectionalLight.prototype.computeTransformedPosition = function () {
  5338. if (this.parent && this.parent.getWorldMatrix) {
  5339. if (!this.transformedPosition) {
  5340. this.transformedPosition = BABYLON.Vector3.Zero();
  5341. }
  5342. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5343. return true;
  5344. }
  5345. return false;
  5346. };
  5347. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5348. if (this.parent && this.parent.getWorldMatrix) {
  5349. if (!this._transformedDirection) {
  5350. this._transformedDirection = BABYLON.Vector3.Zero();
  5351. }
  5352. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5353. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5354. return;
  5355. }
  5356. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5357. };
  5358. DirectionalLight.prototype._getWorldMatrix = function () {
  5359. if (!this._worldMatrix) {
  5360. this._worldMatrix = BABYLON.Matrix.Identity();
  5361. }
  5362. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5363. return this._worldMatrix;
  5364. };
  5365. return DirectionalLight;
  5366. })(BABYLON.Light);
  5367. BABYLON.DirectionalLight = DirectionalLight;
  5368. })(BABYLON || (BABYLON = {}));
  5369. //# sourceMappingURL=babylon.directionalLight.js.map
  5370. var BABYLON;
  5371. (function (BABYLON) {
  5372. var ShadowGenerator = (function () {
  5373. function ShadowGenerator(mapSize, light) {
  5374. var _this = this;
  5375. // Members
  5376. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5377. this._darkness = 0;
  5378. this._transparencyShadow = false;
  5379. this._viewMatrix = BABYLON.Matrix.Zero();
  5380. this._projectionMatrix = BABYLON.Matrix.Zero();
  5381. this._transformMatrix = BABYLON.Matrix.Zero();
  5382. this._worldViewProjection = BABYLON.Matrix.Zero();
  5383. this._light = light;
  5384. this._scene = light.getScene();
  5385. light._shadowGenerator = this;
  5386. // Render target
  5387. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5388. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5389. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5390. this._shadowMap.renderParticles = false;
  5391. // Custom render function
  5392. var renderSubMesh = function (subMesh) {
  5393. var mesh = subMesh.getRenderingMesh();
  5394. var scene = _this._scene;
  5395. var engine = scene.getEngine();
  5396. // Culling
  5397. engine.setState(subMesh.getMaterial().backFaceCulling);
  5398. // Managing instances
  5399. var batch = mesh._getInstancesRenderList(subMesh._id);
  5400. if (batch.mustReturn) {
  5401. return;
  5402. }
  5403. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5404. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5405. engine.enableEffect(_this._effect);
  5406. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5407. var material = subMesh.getMaterial();
  5408. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5409. // Alpha test
  5410. if (material && material.needAlphaTesting()) {
  5411. var alphaTexture = material.getAlphaTestTexture();
  5412. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5413. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5414. }
  5415. // Bones
  5416. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5417. if (useBones) {
  5418. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5419. }
  5420. if (hardwareInstancedRendering) {
  5421. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5422. } else {
  5423. if (batch.renderSelf[subMesh._id]) {
  5424. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5425. // Draw
  5426. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5427. }
  5428. if (batch.visibleInstances[subMesh._id]) {
  5429. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5430. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5431. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5432. // Draw
  5433. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5434. }
  5435. }
  5436. }
  5437. } else {
  5438. // Need to reset refresh rate of the shadowMap
  5439. _this._shadowMap.resetRefreshCounter();
  5440. }
  5441. };
  5442. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5443. var index;
  5444. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5445. renderSubMesh(opaqueSubMeshes.data[index]);
  5446. }
  5447. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5448. renderSubMesh(alphaTestSubMeshes.data[index]);
  5449. }
  5450. if (_this._transparencyShadow) {
  5451. for (index = 0; index < transparentSubMeshes.length; index++) {
  5452. renderSubMesh(transparentSubMeshes.data[index]);
  5453. }
  5454. }
  5455. };
  5456. }
  5457. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5458. // Static
  5459. get: function () {
  5460. return ShadowGenerator._FILTER_NONE;
  5461. },
  5462. enumerable: true,
  5463. configurable: true
  5464. });
  5465. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5466. get: function () {
  5467. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5473. get: function () {
  5474. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5475. },
  5476. enumerable: true,
  5477. configurable: true
  5478. });
  5479. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5480. get: function () {
  5481. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5482. },
  5483. set: function (value) {
  5484. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5485. },
  5486. enumerable: true,
  5487. configurable: true
  5488. });
  5489. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5490. get: function () {
  5491. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5492. },
  5493. set: function (value) {
  5494. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5495. },
  5496. enumerable: true,
  5497. configurable: true
  5498. });
  5499. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5500. var defines = [];
  5501. if (this.useVarianceShadowMap) {
  5502. defines.push("#define VSM");
  5503. }
  5504. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5505. var mesh = subMesh.getMesh();
  5506. var scene = mesh.getScene();
  5507. var material = subMesh.getMaterial();
  5508. // Alpha test
  5509. if (material && material.needAlphaTesting()) {
  5510. defines.push("#define ALPHATEST");
  5511. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5512. attribs.push(BABYLON.VertexBuffer.UVKind);
  5513. defines.push("#define UV1");
  5514. }
  5515. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5516. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5517. defines.push("#define UV2");
  5518. }
  5519. }
  5520. // Bones
  5521. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5522. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5523. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5524. defines.push("#define BONES");
  5525. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5526. }
  5527. // Instances
  5528. if (useInstances) {
  5529. defines.push("#define INSTANCES");
  5530. attribs.push("world0");
  5531. attribs.push("world1");
  5532. attribs.push("world2");
  5533. attribs.push("world3");
  5534. }
  5535. // Get correct effect
  5536. var join = defines.join("\n");
  5537. if (this._cachedDefines !== join) {
  5538. this._cachedDefines = join;
  5539. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5540. }
  5541. return this._effect.isReady();
  5542. };
  5543. ShadowGenerator.prototype.getShadowMap = function () {
  5544. return this._shadowMap;
  5545. };
  5546. ShadowGenerator.prototype.getLight = function () {
  5547. return this._light;
  5548. };
  5549. // Methods
  5550. ShadowGenerator.prototype.getTransformMatrix = function () {
  5551. var lightPosition = this._light.position;
  5552. var lightDirection = this._light.direction;
  5553. if (this._light.computeTransformedPosition()) {
  5554. lightPosition = this._light.transformedPosition;
  5555. }
  5556. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5557. this._cachedPosition = lightPosition.clone();
  5558. this._cachedDirection = lightDirection.clone();
  5559. var activeCamera = this._scene.activeCamera;
  5560. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5561. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5562. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5563. }
  5564. return this._transformMatrix;
  5565. };
  5566. ShadowGenerator.prototype.getDarkness = function () {
  5567. return this._darkness;
  5568. };
  5569. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5570. if (darkness >= 1.0)
  5571. this._darkness = 1.0;
  5572. else if (darkness <= 0.0)
  5573. this._darkness = 0.0;
  5574. else
  5575. this._darkness = darkness;
  5576. };
  5577. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5578. this._transparencyShadow = hasShadow;
  5579. };
  5580. ShadowGenerator.prototype.dispose = function () {
  5581. this._shadowMap.dispose();
  5582. };
  5583. ShadowGenerator._FILTER_NONE = 0;
  5584. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5585. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5586. return ShadowGenerator;
  5587. })();
  5588. BABYLON.ShadowGenerator = ShadowGenerator;
  5589. })(BABYLON || (BABYLON = {}));
  5590. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5591. var BABYLON;
  5592. (function (BABYLON) {
  5593. var HemisphericLight = (function (_super) {
  5594. __extends(HemisphericLight, _super);
  5595. function HemisphericLight(name, direction, scene) {
  5596. _super.call(this, name, scene);
  5597. this.direction = direction;
  5598. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5599. }
  5600. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5601. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5602. return this.direction;
  5603. };
  5604. HemisphericLight.prototype.getShadowGenerator = function () {
  5605. return null;
  5606. };
  5607. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5608. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5609. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5610. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5611. };
  5612. HemisphericLight.prototype._getWorldMatrix = function () {
  5613. if (!this._worldMatrix) {
  5614. this._worldMatrix = BABYLON.Matrix.Identity();
  5615. }
  5616. return this._worldMatrix;
  5617. };
  5618. return HemisphericLight;
  5619. })(BABYLON.Light);
  5620. BABYLON.HemisphericLight = HemisphericLight;
  5621. })(BABYLON || (BABYLON = {}));
  5622. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5623. var BABYLON;
  5624. (function (BABYLON) {
  5625. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5626. if (boxMin.x > sphereCenter.x + sphereRadius)
  5627. return false;
  5628. if (sphereCenter.x - sphereRadius > boxMax.x)
  5629. return false;
  5630. if (boxMin.y > sphereCenter.y + sphereRadius)
  5631. return false;
  5632. if (sphereCenter.y - sphereRadius > boxMax.y)
  5633. return false;
  5634. if (boxMin.z > sphereCenter.z + sphereRadius)
  5635. return false;
  5636. if (sphereCenter.z - sphereRadius > boxMax.z)
  5637. return false;
  5638. return true;
  5639. };
  5640. var getLowestRoot = function (a, b, c, maxR) {
  5641. var determinant = b * b - 4.0 * a * c;
  5642. var result = { root: 0, found: false };
  5643. if (determinant < 0)
  5644. return result;
  5645. var sqrtD = Math.sqrt(determinant);
  5646. var r1 = (-b - sqrtD) / (2.0 * a);
  5647. var r2 = (-b + sqrtD) / (2.0 * a);
  5648. if (r1 > r2) {
  5649. var temp = r2;
  5650. r2 = r1;
  5651. r1 = temp;
  5652. }
  5653. if (r1 > 0 && r1 < maxR) {
  5654. result.root = r1;
  5655. result.found = true;
  5656. return result;
  5657. }
  5658. if (r2 > 0 && r2 < maxR) {
  5659. result.root = r2;
  5660. result.found = true;
  5661. return result;
  5662. }
  5663. return result;
  5664. };
  5665. var Collider = (function () {
  5666. function Collider() {
  5667. this.radius = new BABYLON.Vector3(1, 1, 1);
  5668. this.retry = 0;
  5669. this.basePointWorld = BABYLON.Vector3.Zero();
  5670. this.velocityWorld = BABYLON.Vector3.Zero();
  5671. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5672. this._collisionPoint = BABYLON.Vector3.Zero();
  5673. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5674. this._tempVector = BABYLON.Vector3.Zero();
  5675. this._tempVector2 = BABYLON.Vector3.Zero();
  5676. this._tempVector3 = BABYLON.Vector3.Zero();
  5677. this._tempVector4 = BABYLON.Vector3.Zero();
  5678. this._edge = BABYLON.Vector3.Zero();
  5679. this._baseToVertex = BABYLON.Vector3.Zero();
  5680. this._destinationPoint = BABYLON.Vector3.Zero();
  5681. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5682. this._displacementVector = BABYLON.Vector3.Zero();
  5683. }
  5684. // Methods
  5685. Collider.prototype._initialize = function (source, dir, e) {
  5686. this.velocity = dir;
  5687. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5688. this.basePoint = source;
  5689. source.multiplyToRef(this.radius, this.basePointWorld);
  5690. dir.multiplyToRef(this.radius, this.velocityWorld);
  5691. this.velocityWorldLength = this.velocityWorld.length();
  5692. this.epsilon = e;
  5693. this.collisionFound = false;
  5694. };
  5695. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5696. pa.subtractToRef(point, this._tempVector);
  5697. pb.subtractToRef(point, this._tempVector2);
  5698. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5699. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5700. if (d < 0)
  5701. return false;
  5702. pc.subtractToRef(point, this._tempVector3);
  5703. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5704. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5705. if (d < 0)
  5706. return false;
  5707. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5708. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5709. return d >= 0;
  5710. };
  5711. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5712. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5713. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5714. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5715. return false;
  5716. }
  5717. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5718. return false;
  5719. return true;
  5720. };
  5721. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5722. var t0;
  5723. var embeddedInPlane = false;
  5724. if (!subMesh._trianglePlanes) {
  5725. subMesh._trianglePlanes = [];
  5726. }
  5727. if (!subMesh._trianglePlanes[faceIndex]) {
  5728. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5729. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5730. }
  5731. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5732. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5733. return;
  5734. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5735. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5736. if (normalDotVelocity == 0) {
  5737. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5738. return;
  5739. embeddedInPlane = true;
  5740. t0 = 0;
  5741. } else {
  5742. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5743. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5744. if (t0 > t1) {
  5745. var temp = t1;
  5746. t1 = t0;
  5747. t0 = temp;
  5748. }
  5749. if (t0 > 1.0 || t1 < 0.0)
  5750. return;
  5751. if (t0 < 0)
  5752. t0 = 0;
  5753. if (t0 > 1.0)
  5754. t0 = 1.0;
  5755. }
  5756. this._collisionPoint.copyFromFloats(0, 0, 0);
  5757. var found = false;
  5758. var t = 1.0;
  5759. if (!embeddedInPlane) {
  5760. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5761. this.velocity.scaleToRef(t0, this._tempVector);
  5762. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5763. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5764. found = true;
  5765. t = t0;
  5766. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5767. }
  5768. }
  5769. if (!found) {
  5770. var velocitySquaredLength = this.velocity.lengthSquared();
  5771. var a = velocitySquaredLength;
  5772. this.basePoint.subtractToRef(p1, this._tempVector);
  5773. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5774. var c = this._tempVector.lengthSquared() - 1.0;
  5775. var lowestRoot = getLowestRoot(a, b, c, t);
  5776. if (lowestRoot.found) {
  5777. t = lowestRoot.root;
  5778. found = true;
  5779. this._collisionPoint.copyFrom(p1);
  5780. }
  5781. this.basePoint.subtractToRef(p2, this._tempVector);
  5782. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5783. c = this._tempVector.lengthSquared() - 1.0;
  5784. lowestRoot = getLowestRoot(a, b, c, t);
  5785. if (lowestRoot.found) {
  5786. t = lowestRoot.root;
  5787. found = true;
  5788. this._collisionPoint.copyFrom(p2);
  5789. }
  5790. this.basePoint.subtractToRef(p3, this._tempVector);
  5791. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5792. c = this._tempVector.lengthSquared() - 1.0;
  5793. lowestRoot = getLowestRoot(a, b, c, t);
  5794. if (lowestRoot.found) {
  5795. t = lowestRoot.root;
  5796. found = true;
  5797. this._collisionPoint.copyFrom(p3);
  5798. }
  5799. p2.subtractToRef(p1, this._edge);
  5800. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5801. var edgeSquaredLength = this._edge.lengthSquared();
  5802. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5803. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5804. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5805. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5806. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5807. lowestRoot = getLowestRoot(a, b, c, t);
  5808. if (lowestRoot.found) {
  5809. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5810. if (f >= 0.0 && f <= 1.0) {
  5811. t = lowestRoot.root;
  5812. found = true;
  5813. this._edge.scaleInPlace(f);
  5814. p1.addToRef(this._edge, this._collisionPoint);
  5815. }
  5816. }
  5817. p3.subtractToRef(p2, this._edge);
  5818. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5819. edgeSquaredLength = this._edge.lengthSquared();
  5820. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5821. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5822. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5823. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5824. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5825. lowestRoot = getLowestRoot(a, b, c, t);
  5826. if (lowestRoot.found) {
  5827. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5828. if (f >= 0.0 && f <= 1.0) {
  5829. t = lowestRoot.root;
  5830. found = true;
  5831. this._edge.scaleInPlace(f);
  5832. p2.addToRef(this._edge, this._collisionPoint);
  5833. }
  5834. }
  5835. p1.subtractToRef(p3, this._edge);
  5836. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5837. edgeSquaredLength = this._edge.lengthSquared();
  5838. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5839. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5840. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5841. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5842. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5843. lowestRoot = getLowestRoot(a, b, c, t);
  5844. if (lowestRoot.found) {
  5845. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5846. if (f >= 0.0 && f <= 1.0) {
  5847. t = lowestRoot.root;
  5848. found = true;
  5849. this._edge.scaleInPlace(f);
  5850. p3.addToRef(this._edge, this._collisionPoint);
  5851. }
  5852. }
  5853. }
  5854. if (found) {
  5855. var distToCollision = t * this.velocity.length();
  5856. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5857. if (!this.intersectionPoint) {
  5858. this.intersectionPoint = this._collisionPoint.clone();
  5859. } else {
  5860. this.intersectionPoint.copyFrom(this._collisionPoint);
  5861. }
  5862. this.nearestDistance = distToCollision;
  5863. this.collisionFound = true;
  5864. this.collidedMesh = subMesh.getMesh();
  5865. }
  5866. }
  5867. };
  5868. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5869. for (var i = indexStart; i < indexEnd; i += 3) {
  5870. var p1 = pts[indices[i] - decal];
  5871. var p2 = pts[indices[i + 1] - decal];
  5872. var p3 = pts[indices[i + 2] - decal];
  5873. this._testTriangle(i, subMesh, p3, p2, p1);
  5874. }
  5875. };
  5876. Collider.prototype._getResponse = function (pos, vel) {
  5877. pos.addToRef(vel, this._destinationPoint);
  5878. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5879. this.basePoint.addToRef(vel, pos);
  5880. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5881. this._slidePlaneNormal.normalize();
  5882. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5883. pos.addInPlace(this._displacementVector);
  5884. this.intersectionPoint.addInPlace(this._displacementVector);
  5885. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5886. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5887. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5888. };
  5889. return Collider;
  5890. })();
  5891. BABYLON.Collider = Collider;
  5892. })(BABYLON || (BABYLON = {}));
  5893. //# sourceMappingURL=babylon.collider.js.map
  5894. var BABYLON;
  5895. (function (BABYLON) {
  5896. var Camera = (function (_super) {
  5897. __extends(Camera, _super);
  5898. function Camera(name, position, scene) {
  5899. _super.call(this, name, scene);
  5900. this.position = position;
  5901. // Members
  5902. this.upVector = BABYLON.Vector3.Up();
  5903. this.orthoLeft = null;
  5904. this.orthoRight = null;
  5905. this.orthoBottom = null;
  5906. this.orthoTop = null;
  5907. this.fov = 0.8;
  5908. this.minZ = 1.0;
  5909. this.maxZ = 10000.0;
  5910. this.inertia = 0.9;
  5911. this.mode = Camera.PERSPECTIVE_CAMERA;
  5912. this.isIntermediate = false;
  5913. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5914. this.subCameras = [];
  5915. this.layerMask = 0xFFFFFFFF;
  5916. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5917. this._projectionMatrix = new BABYLON.Matrix();
  5918. this._postProcesses = new Array();
  5919. this._postProcessesTakenIndices = [];
  5920. scene.cameras.push(this);
  5921. if (!scene.activeCamera) {
  5922. scene.activeCamera = this;
  5923. }
  5924. }
  5925. //Cache
  5926. Camera.prototype._initCache = function () {
  5927. _super.prototype._initCache.call(this);
  5928. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5929. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5930. this._cache.mode = undefined;
  5931. this._cache.minZ = undefined;
  5932. this._cache.maxZ = undefined;
  5933. this._cache.fov = undefined;
  5934. this._cache.aspectRatio = undefined;
  5935. this._cache.orthoLeft = undefined;
  5936. this._cache.orthoRight = undefined;
  5937. this._cache.orthoBottom = undefined;
  5938. this._cache.orthoTop = undefined;
  5939. this._cache.renderWidth = undefined;
  5940. this._cache.renderHeight = undefined;
  5941. };
  5942. Camera.prototype._updateCache = function (ignoreParentClass) {
  5943. if (!ignoreParentClass) {
  5944. _super.prototype._updateCache.call(this);
  5945. }
  5946. var engine = this.getEngine();
  5947. this._cache.position.copyFrom(this.position);
  5948. this._cache.upVector.copyFrom(this.upVector);
  5949. this._cache.mode = this.mode;
  5950. this._cache.minZ = this.minZ;
  5951. this._cache.maxZ = this.maxZ;
  5952. this._cache.fov = this.fov;
  5953. this._cache.aspectRatio = engine.getAspectRatio(this);
  5954. this._cache.orthoLeft = this.orthoLeft;
  5955. this._cache.orthoRight = this.orthoRight;
  5956. this._cache.orthoBottom = this.orthoBottom;
  5957. this._cache.orthoTop = this.orthoTop;
  5958. this._cache.renderWidth = engine.getRenderWidth();
  5959. this._cache.renderHeight = engine.getRenderHeight();
  5960. };
  5961. Camera.prototype._updateFromScene = function () {
  5962. this.updateCache();
  5963. this._update();
  5964. };
  5965. // Synchronized
  5966. Camera.prototype._isSynchronized = function () {
  5967. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5968. };
  5969. Camera.prototype._isSynchronizedViewMatrix = function () {
  5970. if (!_super.prototype._isSynchronized.call(this))
  5971. return false;
  5972. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5973. };
  5974. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5975. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5976. if (!check) {
  5977. return false;
  5978. }
  5979. var engine = this.getEngine();
  5980. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5981. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5982. } else {
  5983. 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();
  5984. }
  5985. return check;
  5986. };
  5987. // Controls
  5988. Camera.prototype.attachControl = function (element) {
  5989. };
  5990. Camera.prototype.detachControl = function (element) {
  5991. };
  5992. Camera.prototype._update = function () {
  5993. };
  5994. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5995. if (typeof insertAt === "undefined") { insertAt = null; }
  5996. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5997. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5998. return 0;
  5999. }
  6000. if (insertAt == null || insertAt < 0) {
  6001. this._postProcesses.push(postProcess);
  6002. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6003. return this._postProcesses.length - 1;
  6004. }
  6005. var add = 0;
  6006. if (this._postProcesses[insertAt]) {
  6007. var start = this._postProcesses.length - 1;
  6008. for (var i = start; i >= insertAt + 1; --i) {
  6009. this._postProcesses[i + 1] = this._postProcesses[i];
  6010. }
  6011. add = 1;
  6012. }
  6013. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6014. if (this._postProcessesTakenIndices[i] < insertAt) {
  6015. continue;
  6016. }
  6017. start = this._postProcessesTakenIndices.length - 1;
  6018. for (var j = start; j >= i; --j) {
  6019. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6020. }
  6021. this._postProcessesTakenIndices[i] = insertAt;
  6022. break;
  6023. }
  6024. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6025. this._postProcessesTakenIndices.push(insertAt);
  6026. }
  6027. var result = insertAt + add;
  6028. this._postProcesses[result] = postProcess;
  6029. return result;
  6030. };
  6031. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6032. if (typeof atIndices === "undefined") { atIndices = null; }
  6033. var result = [];
  6034. if (!atIndices) {
  6035. var length = this._postProcesses.length;
  6036. for (var i = 0; i < length; i++) {
  6037. if (this._postProcesses[i] !== postProcess) {
  6038. continue;
  6039. }
  6040. delete this._postProcesses[i];
  6041. var index = this._postProcessesTakenIndices.indexOf(i);
  6042. this._postProcessesTakenIndices.splice(index, 1);
  6043. }
  6044. } else {
  6045. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6046. for (i = 0; i < atIndices.length; i++) {
  6047. var foundPostProcess = this._postProcesses[atIndices[i]];
  6048. if (foundPostProcess !== postProcess) {
  6049. result.push(i);
  6050. continue;
  6051. }
  6052. delete this._postProcesses[atIndices[i]];
  6053. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6054. this._postProcessesTakenIndices.splice(index, 1);
  6055. }
  6056. }
  6057. return result;
  6058. };
  6059. Camera.prototype.getWorldMatrix = function () {
  6060. if (!this._worldMatrix) {
  6061. this._worldMatrix = BABYLON.Matrix.Identity();
  6062. }
  6063. var viewMatrix = this.getViewMatrix();
  6064. viewMatrix.invertToRef(this._worldMatrix);
  6065. return this._worldMatrix;
  6066. };
  6067. Camera.prototype._getViewMatrix = function () {
  6068. return BABYLON.Matrix.Identity();
  6069. };
  6070. Camera.prototype.getViewMatrix = function () {
  6071. this._computedViewMatrix = this._computeViewMatrix();
  6072. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6073. return this._computedViewMatrix;
  6074. }
  6075. if (!this._worldMatrix) {
  6076. this._worldMatrix = BABYLON.Matrix.Identity();
  6077. }
  6078. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6079. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6080. this._computedViewMatrix.invert();
  6081. this._currentRenderId = this.getScene().getRenderId();
  6082. return this._computedViewMatrix;
  6083. };
  6084. Camera.prototype._computeViewMatrix = function (force) {
  6085. if (!force && this._isSynchronizedViewMatrix()) {
  6086. return this._computedViewMatrix;
  6087. }
  6088. this._computedViewMatrix = this._getViewMatrix();
  6089. if (!this.parent || !this.parent.getWorldMatrix) {
  6090. this._currentRenderId = this.getScene().getRenderId();
  6091. }
  6092. return this._computedViewMatrix;
  6093. };
  6094. Camera.prototype.getProjectionMatrix = function (force) {
  6095. if (!force && this._isSynchronizedProjectionMatrix()) {
  6096. return this._projectionMatrix;
  6097. }
  6098. var engine = this.getEngine();
  6099. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6100. if (this.minZ <= 0) {
  6101. this.minZ = 0.1;
  6102. }
  6103. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6104. return this._projectionMatrix;
  6105. }
  6106. var halfWidth = engine.getRenderWidth() / 2.0;
  6107. var halfHeight = engine.getRenderHeight() / 2.0;
  6108. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6109. return this._projectionMatrix;
  6110. };
  6111. Camera.prototype.dispose = function () {
  6112. // Remove from scene
  6113. var index = this.getScene().cameras.indexOf(this);
  6114. this.getScene().cameras.splice(index, 1);
  6115. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6116. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6117. }
  6118. };
  6119. Camera.PERSPECTIVE_CAMERA = 0;
  6120. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6121. return Camera;
  6122. })(BABYLON.Node);
  6123. BABYLON.Camera = Camera;
  6124. })(BABYLON || (BABYLON = {}));
  6125. //# sourceMappingURL=babylon.camera.js.map
  6126. var BABYLON;
  6127. (function (BABYLON) {
  6128. var TargetCamera = (function (_super) {
  6129. __extends(TargetCamera, _super);
  6130. function TargetCamera(name, position, scene) {
  6131. _super.call(this, name, position, scene);
  6132. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6133. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6134. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6135. this.speed = 2.0;
  6136. this.noRotationConstraint = false;
  6137. this.lockedTarget = null;
  6138. this._currentTarget = BABYLON.Vector3.Zero();
  6139. this._viewMatrix = BABYLON.Matrix.Zero();
  6140. this._camMatrix = BABYLON.Matrix.Zero();
  6141. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6142. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6143. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6144. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6145. this._lookAtTemp = BABYLON.Matrix.Zero();
  6146. this._tempMatrix = BABYLON.Matrix.Zero();
  6147. }
  6148. TargetCamera.prototype._getLockedTargetPosition = function () {
  6149. if (!this.lockedTarget) {
  6150. return null;
  6151. }
  6152. return this.lockedTarget.position || this.lockedTarget;
  6153. };
  6154. // Cache
  6155. TargetCamera.prototype._initCache = function () {
  6156. _super.prototype._initCache.call(this);
  6157. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6158. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6159. };
  6160. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6161. if (!ignoreParentClass) {
  6162. _super.prototype._updateCache.call(this);
  6163. }
  6164. var lockedTargetPosition = this._getLockedTargetPosition();
  6165. if (!lockedTargetPosition) {
  6166. this._cache.lockedTarget = null;
  6167. } else {
  6168. if (!this._cache.lockedTarget) {
  6169. this._cache.lockedTarget = lockedTargetPosition.clone();
  6170. } else {
  6171. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6172. }
  6173. }
  6174. this._cache.rotation.copyFrom(this.rotation);
  6175. };
  6176. // Synchronized
  6177. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6178. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6179. return false;
  6180. }
  6181. var lockedTargetPosition = this._getLockedTargetPosition();
  6182. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6183. };
  6184. // Methods
  6185. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6186. var engine = this.getEngine();
  6187. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6188. };
  6189. // Target
  6190. TargetCamera.prototype.setTarget = function (target) {
  6191. this.upVector.normalize();
  6192. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6193. this._camMatrix.invert();
  6194. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6195. var vDir = target.subtract(this.position);
  6196. if (vDir.x >= 0.0) {
  6197. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6198. } else {
  6199. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6200. }
  6201. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6202. if (isNaN(this.rotation.x)) {
  6203. this.rotation.x = 0;
  6204. }
  6205. if (isNaN(this.rotation.y)) {
  6206. this.rotation.y = 0;
  6207. }
  6208. if (isNaN(this.rotation.z)) {
  6209. this.rotation.z = 0;
  6210. }
  6211. };
  6212. TargetCamera.prototype.getTarget = function () {
  6213. return this._currentTarget;
  6214. };
  6215. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6216. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6217. };
  6218. TargetCamera.prototype._updatePosition = function () {
  6219. this.position.addInPlace(this.cameraDirection);
  6220. };
  6221. TargetCamera.prototype._update = function () {
  6222. var needToMove = this._decideIfNeedsToMove();
  6223. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6224. // Move
  6225. if (needToMove) {
  6226. this._updatePosition();
  6227. }
  6228. // Rotate
  6229. if (needToRotate) {
  6230. this.rotation.x += this.cameraRotation.x;
  6231. this.rotation.y += this.cameraRotation.y;
  6232. if (!this.noRotationConstraint) {
  6233. var limit = (Math.PI / 2) * 0.95;
  6234. if (this.rotation.x > limit)
  6235. this.rotation.x = limit;
  6236. if (this.rotation.x < -limit)
  6237. this.rotation.x = -limit;
  6238. }
  6239. }
  6240. // Inertia
  6241. if (needToMove) {
  6242. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6243. this.cameraDirection.x = 0;
  6244. }
  6245. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6246. this.cameraDirection.y = 0;
  6247. }
  6248. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6249. this.cameraDirection.z = 0;
  6250. }
  6251. this.cameraDirection.scaleInPlace(this.inertia);
  6252. }
  6253. if (needToRotate) {
  6254. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6255. this.cameraRotation.x = 0;
  6256. }
  6257. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6258. this.cameraRotation.y = 0;
  6259. }
  6260. this.cameraRotation.scaleInPlace(this.inertia);
  6261. }
  6262. };
  6263. TargetCamera.prototype._getViewMatrix = function () {
  6264. if (!this.lockedTarget) {
  6265. // Compute
  6266. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6267. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6268. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6269. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6270. this._lookAtTemp.invert();
  6271. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6272. } else {
  6273. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6274. }
  6275. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6276. // Computing target and final matrix
  6277. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6278. } else {
  6279. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6280. }
  6281. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6282. return this._viewMatrix;
  6283. };
  6284. return TargetCamera;
  6285. })(BABYLON.Camera);
  6286. BABYLON.TargetCamera = TargetCamera;
  6287. })(BABYLON || (BABYLON = {}));
  6288. //# sourceMappingURL=babylon.targetCamera.js.map
  6289. var BABYLON;
  6290. (function (BABYLON) {
  6291. var FollowCamera = (function (_super) {
  6292. __extends(FollowCamera, _super);
  6293. function FollowCamera(name, position, scene) {
  6294. _super.call(this, name, position, scene);
  6295. this.radius = 12;
  6296. this.rotationOffset = 0;
  6297. this.heightOffset = 4;
  6298. this.cameraAcceleration = 0.05;
  6299. this.maxCameraSpeed = 20;
  6300. }
  6301. FollowCamera.prototype.getRadians = function (degrees) {
  6302. return degrees * Math.PI / 180;
  6303. };
  6304. FollowCamera.prototype.follow = function (cameraTarget) {
  6305. if (!cameraTarget)
  6306. return;
  6307. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6308. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6309. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6310. var dx = targetX - this.position.x;
  6311. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6312. var dz = (targetZ) - this.position.z;
  6313. var vx = dx * this.cameraAcceleration * 2;
  6314. var vy = dy * this.cameraAcceleration;
  6315. var vz = dz * this.cameraAcceleration * 2;
  6316. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6317. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6318. }
  6319. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6320. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6321. }
  6322. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6323. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6324. }
  6325. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6326. this.setTarget(cameraTarget.position);
  6327. };
  6328. FollowCamera.prototype._update = function () {
  6329. _super.prototype._update.call(this);
  6330. this.follow(this.target);
  6331. };
  6332. return FollowCamera;
  6333. })(BABYLON.TargetCamera);
  6334. BABYLON.FollowCamera = FollowCamera;
  6335. })(BABYLON || (BABYLON = {}));
  6336. //# sourceMappingURL=babylon.followCamera.js.map
  6337. var BABYLON;
  6338. (function (BABYLON) {
  6339. var FreeCamera = (function (_super) {
  6340. __extends(FreeCamera, _super);
  6341. function FreeCamera(name, position, scene) {
  6342. _super.call(this, name, position, scene);
  6343. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6344. this.keysUp = [38];
  6345. this.keysDown = [40];
  6346. this.keysLeft = [37];
  6347. this.keysRight = [39];
  6348. this.checkCollisions = false;
  6349. this.applyGravity = false;
  6350. this.angularSensibility = 2000.0;
  6351. this._keys = [];
  6352. this._collider = new BABYLON.Collider();
  6353. this._needMoveForGravity = true;
  6354. this._oldPosition = BABYLON.Vector3.Zero();
  6355. this._diffPosition = BABYLON.Vector3.Zero();
  6356. this._newPosition = BABYLON.Vector3.Zero();
  6357. }
  6358. // Controls
  6359. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6360. var _this = this;
  6361. var previousPosition;
  6362. var engine = this.getEngine();
  6363. if (this._attachedElement) {
  6364. return;
  6365. }
  6366. this._attachedElement = element;
  6367. if (this._onMouseDown === undefined) {
  6368. this._onMouseDown = function (evt) {
  6369. previousPosition = {
  6370. x: evt.clientX,
  6371. y: evt.clientY
  6372. };
  6373. if (!noPreventDefault) {
  6374. evt.preventDefault();
  6375. }
  6376. };
  6377. this._onMouseUp = function (evt) {
  6378. previousPosition = null;
  6379. if (!noPreventDefault) {
  6380. evt.preventDefault();
  6381. }
  6382. };
  6383. this._onMouseOut = function (evt) {
  6384. previousPosition = null;
  6385. _this._keys = [];
  6386. if (!noPreventDefault) {
  6387. evt.preventDefault();
  6388. }
  6389. };
  6390. this._onMouseMove = function (evt) {
  6391. if (!previousPosition && !engine.isPointerLock) {
  6392. return;
  6393. }
  6394. var offsetX;
  6395. var offsetY;
  6396. if (!engine.isPointerLock) {
  6397. offsetX = evt.clientX - previousPosition.x;
  6398. offsetY = evt.clientY - previousPosition.y;
  6399. } else {
  6400. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6401. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6402. }
  6403. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6404. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6405. previousPosition = {
  6406. x: evt.clientX,
  6407. y: evt.clientY
  6408. };
  6409. if (!noPreventDefault) {
  6410. evt.preventDefault();
  6411. }
  6412. };
  6413. this._onKeyDown = function (evt) {
  6414. 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) {
  6415. var index = _this._keys.indexOf(evt.keyCode);
  6416. if (index === -1) {
  6417. _this._keys.push(evt.keyCode);
  6418. }
  6419. if (!noPreventDefault) {
  6420. evt.preventDefault();
  6421. }
  6422. }
  6423. };
  6424. this._onKeyUp = function (evt) {
  6425. 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) {
  6426. var index = _this._keys.indexOf(evt.keyCode);
  6427. if (index >= 0) {
  6428. _this._keys.splice(index, 1);
  6429. }
  6430. if (!noPreventDefault) {
  6431. evt.preventDefault();
  6432. }
  6433. }
  6434. };
  6435. this._onLostFocus = function () {
  6436. _this._keys = [];
  6437. };
  6438. this._reset = function () {
  6439. _this._keys = [];
  6440. previousPosition = null;
  6441. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6442. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6443. };
  6444. }
  6445. element.addEventListener("mousedown", this._onMouseDown, false);
  6446. element.addEventListener("mouseup", this._onMouseUp, false);
  6447. element.addEventListener("mouseout", this._onMouseOut, false);
  6448. element.addEventListener("mousemove", this._onMouseMove, false);
  6449. BABYLON.Tools.RegisterTopRootEvents([
  6450. { name: "keydown", handler: this._onKeyDown },
  6451. { name: "keyup", handler: this._onKeyUp },
  6452. { name: "blur", handler: this._onLostFocus }
  6453. ]);
  6454. };
  6455. FreeCamera.prototype.detachControl = function (element) {
  6456. if (this._attachedElement != element) {
  6457. return;
  6458. }
  6459. element.removeEventListener("mousedown", this._onMouseDown);
  6460. element.removeEventListener("mouseup", this._onMouseUp);
  6461. element.removeEventListener("mouseout", this._onMouseOut);
  6462. element.removeEventListener("mousemove", this._onMouseMove);
  6463. BABYLON.Tools.UnregisterTopRootEvents([
  6464. { name: "keydown", handler: this._onKeyDown },
  6465. { name: "keyup", handler: this._onKeyUp },
  6466. { name: "blur", handler: this._onLostFocus }
  6467. ]);
  6468. this._attachedElement = null;
  6469. if (this._reset) {
  6470. this._reset();
  6471. }
  6472. };
  6473. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6474. var globalPosition;
  6475. if (this.parent) {
  6476. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6477. } else {
  6478. globalPosition = this.position;
  6479. }
  6480. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6481. this._collider.radius = this.ellipsoid;
  6482. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6483. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6484. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6485. this.position.addInPlace(this._diffPosition);
  6486. if (this.onCollide) {
  6487. this.onCollide(this._collider.collidedMesh);
  6488. }
  6489. }
  6490. };
  6491. FreeCamera.prototype._checkInputs = function () {
  6492. if (!this._localDirection) {
  6493. this._localDirection = BABYLON.Vector3.Zero();
  6494. this._transformedDirection = BABYLON.Vector3.Zero();
  6495. }
  6496. for (var index = 0; index < this._keys.length; index++) {
  6497. var keyCode = this._keys[index];
  6498. var speed = this._computeLocalCameraSpeed();
  6499. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6500. this._localDirection.copyFromFloats(-speed, 0, 0);
  6501. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6502. this._localDirection.copyFromFloats(0, 0, speed);
  6503. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6504. this._localDirection.copyFromFloats(speed, 0, 0);
  6505. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6506. this._localDirection.copyFromFloats(0, 0, -speed);
  6507. }
  6508. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6509. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6510. this.cameraDirection.addInPlace(this._transformedDirection);
  6511. }
  6512. };
  6513. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6514. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6515. };
  6516. FreeCamera.prototype._updatePosition = function () {
  6517. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6518. this._collideWithWorld(this.cameraDirection);
  6519. if (this.applyGravity) {
  6520. var oldPosition = this.position;
  6521. this._collideWithWorld(this.getScene().gravity);
  6522. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6523. }
  6524. } else {
  6525. this.position.addInPlace(this.cameraDirection);
  6526. }
  6527. };
  6528. FreeCamera.prototype._update = function () {
  6529. this._checkInputs();
  6530. _super.prototype._update.call(this);
  6531. };
  6532. return FreeCamera;
  6533. })(BABYLON.TargetCamera);
  6534. BABYLON.FreeCamera = FreeCamera;
  6535. })(BABYLON || (BABYLON = {}));
  6536. //# sourceMappingURL=babylon.freeCamera.js.map
  6537. var BABYLON;
  6538. (function (BABYLON) {
  6539. // We're mainly based on the logic defined into the FreeCamera code
  6540. var TouchCamera = (function (_super) {
  6541. __extends(TouchCamera, _super);
  6542. function TouchCamera(name, position, scene) {
  6543. _super.call(this, name, position, scene);
  6544. this._offsetX = null;
  6545. this._offsetY = null;
  6546. this._pointerCount = 0;
  6547. this._pointerPressed = [];
  6548. this.angularSensibility = 200000.0;
  6549. this.moveSensibility = 500.0;
  6550. }
  6551. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6552. var _this = this;
  6553. var previousPosition;
  6554. if (this._attachedCanvas) {
  6555. return;
  6556. }
  6557. this._attachedCanvas = canvas;
  6558. if (this._onPointerDown === undefined) {
  6559. this._onPointerDown = function (evt) {
  6560. if (!noPreventDefault) {
  6561. evt.preventDefault();
  6562. }
  6563. _this._pointerPressed.push(evt.pointerId);
  6564. if (_this._pointerPressed.length !== 1) {
  6565. return;
  6566. }
  6567. previousPosition = {
  6568. x: evt.clientX,
  6569. y: evt.clientY
  6570. };
  6571. };
  6572. this._onPointerUp = function (evt) {
  6573. if (!noPreventDefault) {
  6574. evt.preventDefault();
  6575. }
  6576. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6577. if (index === -1) {
  6578. return;
  6579. }
  6580. _this._pointerPressed.splice(index, 1);
  6581. if (index != 0) {
  6582. return;
  6583. }
  6584. previousPosition = null;
  6585. _this._offsetX = null;
  6586. _this._offsetY = null;
  6587. };
  6588. this._onPointerMove = function (evt) {
  6589. if (!noPreventDefault) {
  6590. evt.preventDefault();
  6591. }
  6592. if (!previousPosition) {
  6593. return;
  6594. }
  6595. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6596. if (index != 0) {
  6597. return;
  6598. }
  6599. _this._offsetX = evt.clientX - previousPosition.x;
  6600. _this._offsetY = -(evt.clientY - previousPosition.y);
  6601. };
  6602. this._onLostFocus = function () {
  6603. _this._offsetX = null;
  6604. _this._offsetY = null;
  6605. };
  6606. }
  6607. canvas.addEventListener("pointerdown", this._onPointerDown);
  6608. canvas.addEventListener("pointerup", this._onPointerUp);
  6609. canvas.addEventListener("pointerout", this._onPointerUp);
  6610. canvas.addEventListener("pointermove", this._onPointerMove);
  6611. BABYLON.Tools.RegisterTopRootEvents([
  6612. { name: "blur", handler: this._onLostFocus }
  6613. ]);
  6614. };
  6615. TouchCamera.prototype.detachControl = function (canvas) {
  6616. if (this._attachedCanvas != canvas) {
  6617. return;
  6618. }
  6619. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6620. canvas.removeEventListener("pointerup", this._onPointerUp);
  6621. canvas.removeEventListener("pointerout", this._onPointerUp);
  6622. canvas.removeEventListener("pointermove", this._onPointerMove);
  6623. BABYLON.Tools.UnregisterTopRootEvents([
  6624. { name: "blur", handler: this._onLostFocus }
  6625. ]);
  6626. this._attachedCanvas = null;
  6627. };
  6628. TouchCamera.prototype._checkInputs = function () {
  6629. if (!this._offsetX) {
  6630. return;
  6631. }
  6632. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6633. if (this._pointerPressed.length > 1) {
  6634. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6635. } else {
  6636. var speed = this._computeLocalCameraSpeed();
  6637. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6638. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6639. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6640. }
  6641. };
  6642. return TouchCamera;
  6643. })(BABYLON.FreeCamera);
  6644. BABYLON.TouchCamera = TouchCamera;
  6645. })(BABYLON || (BABYLON = {}));
  6646. //# sourceMappingURL=babylon.touchCamera.js.map
  6647. var BABYLON;
  6648. (function (BABYLON) {
  6649. // We're mainly based on the logic defined into the FreeCamera code
  6650. var DeviceOrientationCamera = (function (_super) {
  6651. __extends(DeviceOrientationCamera, _super);
  6652. function DeviceOrientationCamera(name, position, scene) {
  6653. var _this = this;
  6654. _super.call(this, name, position, scene);
  6655. this._offsetX = null;
  6656. this._offsetY = null;
  6657. this._orientationGamma = 0;
  6658. this._orientationBeta = 0;
  6659. this._initialOrientationGamma = 0;
  6660. this._initialOrientationBeta = 0;
  6661. this.angularSensibility = 10000.0;
  6662. this.moveSensibility = 50.0;
  6663. window.addEventListener("resize", function () {
  6664. _this._initialOrientationGamma = null;
  6665. }, false);
  6666. }
  6667. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6668. var _this = this;
  6669. if (this._attachedCanvas) {
  6670. return;
  6671. }
  6672. this._attachedCanvas = canvas;
  6673. if (!this._orientationChanged) {
  6674. this._orientationChanged = function (evt) {
  6675. if (!_this._initialOrientationGamma) {
  6676. _this._initialOrientationGamma = evt.gamma;
  6677. _this._initialOrientationBeta = evt.beta;
  6678. }
  6679. _this._orientationGamma = evt.gamma;
  6680. _this._orientationBeta = evt.beta;
  6681. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6682. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6683. };
  6684. }
  6685. window.addEventListener("deviceorientation", this._orientationChanged);
  6686. };
  6687. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6688. if (this._attachedCanvas != canvas) {
  6689. return;
  6690. }
  6691. window.removeEventListener("deviceorientation", this._orientationChanged);
  6692. this._attachedCanvas = null;
  6693. this._orientationGamma = 0;
  6694. this._orientationBeta = 0;
  6695. this._initialOrientationGamma = 0;
  6696. this._initialOrientationBeta = 0;
  6697. };
  6698. DeviceOrientationCamera.prototype._checkInputs = function () {
  6699. if (!this._offsetX) {
  6700. return;
  6701. }
  6702. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6703. var speed = this._computeLocalCameraSpeed();
  6704. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6705. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6706. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6707. };
  6708. return DeviceOrientationCamera;
  6709. })(BABYLON.FreeCamera);
  6710. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6711. })(BABYLON || (BABYLON = {}));
  6712. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6713. var BABYLON;
  6714. (function (BABYLON) {
  6715. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6716. var ArcRotateCamera = (function (_super) {
  6717. __extends(ArcRotateCamera, _super);
  6718. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6719. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6720. this.alpha = alpha;
  6721. this.beta = beta;
  6722. this.radius = radius;
  6723. this.target = target;
  6724. this.inertialAlphaOffset = 0;
  6725. this.inertialBetaOffset = 0;
  6726. this.inertialRadiusOffset = 0;
  6727. this.lowerAlphaLimit = null;
  6728. this.upperAlphaLimit = null;
  6729. this.lowerBetaLimit = 0.01;
  6730. this.upperBetaLimit = Math.PI;
  6731. this.lowerRadiusLimit = null;
  6732. this.upperRadiusLimit = null;
  6733. this.angularSensibility = 1000.0;
  6734. this.wheelPrecision = 3.0;
  6735. this.keysUp = [38];
  6736. this.keysDown = [40];
  6737. this.keysLeft = [37];
  6738. this.keysRight = [39];
  6739. this.zoomOnFactor = 1;
  6740. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6741. this._keys = [];
  6742. this._viewMatrix = new BABYLON.Matrix();
  6743. this.checkCollisions = false;
  6744. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6745. this._collider = new BABYLON.Collider();
  6746. this._previousPosition = BABYLON.Vector3.Zero();
  6747. this._collisionVelocity = BABYLON.Vector3.Zero();
  6748. this._newPosition = BABYLON.Vector3.Zero();
  6749. // Pinch
  6750. // value for pinch step scaling
  6751. // set to 20 by default
  6752. this.pinchPrecision = 20;
  6753. this.getViewMatrix();
  6754. }
  6755. ArcRotateCamera.prototype._getTargetPosition = function () {
  6756. return this.target.position || this.target;
  6757. };
  6758. // Cache
  6759. ArcRotateCamera.prototype._initCache = function () {
  6760. _super.prototype._initCache.call(this);
  6761. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6762. this._cache.alpha = undefined;
  6763. this._cache.beta = undefined;
  6764. this._cache.radius = undefined;
  6765. this._cache.targetScreenOffset = undefined;
  6766. };
  6767. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6768. if (!ignoreParentClass) {
  6769. _super.prototype._updateCache.call(this);
  6770. }
  6771. this._cache.target.copyFrom(this._getTargetPosition());
  6772. this._cache.alpha = this.alpha;
  6773. this._cache.beta = this.beta;
  6774. this._cache.radius = this.radius;
  6775. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6776. };
  6777. // Synchronized
  6778. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6779. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6780. return false;
  6781. 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);
  6782. };
  6783. // Methods
  6784. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6785. var _this = this;
  6786. var previousPosition;
  6787. var pointerId;
  6788. // to know if pinch started
  6789. var pinchStarted = false;
  6790. // two pinch point on X
  6791. // that will use for find if user action is pinch open or pinch close
  6792. var pinchPointX1, pinchPointX2;
  6793. if (this._attachedElement) {
  6794. return;
  6795. }
  6796. this._attachedElement = element;
  6797. var engine = this.getEngine();
  6798. if (this._onPointerDown === undefined) {
  6799. this._onPointerDown = function (evt) {
  6800. if (pointerId) {
  6801. return;
  6802. }
  6803. pointerId = evt.pointerId;
  6804. previousPosition = {
  6805. x: evt.clientX,
  6806. y: evt.clientY
  6807. };
  6808. if (!noPreventDefault) {
  6809. evt.preventDefault();
  6810. }
  6811. };
  6812. this._onPointerUp = function (evt) {
  6813. previousPosition = null;
  6814. pointerId = null;
  6815. if (!noPreventDefault) {
  6816. evt.preventDefault();
  6817. }
  6818. };
  6819. this._onPointerMove = function (evt) {
  6820. if (!previousPosition) {
  6821. return;
  6822. }
  6823. if (pointerId !== evt.pointerId) {
  6824. return;
  6825. }
  6826. // return pinch is started
  6827. if (pinchStarted) {
  6828. return;
  6829. }
  6830. var offsetX = evt.clientX - previousPosition.x;
  6831. var offsetY = evt.clientY - previousPosition.y;
  6832. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6833. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6834. previousPosition = {
  6835. x: evt.clientX,
  6836. y: evt.clientY
  6837. };
  6838. if (!noPreventDefault) {
  6839. evt.preventDefault();
  6840. }
  6841. };
  6842. this._onMouseMove = function (evt) {
  6843. if (!engine.isPointerLock) {
  6844. return;
  6845. }
  6846. // return pinch is started
  6847. if (pinchStarted) {
  6848. return;
  6849. }
  6850. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6851. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6852. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6853. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6854. if (!noPreventDefault) {
  6855. evt.preventDefault();
  6856. }
  6857. };
  6858. this._wheel = function (event) {
  6859. var delta = 0;
  6860. if (event.wheelDelta) {
  6861. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6862. } else if (event.detail) {
  6863. delta = -event.detail / _this.wheelPrecision;
  6864. }
  6865. if (delta)
  6866. _this.inertialRadiusOffset += delta;
  6867. if (event.preventDefault) {
  6868. if (!noPreventDefault) {
  6869. event.preventDefault();
  6870. }
  6871. }
  6872. };
  6873. this._onKeyDown = function (evt) {
  6874. 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) {
  6875. var index = _this._keys.indexOf(evt.keyCode);
  6876. if (index === -1) {
  6877. _this._keys.push(evt.keyCode);
  6878. }
  6879. if (evt.preventDefault) {
  6880. if (!noPreventDefault) {
  6881. evt.preventDefault();
  6882. }
  6883. }
  6884. }
  6885. };
  6886. this._onKeyUp = function (evt) {
  6887. 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) {
  6888. var index = _this._keys.indexOf(evt.keyCode);
  6889. if (index >= 0) {
  6890. _this._keys.splice(index, 1);
  6891. }
  6892. if (evt.preventDefault) {
  6893. if (!noPreventDefault) {
  6894. evt.preventDefault();
  6895. }
  6896. }
  6897. }
  6898. };
  6899. this._onLostFocus = function () {
  6900. _this._keys = [];
  6901. pointerId = null;
  6902. };
  6903. this._onGestureStart = function (e) {
  6904. if (window.MSGesture === undefined) {
  6905. return;
  6906. }
  6907. if (!_this._MSGestureHandler) {
  6908. _this._MSGestureHandler = new MSGesture();
  6909. _this._MSGestureHandler.target = element;
  6910. }
  6911. _this._MSGestureHandler.addPointer(e.pointerId);
  6912. };
  6913. this._onGesture = function (e) {
  6914. _this.radius *= e.scale;
  6915. if (e.preventDefault) {
  6916. if (!noPreventDefault) {
  6917. e.stopPropagation();
  6918. e.preventDefault();
  6919. }
  6920. }
  6921. };
  6922. this._reset = function () {
  6923. _this._keys = [];
  6924. _this.inertialAlphaOffset = 0;
  6925. _this.inertialBetaOffset = 0;
  6926. _this.inertialRadiusOffset = 0;
  6927. previousPosition = null;
  6928. pointerId = null;
  6929. };
  6930. this._touchStart = function (event) {
  6931. if (event.touches.length === 2) {
  6932. //-- start pinch if two fingers on the screen
  6933. pinchStarted = true;
  6934. _this._pinchStart(event);
  6935. }
  6936. };
  6937. this._touchMove = function (event) {
  6938. if (pinchStarted) {
  6939. //-- make scaling
  6940. _this._pinchMove(event);
  6941. }
  6942. };
  6943. this._touchEnd = function (event) {
  6944. if (pinchStarted) {
  6945. //-- end of pinch
  6946. _this._pinchEnd(event);
  6947. }
  6948. };
  6949. this._pinchStart = function (event) {
  6950. // save origin touch point
  6951. pinchPointX1 = event.touches[0].clientX;
  6952. pinchPointX2 = event.touches[1].clientX;
  6953. // block the camera
  6954. // if not it rotate around target during pinch
  6955. pinchStarted = true;
  6956. };
  6957. this._pinchMove = function (event) {
  6958. // variable for new camera's radius
  6959. var delta = 0;
  6960. // variables to know if pinch open or pinch close
  6961. var direction = 1;
  6962. var distanceXOrigine, distanceXNow;
  6963. if (event.touches.length !== 2)
  6964. return;
  6965. // calculate absolute distances of the two fingers
  6966. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6967. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6968. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  6969. if (distanceXNow < distanceXOrigine) {
  6970. direction = -1;
  6971. }
  6972. // calculate new radius
  6973. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6974. // set new radius
  6975. _this.inertialRadiusOffset -= delta;
  6976. // save origin touch point
  6977. pinchPointX1 = event.touches[0].clientX;
  6978. pinchPointX2 = event.touches[1].clientX;
  6979. };
  6980. this._pinchEnd = function (event) {
  6981. // cancel pinch and deblock camera rotation
  6982. pinchStarted = false;
  6983. };
  6984. }
  6985. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6986. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6987. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6988. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6989. element.addEventListener("mousemove", this._onMouseMove, false);
  6990. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6991. element.addEventListener("MSGestureChange", this._onGesture, false);
  6992. element.addEventListener('mousewheel', this._wheel, false);
  6993. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6994. // pinch
  6995. element.addEventListener('touchstart', this._touchStart, false);
  6996. element.addEventListener('touchmove', this._touchMove, false);
  6997. element.addEventListener('touchend', this._touchEnd, false);
  6998. BABYLON.Tools.RegisterTopRootEvents([
  6999. { name: "keydown", handler: this._onKeyDown },
  7000. { name: "keyup", handler: this._onKeyUp },
  7001. { name: "blur", handler: this._onLostFocus }
  7002. ]);
  7003. };
  7004. ArcRotateCamera.prototype.detachControl = function (element) {
  7005. if (this._attachedElement != element) {
  7006. return;
  7007. }
  7008. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7009. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7010. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7011. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7012. element.removeEventListener("mousemove", this._onMouseMove);
  7013. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7014. element.removeEventListener("MSGestureChange", this._onGesture);
  7015. element.removeEventListener('mousewheel', this._wheel);
  7016. element.removeEventListener('DOMMouseScroll', this._wheel);
  7017. // pinch
  7018. element.removeEventListener('touchstart', this._touchStart);
  7019. element.removeEventListener('touchmove', this._touchMove);
  7020. element.removeEventListener('touchend', this._touchEnd);
  7021. BABYLON.Tools.UnregisterTopRootEvents([
  7022. { name: "keydown", handler: this._onKeyDown },
  7023. { name: "keyup", handler: this._onKeyUp },
  7024. { name: "blur", handler: this._onLostFocus }
  7025. ]);
  7026. this._MSGestureHandler = null;
  7027. this._attachedElement = null;
  7028. if (this._reset) {
  7029. this._reset();
  7030. }
  7031. };
  7032. ArcRotateCamera.prototype._update = function () {
  7033. for (var index = 0; index < this._keys.length; index++) {
  7034. var keyCode = this._keys[index];
  7035. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7036. this.inertialAlphaOffset -= 0.01;
  7037. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  7038. this.inertialBetaOffset -= 0.01;
  7039. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  7040. this.inertialAlphaOffset += 0.01;
  7041. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  7042. this.inertialBetaOffset += 0.01;
  7043. }
  7044. }
  7045. // Inertia
  7046. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7047. this.alpha += this.inertialAlphaOffset;
  7048. this.beta += this.inertialBetaOffset;
  7049. this.radius -= this.inertialRadiusOffset;
  7050. this.inertialAlphaOffset *= this.inertia;
  7051. this.inertialBetaOffset *= this.inertia;
  7052. this.inertialRadiusOffset *= this.inertia;
  7053. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7054. this.inertialAlphaOffset = 0;
  7055. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7056. this.inertialBetaOffset = 0;
  7057. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7058. this.inertialRadiusOffset = 0;
  7059. }
  7060. // Limits
  7061. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7062. this.alpha = this.lowerAlphaLimit;
  7063. }
  7064. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7065. this.alpha = this.upperAlphaLimit;
  7066. }
  7067. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7068. this.beta = this.lowerBetaLimit;
  7069. }
  7070. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7071. this.beta = this.upperBetaLimit;
  7072. }
  7073. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7074. this.radius = this.lowerRadiusLimit;
  7075. }
  7076. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7077. this.radius = this.upperRadiusLimit;
  7078. }
  7079. };
  7080. ArcRotateCamera.prototype.setPosition = function (position) {
  7081. var radiusv3 = position.subtract(this._getTargetPosition());
  7082. this.radius = radiusv3.length();
  7083. // Alpha
  7084. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7085. if (radiusv3.z < 0) {
  7086. this.alpha = 2 * Math.PI - this.alpha;
  7087. }
  7088. // Beta
  7089. this.beta = Math.acos(radiusv3.y / this.radius);
  7090. };
  7091. ArcRotateCamera.prototype._getViewMatrix = function () {
  7092. // Compute
  7093. var cosa = Math.cos(this.alpha);
  7094. var sina = Math.sin(this.alpha);
  7095. var cosb = Math.cos(this.beta);
  7096. var sinb = Math.sin(this.beta);
  7097. var target = this._getTargetPosition();
  7098. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7099. if (this.checkCollisions) {
  7100. this._collider.radius = this.collisionRadius;
  7101. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7102. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7103. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7104. this.position.copyFrom(this._previousPosition);
  7105. this.alpha = this._previousAlpha;
  7106. this.beta = this._previousBeta;
  7107. this.radius = this._previousRadius;
  7108. if (this.onCollide) {
  7109. this.onCollide(this._collider.collidedMesh);
  7110. }
  7111. }
  7112. }
  7113. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7114. this._previousAlpha = this.alpha;
  7115. this._previousBeta = this.beta;
  7116. this._previousRadius = this.radius;
  7117. this._previousPosition.copyFrom(this.position);
  7118. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7119. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7120. return this._viewMatrix;
  7121. };
  7122. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7123. meshes = meshes || this.getScene().meshes;
  7124. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7125. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7126. this.radius = distance * this.zoomOnFactor;
  7127. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7128. };
  7129. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7130. var meshesOrMinMaxVector;
  7131. var distance;
  7132. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7133. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7134. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7135. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7136. } else {
  7137. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7138. distance = meshesOrMinMaxVectorAndDistance.distance;
  7139. }
  7140. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7141. this.maxZ = distance * 2;
  7142. };
  7143. return ArcRotateCamera;
  7144. })(BABYLON.Camera);
  7145. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7146. })(BABYLON || (BABYLON = {}));
  7147. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  7148. var BABYLON;
  7149. (function (BABYLON) {
  7150. var Scene = (function () {
  7151. // Constructor
  7152. function Scene(engine) {
  7153. // Members
  7154. this.autoClear = true;
  7155. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7156. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7157. this.forceWireframe = false;
  7158. this.forcePointsCloud = false;
  7159. this.forceShowBoundingBoxes = false;
  7160. this.animationsEnabled = true;
  7161. this.cameraToUseForPointers = null;
  7162. // Fog
  7163. this.fogEnabled = true;
  7164. this.fogMode = Scene.FOGMODE_NONE;
  7165. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7166. this.fogDensity = 0.1;
  7167. this.fogStart = 0;
  7168. this.fogEnd = 1000.0;
  7169. // Lights
  7170. this.shadowsEnabled = true;
  7171. this.lightsEnabled = true;
  7172. this.lights = new Array();
  7173. // Cameras
  7174. this.cameras = new Array();
  7175. this.activeCameras = new Array();
  7176. // Meshes
  7177. this.meshes = new Array();
  7178. // Geometries
  7179. this._geometries = new Array();
  7180. this.materials = new Array();
  7181. this.multiMaterials = new Array();
  7182. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7183. // Textures
  7184. this.texturesEnabled = true;
  7185. this.textures = new Array();
  7186. // Particles
  7187. this.particlesEnabled = true;
  7188. this.particleSystems = new Array();
  7189. // Sprites
  7190. this.spriteManagers = new Array();
  7191. // Layers
  7192. this.layers = new Array();
  7193. // Skeletons
  7194. this.skeletonsEnabled = true;
  7195. this.skeletons = new Array();
  7196. // Lens flares
  7197. this.lensFlaresEnabled = true;
  7198. this.lensFlareSystems = new Array();
  7199. // Collisions
  7200. this.collisionsEnabled = true;
  7201. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7202. // Postprocesses
  7203. this.postProcessesEnabled = true;
  7204. // Customs render targets
  7205. this.renderTargetsEnabled = true;
  7206. this.customRenderTargets = new Array();
  7207. // Imported meshes
  7208. this.importedMeshesFiles = new Array();
  7209. this._actionManagers = new Array();
  7210. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7211. // Procedural textures
  7212. this.proceduralTexturesEnabled = true;
  7213. this._proceduralTextures = new Array();
  7214. this.soundTracks = new Array();
  7215. this._totalVertices = 0;
  7216. this._activeVertices = 0;
  7217. this._activeParticles = 0;
  7218. this._lastFrameDuration = 0;
  7219. this._evaluateActiveMeshesDuration = 0;
  7220. this._renderTargetsDuration = 0;
  7221. this._particlesDuration = 0;
  7222. this._renderDuration = 0;
  7223. this._spritesDuration = 0;
  7224. this._animationRatio = 0;
  7225. this._renderId = 0;
  7226. this._executeWhenReadyTimeoutId = -1;
  7227. this._toBeDisposed = new BABYLON.SmartArray(256);
  7228. this._onReadyCallbacks = new Array();
  7229. this._pendingData = [];
  7230. this._onBeforeRenderCallbacks = new Array();
  7231. this._onAfterRenderCallbacks = new Array();
  7232. this._activeMeshes = new BABYLON.SmartArray(256);
  7233. this._processedMaterials = new BABYLON.SmartArray(256);
  7234. this._renderTargets = new BABYLON.SmartArray(256);
  7235. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7236. this._activeSkeletons = new BABYLON.SmartArray(32);
  7237. this._activeBones = 0;
  7238. this._activeAnimatables = new Array();
  7239. this._transformMatrix = BABYLON.Matrix.Zero();
  7240. this._scaledPosition = BABYLON.Vector3.Zero();
  7241. this._scaledVelocity = BABYLON.Vector3.Zero();
  7242. this._engine = engine;
  7243. engine.scenes.push(this);
  7244. this._renderingManager = new BABYLON.RenderingManager(this);
  7245. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7246. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7247. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7248. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7249. this.attachControl();
  7250. this._debugLayer = new BABYLON.DebugLayer(this);
  7251. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7252. }
  7253. Object.defineProperty(Scene.prototype, "debugLayer", {
  7254. // Properties
  7255. get: function () {
  7256. return this._debugLayer;
  7257. },
  7258. enumerable: true,
  7259. configurable: true
  7260. });
  7261. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7262. get: function () {
  7263. return this._meshUnderPointer;
  7264. },
  7265. enumerable: true,
  7266. configurable: true
  7267. });
  7268. Object.defineProperty(Scene.prototype, "pointerX", {
  7269. get: function () {
  7270. return this._pointerX;
  7271. },
  7272. enumerable: true,
  7273. configurable: true
  7274. });
  7275. Object.defineProperty(Scene.prototype, "pointerY", {
  7276. get: function () {
  7277. return this._pointerY;
  7278. },
  7279. enumerable: true,
  7280. configurable: true
  7281. });
  7282. Scene.prototype.getCachedMaterial = function () {
  7283. return this._cachedMaterial;
  7284. };
  7285. Scene.prototype.getBoundingBoxRenderer = function () {
  7286. return this._boundingBoxRenderer;
  7287. };
  7288. Scene.prototype.getOutlineRenderer = function () {
  7289. return this._outlineRenderer;
  7290. };
  7291. Scene.prototype.getEngine = function () {
  7292. return this._engine;
  7293. };
  7294. Scene.prototype.getTotalVertices = function () {
  7295. return this._totalVertices;
  7296. };
  7297. Scene.prototype.getActiveVertices = function () {
  7298. return this._activeVertices;
  7299. };
  7300. Scene.prototype.getActiveParticles = function () {
  7301. return this._activeParticles;
  7302. };
  7303. Scene.prototype.getActiveBones = function () {
  7304. return this._activeBones;
  7305. };
  7306. // Stats
  7307. Scene.prototype.getLastFrameDuration = function () {
  7308. return this._lastFrameDuration;
  7309. };
  7310. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7311. return this._evaluateActiveMeshesDuration;
  7312. };
  7313. Scene.prototype.getActiveMeshes = function () {
  7314. return this._activeMeshes;
  7315. };
  7316. Scene.prototype.getRenderTargetsDuration = function () {
  7317. return this._renderTargetsDuration;
  7318. };
  7319. Scene.prototype.getRenderDuration = function () {
  7320. return this._renderDuration;
  7321. };
  7322. Scene.prototype.getParticlesDuration = function () {
  7323. return this._particlesDuration;
  7324. };
  7325. Scene.prototype.getSpritesDuration = function () {
  7326. return this._spritesDuration;
  7327. };
  7328. Scene.prototype.getAnimationRatio = function () {
  7329. return this._animationRatio;
  7330. };
  7331. Scene.prototype.getRenderId = function () {
  7332. return this._renderId;
  7333. };
  7334. Scene.prototype._updatePointerPosition = function (evt) {
  7335. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7336. this._pointerX = evt.clientX - canvasRect.left;
  7337. this._pointerY = evt.clientY - canvasRect.top;
  7338. if (this.cameraToUseForPointers) {
  7339. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7340. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7341. }
  7342. };
  7343. // Pointers handling
  7344. Scene.prototype.attachControl = function () {
  7345. var _this = this;
  7346. this._onPointerMove = function (evt) {
  7347. var canvas = _this._engine.getRenderingCanvas();
  7348. _this._updatePointerPosition(evt);
  7349. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7350. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7351. }, false, _this.cameraToUseForPointers);
  7352. if (pickResult.hit) {
  7353. _this._meshUnderPointer = pickResult.pickedMesh;
  7354. _this.setPointerOverMesh(pickResult.pickedMesh);
  7355. canvas.style.cursor = "pointer";
  7356. } else {
  7357. _this.setPointerOverMesh(null);
  7358. canvas.style.cursor = "";
  7359. _this._meshUnderPointer = null;
  7360. }
  7361. };
  7362. this._onPointerDown = function (evt) {
  7363. var predicate = null;
  7364. if (!_this.onPointerDown) {
  7365. predicate = function (mesh) {
  7366. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7367. };
  7368. }
  7369. _this._updatePointerPosition(evt);
  7370. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7371. if (pickResult.hit) {
  7372. if (pickResult.pickedMesh.actionManager) {
  7373. switch (evt.button) {
  7374. case 0:
  7375. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7376. break;
  7377. case 1:
  7378. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7379. break;
  7380. case 2:
  7381. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7382. break;
  7383. }
  7384. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7385. }
  7386. }
  7387. if (_this.onPointerDown) {
  7388. _this.onPointerDown(evt, pickResult);
  7389. }
  7390. };
  7391. this._onKeyDown = function (evt) {
  7392. if (_this.actionManager) {
  7393. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7394. }
  7395. };
  7396. this._onKeyUp = function (evt) {
  7397. if (_this.actionManager) {
  7398. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7399. }
  7400. };
  7401. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7402. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7403. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7404. window.addEventListener("keydown", this._onKeyDown, false);
  7405. window.addEventListener("keyup", this._onKeyUp, false);
  7406. };
  7407. Scene.prototype.detachControl = function () {
  7408. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7409. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7410. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7411. window.removeEventListener("keydown", this._onKeyDown);
  7412. window.removeEventListener("keyup", this._onKeyUp);
  7413. };
  7414. // Ready
  7415. Scene.prototype.isReady = function () {
  7416. if (this._pendingData.length > 0) {
  7417. return false;
  7418. }
  7419. for (var index = 0; index < this._geometries.length; index++) {
  7420. var geometry = this._geometries[index];
  7421. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7422. return false;
  7423. }
  7424. }
  7425. for (index = 0; index < this.meshes.length; index++) {
  7426. var mesh = this.meshes[index];
  7427. if (!mesh.isReady()) {
  7428. return false;
  7429. }
  7430. var mat = mesh.material;
  7431. if (mat) {
  7432. if (!mat.isReady(mesh)) {
  7433. return false;
  7434. }
  7435. }
  7436. }
  7437. return true;
  7438. };
  7439. Scene.prototype.resetCachedMaterial = function () {
  7440. this._cachedMaterial = null;
  7441. };
  7442. Scene.prototype.registerBeforeRender = function (func) {
  7443. this._onBeforeRenderCallbacks.push(func);
  7444. };
  7445. Scene.prototype.unregisterBeforeRender = function (func) {
  7446. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7447. if (index > -1) {
  7448. this._onBeforeRenderCallbacks.splice(index, 1);
  7449. }
  7450. };
  7451. Scene.prototype.registerAfterRender = function (func) {
  7452. this._onAfterRenderCallbacks.push(func);
  7453. };
  7454. Scene.prototype.unregisterAfterRender = function (func) {
  7455. var index = this._onAfterRenderCallbacks.indexOf(func);
  7456. if (index > -1) {
  7457. this._onAfterRenderCallbacks.splice(index, 1);
  7458. }
  7459. };
  7460. Scene.prototype._addPendingData = function (data) {
  7461. this._pendingData.push(data);
  7462. };
  7463. Scene.prototype._removePendingData = function (data) {
  7464. var index = this._pendingData.indexOf(data);
  7465. if (index !== -1) {
  7466. this._pendingData.splice(index, 1);
  7467. }
  7468. };
  7469. Scene.prototype.getWaitingItemsCount = function () {
  7470. return this._pendingData.length;
  7471. };
  7472. Scene.prototype.executeWhenReady = function (func) {
  7473. var _this = this;
  7474. this._onReadyCallbacks.push(func);
  7475. if (this._executeWhenReadyTimeoutId !== -1) {
  7476. return;
  7477. }
  7478. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7479. _this._checkIsReady();
  7480. }, 150);
  7481. };
  7482. Scene.prototype._checkIsReady = function () {
  7483. var _this = this;
  7484. if (this.isReady()) {
  7485. this._onReadyCallbacks.forEach(function (func) {
  7486. func();
  7487. });
  7488. this._onReadyCallbacks = [];
  7489. this._executeWhenReadyTimeoutId = -1;
  7490. return;
  7491. }
  7492. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7493. _this._checkIsReady();
  7494. }, 150);
  7495. };
  7496. // Animations
  7497. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7498. if (speedRatio === undefined) {
  7499. speedRatio = 1.0;
  7500. }
  7501. this.stopAnimation(target);
  7502. if (!animatable) {
  7503. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7504. }
  7505. // Local animations
  7506. if (target.animations) {
  7507. animatable.appendAnimations(target, target.animations);
  7508. }
  7509. // Children animations
  7510. if (target.getAnimatables) {
  7511. var animatables = target.getAnimatables();
  7512. for (var index = 0; index < animatables.length; index++) {
  7513. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7514. }
  7515. }
  7516. return animatable;
  7517. };
  7518. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7519. if (speedRatio === undefined) {
  7520. speedRatio = 1.0;
  7521. }
  7522. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7523. return animatable;
  7524. };
  7525. Scene.prototype.getAnimatableByTarget = function (target) {
  7526. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7527. if (this._activeAnimatables[index].target === target) {
  7528. return this._activeAnimatables[index];
  7529. }
  7530. }
  7531. return null;
  7532. };
  7533. Scene.prototype.stopAnimation = function (target) {
  7534. var animatable = this.getAnimatableByTarget(target);
  7535. if (animatable) {
  7536. animatable.stop();
  7537. }
  7538. };
  7539. Scene.prototype._animate = function () {
  7540. if (!this.animationsEnabled) {
  7541. return;
  7542. }
  7543. if (!this._animationStartDate) {
  7544. this._animationStartDate = BABYLON.Tools.Now;
  7545. }
  7546. // Getting time
  7547. var now = BABYLON.Tools.Now;
  7548. var delay = now - this._animationStartDate;
  7549. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7550. if (!this._activeAnimatables[index]._animate(delay)) {
  7551. this._activeAnimatables.splice(index, 1);
  7552. index--;
  7553. }
  7554. }
  7555. };
  7556. // Matrix
  7557. Scene.prototype.getViewMatrix = function () {
  7558. return this._viewMatrix;
  7559. };
  7560. Scene.prototype.getProjectionMatrix = function () {
  7561. return this._projectionMatrix;
  7562. };
  7563. Scene.prototype.getTransformMatrix = function () {
  7564. return this._transformMatrix;
  7565. };
  7566. Scene.prototype.setTransformMatrix = function (view, projection) {
  7567. this._viewMatrix = view;
  7568. this._projectionMatrix = projection;
  7569. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7570. };
  7571. // Methods
  7572. Scene.prototype.setActiveCameraByID = function (id) {
  7573. var camera = this.getCameraByID(id);
  7574. if (camera) {
  7575. this.activeCamera = camera;
  7576. return camera;
  7577. }
  7578. return null;
  7579. };
  7580. Scene.prototype.setActiveCameraByName = function (name) {
  7581. var camera = this.getCameraByName(name);
  7582. if (camera) {
  7583. this.activeCamera = camera;
  7584. return camera;
  7585. }
  7586. return null;
  7587. };
  7588. Scene.prototype.getMaterialByID = function (id) {
  7589. for (var index = 0; index < this.materials.length; index++) {
  7590. if (this.materials[index].id === id) {
  7591. return this.materials[index];
  7592. }
  7593. }
  7594. return null;
  7595. };
  7596. Scene.prototype.getMaterialByName = function (name) {
  7597. for (var index = 0; index < this.materials.length; index++) {
  7598. if (this.materials[index].name === name) {
  7599. return this.materials[index];
  7600. }
  7601. }
  7602. return null;
  7603. };
  7604. Scene.prototype.getCameraByID = function (id) {
  7605. for (var index = 0; index < this.cameras.length; index++) {
  7606. if (this.cameras[index].id === id) {
  7607. return this.cameras[index];
  7608. }
  7609. }
  7610. return null;
  7611. };
  7612. Scene.prototype.getCameraByName = function (name) {
  7613. for (var index = 0; index < this.cameras.length; index++) {
  7614. if (this.cameras[index].name === name) {
  7615. return this.cameras[index];
  7616. }
  7617. }
  7618. return null;
  7619. };
  7620. Scene.prototype.getLightByName = function (name) {
  7621. for (var index = 0; index < this.lights.length; index++) {
  7622. if (this.lights[index].name === name) {
  7623. return this.lights[index];
  7624. }
  7625. }
  7626. return null;
  7627. };
  7628. Scene.prototype.getLightByID = function (id) {
  7629. for (var index = 0; index < this.lights.length; index++) {
  7630. if (this.lights[index].id === id) {
  7631. return this.lights[index];
  7632. }
  7633. }
  7634. return null;
  7635. };
  7636. Scene.prototype.getGeometryByID = function (id) {
  7637. for (var index = 0; index < this._geometries.length; index++) {
  7638. if (this._geometries[index].id === id) {
  7639. return this._geometries[index];
  7640. }
  7641. }
  7642. return null;
  7643. };
  7644. Scene.prototype.pushGeometry = function (geometry, force) {
  7645. if (!force && this.getGeometryByID(geometry.id)) {
  7646. return false;
  7647. }
  7648. this._geometries.push(geometry);
  7649. return true;
  7650. };
  7651. Scene.prototype.getGeometries = function () {
  7652. return this._geometries;
  7653. };
  7654. Scene.prototype.getMeshByID = function (id) {
  7655. for (var index = 0; index < this.meshes.length; index++) {
  7656. if (this.meshes[index].id === id) {
  7657. return this.meshes[index];
  7658. }
  7659. }
  7660. return null;
  7661. };
  7662. Scene.prototype.getLastMeshByID = function (id) {
  7663. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7664. if (this.meshes[index].id === id) {
  7665. return this.meshes[index];
  7666. }
  7667. }
  7668. return null;
  7669. };
  7670. Scene.prototype.getLastEntryByID = function (id) {
  7671. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7672. if (this.meshes[index].id === id) {
  7673. return this.meshes[index];
  7674. }
  7675. }
  7676. for (index = this.cameras.length - 1; index >= 0; index--) {
  7677. if (this.cameras[index].id === id) {
  7678. return this.cameras[index];
  7679. }
  7680. }
  7681. for (index = this.lights.length - 1; index >= 0; index--) {
  7682. if (this.lights[index].id === id) {
  7683. return this.lights[index];
  7684. }
  7685. }
  7686. return null;
  7687. };
  7688. Scene.prototype.getMeshByName = function (name) {
  7689. for (var index = 0; index < this.meshes.length; index++) {
  7690. if (this.meshes[index].name === name) {
  7691. return this.meshes[index];
  7692. }
  7693. }
  7694. return null;
  7695. };
  7696. Scene.prototype.getLastSkeletonByID = function (id) {
  7697. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7698. if (this.skeletons[index].id === id) {
  7699. return this.skeletons[index];
  7700. }
  7701. }
  7702. return null;
  7703. };
  7704. Scene.prototype.getSkeletonById = function (id) {
  7705. for (var index = 0; index < this.skeletons.length; index++) {
  7706. if (this.skeletons[index].id === id) {
  7707. return this.skeletons[index];
  7708. }
  7709. }
  7710. return null;
  7711. };
  7712. Scene.prototype.getSkeletonByName = function (name) {
  7713. for (var index = 0; index < this.skeletons.length; index++) {
  7714. if (this.skeletons[index].name === name) {
  7715. return this.skeletons[index];
  7716. }
  7717. }
  7718. return null;
  7719. };
  7720. Scene.prototype.isActiveMesh = function (mesh) {
  7721. return (this._activeMeshes.indexOf(mesh) !== -1);
  7722. };
  7723. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7724. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7725. var material = subMesh.getMaterial();
  7726. if (mesh.showSubMeshesBoundingBox) {
  7727. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7728. }
  7729. if (material) {
  7730. // Render targets
  7731. if (material.getRenderTargetTextures) {
  7732. if (this._processedMaterials.indexOf(material) === -1) {
  7733. this._processedMaterials.push(material);
  7734. this._renderTargets.concat(material.getRenderTargetTextures());
  7735. }
  7736. }
  7737. // Dispatch
  7738. this._activeVertices += subMesh.indexCount;
  7739. this._renderingManager.dispatch(subMesh);
  7740. }
  7741. }
  7742. };
  7743. Scene.prototype._evaluateActiveMeshes = function () {
  7744. this._activeMeshes.reset();
  7745. this._renderingManager.reset();
  7746. this._processedMaterials.reset();
  7747. this._activeParticleSystems.reset();
  7748. this._activeSkeletons.reset();
  7749. this._boundingBoxRenderer.reset();
  7750. if (!this._frustumPlanes) {
  7751. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7752. } else {
  7753. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7754. }
  7755. // Meshes
  7756. var meshes;
  7757. var len;
  7758. if (this._selectionOctree) {
  7759. var selection = this._selectionOctree.select(this._frustumPlanes);
  7760. meshes = selection.data;
  7761. len = selection.length;
  7762. } else {
  7763. len = this.meshes.length;
  7764. meshes = this.meshes;
  7765. }
  7766. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7767. var mesh = meshes[meshIndex];
  7768. if (mesh.isBlocked) {
  7769. continue;
  7770. }
  7771. this._totalVertices += mesh.getTotalVertices();
  7772. if (!mesh.isReady()) {
  7773. continue;
  7774. }
  7775. mesh.computeWorldMatrix();
  7776. // Intersections
  7777. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7778. this._meshesForIntersections.pushNoDuplicate(mesh);
  7779. }
  7780. // Switch to current LOD
  7781. var meshLOD = mesh.getLOD(this.activeCamera);
  7782. if (!meshLOD) {
  7783. continue;
  7784. }
  7785. mesh._preActivate();
  7786. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7787. this._activeMeshes.push(mesh);
  7788. mesh._activate(this._renderId);
  7789. this._activeMesh(meshLOD);
  7790. }
  7791. }
  7792. // Particle systems
  7793. var beforeParticlesDate = BABYLON.Tools.Now;
  7794. if (this.particlesEnabled) {
  7795. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7796. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7797. var particleSystem = this.particleSystems[particleIndex];
  7798. if (!particleSystem.isStarted()) {
  7799. continue;
  7800. }
  7801. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7802. this._activeParticleSystems.push(particleSystem);
  7803. particleSystem.animate();
  7804. }
  7805. }
  7806. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7807. }
  7808. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7809. };
  7810. Scene.prototype._activeMesh = function (mesh) {
  7811. if (mesh.skeleton && this.skeletonsEnabled) {
  7812. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7813. }
  7814. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7815. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7816. }
  7817. if (mesh && mesh.subMeshes) {
  7818. // Submeshes Octrees
  7819. var len;
  7820. var subMeshes;
  7821. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7822. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7823. len = intersections.length;
  7824. subMeshes = intersections.data;
  7825. } else {
  7826. subMeshes = mesh.subMeshes;
  7827. len = subMeshes.length;
  7828. }
  7829. for (var subIndex = 0; subIndex < len; subIndex++) {
  7830. var subMesh = subMeshes[subIndex];
  7831. this._evaluateSubMesh(subMesh, mesh);
  7832. }
  7833. }
  7834. };
  7835. Scene.prototype.updateTransformMatrix = function (force) {
  7836. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7837. };
  7838. Scene.prototype._renderForCamera = function (camera) {
  7839. var engine = this._engine;
  7840. this.activeCamera = camera;
  7841. if (!this.activeCamera)
  7842. throw new Error("Active camera not set");
  7843. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7844. // Viewport
  7845. engine.setViewport(this.activeCamera.viewport);
  7846. // Camera
  7847. this._renderId++;
  7848. this.updateTransformMatrix();
  7849. if (this.beforeCameraRender) {
  7850. this.beforeCameraRender(this.activeCamera);
  7851. }
  7852. // Meshes
  7853. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7854. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7855. this._evaluateActiveMeshes();
  7856. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7857. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7858. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7859. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7860. skeleton.prepare();
  7861. this._activeBones += skeleton.bones.length;
  7862. }
  7863. // Render targets
  7864. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7865. if (this.renderTargetsEnabled) {
  7866. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7867. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7868. var renderTarget = this._renderTargets.data[renderIndex];
  7869. if (renderTarget._shouldRender()) {
  7870. this._renderId++;
  7871. renderTarget.render();
  7872. }
  7873. }
  7874. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7875. this._renderId++;
  7876. }
  7877. if (this._renderTargets.length > 0) {
  7878. engine.restoreDefaultFramebuffer();
  7879. }
  7880. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7881. // Prepare Frame
  7882. this.postProcessManager._prepareFrame();
  7883. var beforeRenderDate = BABYLON.Tools.Now;
  7884. // Backgrounds
  7885. if (this.layers.length) {
  7886. engine.setDepthBuffer(false);
  7887. var layerIndex;
  7888. var layer;
  7889. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7890. layer = this.layers[layerIndex];
  7891. if (layer.isBackground) {
  7892. layer.render();
  7893. }
  7894. }
  7895. engine.setDepthBuffer(true);
  7896. }
  7897. // Render
  7898. BABYLON.Tools.StartPerformanceCounter("Main render");
  7899. this._renderingManager.render(null, null, true, true);
  7900. BABYLON.Tools.EndPerformanceCounter("Main render");
  7901. // Bounding boxes
  7902. this._boundingBoxRenderer.render();
  7903. // Lens flares
  7904. if (this.lensFlaresEnabled) {
  7905. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7906. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7907. this.lensFlareSystems[lensFlareSystemIndex].render();
  7908. }
  7909. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7910. }
  7911. // Foregrounds
  7912. if (this.layers.length) {
  7913. engine.setDepthBuffer(false);
  7914. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7915. layer = this.layers[layerIndex];
  7916. if (!layer.isBackground) {
  7917. layer.render();
  7918. }
  7919. }
  7920. engine.setDepthBuffer(true);
  7921. }
  7922. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7923. // Finalize frame
  7924. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7925. // Update camera
  7926. this.activeCamera._updateFromScene();
  7927. // Reset some special arrays
  7928. this._renderTargets.reset();
  7929. if (this.afterCameraRender) {
  7930. this.afterCameraRender(this.activeCamera);
  7931. }
  7932. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7933. };
  7934. Scene.prototype._processSubCameras = function (camera) {
  7935. if (camera.subCameras.length === 0) {
  7936. this._renderForCamera(camera);
  7937. return;
  7938. }
  7939. for (var index = 0; index < camera.subCameras.length; index++) {
  7940. this._renderForCamera(camera.subCameras[index]);
  7941. }
  7942. this.activeCamera = camera;
  7943. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7944. // Update camera
  7945. this.activeCamera._updateFromScene();
  7946. };
  7947. Scene.prototype._checkIntersections = function () {
  7948. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7949. var sourceMesh = this._meshesForIntersections.data[index];
  7950. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7951. var action = sourceMesh.actionManager.actions[actionIndex];
  7952. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7953. var otherMesh = action.getTriggerParameter();
  7954. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7955. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7956. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7957. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7958. sourceMesh._intersectionsInProgress.push(otherMesh);
  7959. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7960. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7961. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7962. if (indexOfOther > -1) {
  7963. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7964. }
  7965. }
  7966. }
  7967. }
  7968. }
  7969. };
  7970. Scene.prototype.render = function () {
  7971. var startDate = BABYLON.Tools.Now;
  7972. this._particlesDuration = 0;
  7973. this._spritesDuration = 0;
  7974. this._activeParticles = 0;
  7975. this._renderDuration = 0;
  7976. this._renderTargetsDuration = 0;
  7977. this._evaluateActiveMeshesDuration = 0;
  7978. this._totalVertices = 0;
  7979. this._activeVertices = 0;
  7980. this._activeBones = 0;
  7981. this.getEngine().resetDrawCalls();
  7982. this._meshesForIntersections.reset();
  7983. this.resetCachedMaterial();
  7984. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7985. // Actions
  7986. if (this.actionManager) {
  7987. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7988. }
  7989. // Before render
  7990. if (this.beforeRender) {
  7991. this.beforeRender();
  7992. }
  7993. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7994. this._onBeforeRenderCallbacks[callbackIndex]();
  7995. }
  7996. // Animations
  7997. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  7998. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7999. this._animate();
  8000. // Physics
  8001. if (this._physicsEngine) {
  8002. BABYLON.Tools.StartPerformanceCounter("Physics");
  8003. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8004. BABYLON.Tools.EndPerformanceCounter("Physics");
  8005. }
  8006. // Customs render targets
  8007. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8008. var engine = this.getEngine();
  8009. if (this.renderTargetsEnabled) {
  8010. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8011. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8012. var renderTarget = this.customRenderTargets[customIndex];
  8013. if (renderTarget._shouldRender()) {
  8014. this._renderId++;
  8015. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8016. if (!this.activeCamera)
  8017. throw new Error("Active camera not set");
  8018. // Viewport
  8019. engine.setViewport(this.activeCamera.viewport);
  8020. // Camera
  8021. this.updateTransformMatrix();
  8022. renderTarget.render();
  8023. }
  8024. }
  8025. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8026. this._renderId++;
  8027. }
  8028. if (this.customRenderTargets.length > 0) {
  8029. engine.restoreDefaultFramebuffer();
  8030. }
  8031. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8032. // Procedural textures
  8033. if (this.proceduralTexturesEnabled) {
  8034. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8035. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8036. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8037. if (proceduralTexture._shouldRender()) {
  8038. proceduralTexture.render();
  8039. }
  8040. }
  8041. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8042. }
  8043. // Clear
  8044. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8045. // Shadows
  8046. if (this.shadowsEnabled) {
  8047. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8048. var light = this.lights[lightIndex];
  8049. var shadowGenerator = light.getShadowGenerator();
  8050. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8051. this._renderTargets.push(shadowGenerator.getShadowMap());
  8052. }
  8053. }
  8054. }
  8055. // RenderPipeline
  8056. this.postProcessRenderPipelineManager.update();
  8057. // Multi-cameras?
  8058. if (this.activeCameras.length > 0) {
  8059. var currentRenderId = this._renderId;
  8060. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8061. this._renderId = currentRenderId;
  8062. this._processSubCameras(this.activeCameras[cameraIndex]);
  8063. }
  8064. } else {
  8065. if (!this.activeCamera) {
  8066. throw new Error("No camera defined");
  8067. }
  8068. this._processSubCameras(this.activeCamera);
  8069. }
  8070. // Intersection checks
  8071. this._checkIntersections();
  8072. // Update the audio listener attached to the camera
  8073. this._updateAudioParameters();
  8074. // After render
  8075. if (this.afterRender) {
  8076. this.afterRender();
  8077. }
  8078. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8079. this._onAfterRenderCallbacks[callbackIndex]();
  8080. }
  8081. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8082. this._toBeDisposed.data[index].dispose();
  8083. this._toBeDisposed[index] = null;
  8084. }
  8085. this._toBeDisposed.reset();
  8086. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8087. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8088. };
  8089. Scene.prototype._updateAudioParameters = function () {
  8090. var listeningCamera;
  8091. var audioEngine = this._engine.getAudioEngine();
  8092. if (this.activeCameras.length > 0) {
  8093. listeningCamera = this.activeCameras[0];
  8094. } else {
  8095. listeningCamera = this.activeCamera;
  8096. }
  8097. if (listeningCamera && audioEngine.canUseWebAudio) {
  8098. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8099. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8100. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8101. cameraDirection.normalize();
  8102. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8103. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8104. var sound = this.mainSoundTrack.soundCollection[i];
  8105. if (sound.useCustomAttenuation) {
  8106. sound.updateDistanceFromListener();
  8107. }
  8108. }
  8109. for (var i = 0; i < this.soundTracks.length; i++) {
  8110. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8111. var sound = this.soundTracks[i].soundCollection[j];
  8112. if (sound.useCustomAttenuation) {
  8113. sound.updateDistanceFromListener();
  8114. }
  8115. }
  8116. }
  8117. }
  8118. };
  8119. Scene.prototype.dispose = function () {
  8120. this.beforeRender = null;
  8121. this.afterRender = null;
  8122. this.skeletons = [];
  8123. this._boundingBoxRenderer.dispose();
  8124. // Debug layer
  8125. this.debugLayer.hide();
  8126. // Events
  8127. if (this.onDispose) {
  8128. this.onDispose();
  8129. }
  8130. this._onBeforeRenderCallbacks = [];
  8131. this._onAfterRenderCallbacks = [];
  8132. this.detachControl();
  8133. // Detach cameras
  8134. var canvas = this._engine.getRenderingCanvas();
  8135. var index;
  8136. for (index = 0; index < this.cameras.length; index++) {
  8137. this.cameras[index].detachControl(canvas);
  8138. }
  8139. while (this.lights.length) {
  8140. this.lights[0].dispose();
  8141. }
  8142. while (this.meshes.length) {
  8143. this.meshes[0].dispose(true);
  8144. }
  8145. while (this.cameras.length) {
  8146. this.cameras[0].dispose();
  8147. }
  8148. while (this.materials.length) {
  8149. this.materials[0].dispose();
  8150. }
  8151. while (this.particleSystems.length) {
  8152. this.particleSystems[0].dispose();
  8153. }
  8154. while (this.spriteManagers.length) {
  8155. this.spriteManagers[0].dispose();
  8156. }
  8157. while (this.layers.length) {
  8158. this.layers[0].dispose();
  8159. }
  8160. while (this.textures.length) {
  8161. this.textures[0].dispose();
  8162. }
  8163. // Post-processes
  8164. this.postProcessManager.dispose();
  8165. // Physics
  8166. if (this._physicsEngine) {
  8167. this.disablePhysicsEngine();
  8168. }
  8169. // Remove from engine
  8170. index = this._engine.scenes.indexOf(this);
  8171. if (index > -1) {
  8172. this._engine.scenes.splice(index, 1);
  8173. }
  8174. this._engine.wipeCaches();
  8175. };
  8176. // Collisions
  8177. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8178. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8179. position.divideToRef(collider.radius, this._scaledPosition);
  8180. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8181. collider.retry = 0;
  8182. collider.initialVelocity = this._scaledVelocity;
  8183. collider.initialPosition = this._scaledPosition;
  8184. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8185. finalPosition.multiplyInPlace(collider.radius);
  8186. };
  8187. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8188. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8189. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8190. if (collider.retry >= maximumRetry) {
  8191. finalPosition.copyFrom(position);
  8192. return;
  8193. }
  8194. collider._initialize(position, velocity, closeDistance);
  8195. for (var index = 0; index < this.meshes.length; index++) {
  8196. var mesh = this.meshes[index];
  8197. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8198. mesh._checkCollision(collider);
  8199. }
  8200. }
  8201. if (!collider.collisionFound) {
  8202. position.addToRef(velocity, finalPosition);
  8203. return;
  8204. }
  8205. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8206. collider._getResponse(position, velocity);
  8207. }
  8208. if (velocity.length() <= closeDistance) {
  8209. finalPosition.copyFrom(position);
  8210. return;
  8211. }
  8212. collider.retry++;
  8213. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8214. };
  8215. // Octrees
  8216. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8217. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8218. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8219. if (!this._selectionOctree) {
  8220. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8221. }
  8222. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8223. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8224. for (var index = 0; index < this.meshes.length; index++) {
  8225. var mesh = this.meshes[index];
  8226. mesh.computeWorldMatrix(true);
  8227. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8228. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8229. BABYLON.Tools.CheckExtends(minBox, min, max);
  8230. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8231. }
  8232. // Update octree
  8233. this._selectionOctree.update(min, max, this.meshes);
  8234. return this._selectionOctree;
  8235. };
  8236. // Picking
  8237. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8238. var engine = this._engine;
  8239. if (!camera) {
  8240. if (!this.activeCamera)
  8241. throw new Error("Active camera not set");
  8242. camera = this.activeCamera;
  8243. }
  8244. var cameraViewport = camera.viewport;
  8245. var viewport = cameraViewport.toGlobal(engine);
  8246. // Moving coordinates to local viewport world
  8247. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8248. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8249. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8250. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8251. };
  8252. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8253. var pickingInfo = null;
  8254. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8255. var mesh = this.meshes[meshIndex];
  8256. if (predicate) {
  8257. if (!predicate(mesh)) {
  8258. continue;
  8259. }
  8260. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8261. continue;
  8262. }
  8263. var world = mesh.getWorldMatrix();
  8264. var ray = rayFunction(world);
  8265. var result = mesh.intersects(ray, fastCheck);
  8266. if (!result || !result.hit)
  8267. continue;
  8268. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8269. continue;
  8270. pickingInfo = result;
  8271. if (fastCheck) {
  8272. break;
  8273. }
  8274. }
  8275. return pickingInfo || new BABYLON.PickingInfo();
  8276. };
  8277. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8278. var _this = this;
  8279. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8280. /// <param name="x">X position on screen</param>
  8281. /// <param name="y">Y position on screen</param>
  8282. /// <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>
  8283. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8284. /// <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>
  8285. return this._internalPick(function (world) {
  8286. return _this.createPickingRay(x, y, world, camera);
  8287. }, predicate, fastCheck);
  8288. };
  8289. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8290. var _this = this;
  8291. return this._internalPick(function (world) {
  8292. if (!_this._pickWithRayInverseMatrix) {
  8293. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8294. }
  8295. world.invertToRef(_this._pickWithRayInverseMatrix);
  8296. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8297. }, predicate, fastCheck);
  8298. };
  8299. Scene.prototype.setPointerOverMesh = function (mesh) {
  8300. if (this._pointerOverMesh === mesh) {
  8301. return;
  8302. }
  8303. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8304. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8305. }
  8306. this._pointerOverMesh = mesh;
  8307. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8308. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8309. }
  8310. };
  8311. Scene.prototype.getPointerOverMesh = function () {
  8312. return this._pointerOverMesh;
  8313. };
  8314. // Physics
  8315. Scene.prototype.getPhysicsEngine = function () {
  8316. return this._physicsEngine;
  8317. };
  8318. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8319. if (this._physicsEngine) {
  8320. return true;
  8321. }
  8322. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8323. if (!this._physicsEngine.isSupported()) {
  8324. this._physicsEngine = null;
  8325. return false;
  8326. }
  8327. this._physicsEngine._initialize(gravity);
  8328. return true;
  8329. };
  8330. Scene.prototype.disablePhysicsEngine = function () {
  8331. if (!this._physicsEngine) {
  8332. return;
  8333. }
  8334. this._physicsEngine.dispose();
  8335. this._physicsEngine = undefined;
  8336. };
  8337. Scene.prototype.isPhysicsEnabled = function () {
  8338. return this._physicsEngine !== undefined;
  8339. };
  8340. Scene.prototype.setGravity = function (gravity) {
  8341. if (!this._physicsEngine) {
  8342. return;
  8343. }
  8344. this._physicsEngine._setGravity(gravity);
  8345. };
  8346. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8347. if (parts.parts) {
  8348. options = parts;
  8349. parts = parts.parts;
  8350. }
  8351. if (!this._physicsEngine) {
  8352. return null;
  8353. }
  8354. for (var index = 0; index < parts.length; index++) {
  8355. var mesh = parts[index].mesh;
  8356. mesh._physicImpostor = parts[index].impostor;
  8357. mesh._physicsMass = options.mass / parts.length;
  8358. mesh._physicsFriction = options.friction;
  8359. mesh._physicRestitution = options.restitution;
  8360. }
  8361. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8362. };
  8363. //ANY
  8364. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8365. for (var index = 0; index < compound.parts.length; index++) {
  8366. var mesh = compound.parts[index].mesh;
  8367. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8368. this._physicsEngine._unregisterMesh(mesh);
  8369. }
  8370. };
  8371. // Tags
  8372. Scene.prototype._getByTags = function (list, tagsQuery) {
  8373. if (tagsQuery === undefined) {
  8374. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8375. return list;
  8376. }
  8377. var listByTags = [];
  8378. for (var i in list) {
  8379. var item = list[i];
  8380. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8381. listByTags.push(item);
  8382. }
  8383. }
  8384. return listByTags;
  8385. };
  8386. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8387. return this._getByTags(this.meshes, tagsQuery);
  8388. };
  8389. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8390. return this._getByTags(this.cameras, tagsQuery);
  8391. };
  8392. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8393. return this._getByTags(this.lights, tagsQuery);
  8394. };
  8395. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8396. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8397. };
  8398. Scene.FOGMODE_NONE = 0;
  8399. Scene.FOGMODE_EXP = 1;
  8400. Scene.FOGMODE_EXP2 = 2;
  8401. Scene.FOGMODE_LINEAR = 3;
  8402. Scene.MinDeltaTime = 1.0;
  8403. Scene.MaxDeltaTime = 1000.0;
  8404. return Scene;
  8405. })();
  8406. BABYLON.Scene = Scene;
  8407. })(BABYLON || (BABYLON = {}));
  8408. //# sourceMappingURL=babylon.scene.js.map
  8409. var BABYLON;
  8410. (function (BABYLON) {
  8411. var VertexBuffer = (function () {
  8412. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8413. if (engine instanceof BABYLON.Mesh) {
  8414. this._engine = engine.getScene().getEngine();
  8415. } else {
  8416. this._engine = engine;
  8417. }
  8418. this._updatable = updatable;
  8419. this._data = data;
  8420. if (!postponeInternalCreation) {
  8421. this.create();
  8422. }
  8423. this._kind = kind;
  8424. if (stride) {
  8425. this._strideSize = stride;
  8426. return;
  8427. }
  8428. switch (kind) {
  8429. case VertexBuffer.PositionKind:
  8430. this._strideSize = 3;
  8431. break;
  8432. case VertexBuffer.NormalKind:
  8433. this._strideSize = 3;
  8434. break;
  8435. case VertexBuffer.UVKind:
  8436. this._strideSize = 2;
  8437. break;
  8438. case VertexBuffer.UV2Kind:
  8439. this._strideSize = 2;
  8440. break;
  8441. case VertexBuffer.ColorKind:
  8442. this._strideSize = 4;
  8443. break;
  8444. case VertexBuffer.MatricesIndicesKind:
  8445. this._strideSize = 4;
  8446. break;
  8447. case VertexBuffer.MatricesWeightsKind:
  8448. this._strideSize = 4;
  8449. break;
  8450. }
  8451. }
  8452. // Properties
  8453. VertexBuffer.prototype.isUpdatable = function () {
  8454. return this._updatable;
  8455. };
  8456. VertexBuffer.prototype.getData = function () {
  8457. return this._data;
  8458. };
  8459. VertexBuffer.prototype.getBuffer = function () {
  8460. return this._buffer;
  8461. };
  8462. VertexBuffer.prototype.getStrideSize = function () {
  8463. return this._strideSize;
  8464. };
  8465. // Methods
  8466. VertexBuffer.prototype.create = function (data) {
  8467. if (!data && this._buffer) {
  8468. return;
  8469. }
  8470. data = data || this._data;
  8471. if (!this._buffer) {
  8472. if (this._updatable) {
  8473. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8474. } else {
  8475. this._buffer = this._engine.createVertexBuffer(data);
  8476. }
  8477. }
  8478. if (this._updatable) {
  8479. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8480. this._data = data;
  8481. }
  8482. };
  8483. VertexBuffer.prototype.update = function (data) {
  8484. this.create(data);
  8485. };
  8486. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8487. if (!this._buffer) {
  8488. return;
  8489. }
  8490. if (this._updatable) {
  8491. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8492. this._data = null;
  8493. }
  8494. };
  8495. VertexBuffer.prototype.dispose = function () {
  8496. if (!this._buffer) {
  8497. return;
  8498. }
  8499. if (this._engine._releaseBuffer(this._buffer)) {
  8500. this._buffer = null;
  8501. }
  8502. };
  8503. Object.defineProperty(VertexBuffer, "PositionKind", {
  8504. get: function () {
  8505. return VertexBuffer._PositionKind;
  8506. },
  8507. enumerable: true,
  8508. configurable: true
  8509. });
  8510. Object.defineProperty(VertexBuffer, "NormalKind", {
  8511. get: function () {
  8512. return VertexBuffer._NormalKind;
  8513. },
  8514. enumerable: true,
  8515. configurable: true
  8516. });
  8517. Object.defineProperty(VertexBuffer, "UVKind", {
  8518. get: function () {
  8519. return VertexBuffer._UVKind;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8525. get: function () {
  8526. return VertexBuffer._UV2Kind;
  8527. },
  8528. enumerable: true,
  8529. configurable: true
  8530. });
  8531. Object.defineProperty(VertexBuffer, "ColorKind", {
  8532. get: function () {
  8533. return VertexBuffer._ColorKind;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8539. get: function () {
  8540. return VertexBuffer._MatricesIndicesKind;
  8541. },
  8542. enumerable: true,
  8543. configurable: true
  8544. });
  8545. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8546. get: function () {
  8547. return VertexBuffer._MatricesWeightsKind;
  8548. },
  8549. enumerable: true,
  8550. configurable: true
  8551. });
  8552. VertexBuffer._PositionKind = "position";
  8553. VertexBuffer._NormalKind = "normal";
  8554. VertexBuffer._UVKind = "uv";
  8555. VertexBuffer._UV2Kind = "uv2";
  8556. VertexBuffer._ColorKind = "color";
  8557. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8558. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8559. return VertexBuffer;
  8560. })();
  8561. BABYLON.VertexBuffer = VertexBuffer;
  8562. })(BABYLON || (BABYLON = {}));
  8563. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8564. var BABYLON;
  8565. (function (BABYLON) {
  8566. var AbstractMesh = (function (_super) {
  8567. __extends(AbstractMesh, _super);
  8568. function AbstractMesh(name, scene) {
  8569. _super.call(this, name, scene);
  8570. // Properties
  8571. this.position = new BABYLON.Vector3(0, 0, 0);
  8572. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8573. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8574. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8575. this.visibility = 1.0;
  8576. this.alphaIndex = Number.MAX_VALUE;
  8577. this.infiniteDistance = false;
  8578. this.isVisible = true;
  8579. this.isPickable = true;
  8580. this.showBoundingBox = false;
  8581. this.showSubMeshesBoundingBox = false;
  8582. this.onDispose = null;
  8583. this.checkCollisions = false;
  8584. this.isBlocker = false;
  8585. this.renderingGroupId = 0;
  8586. this.receiveShadows = false;
  8587. this.renderOutline = false;
  8588. this.outlineColor = BABYLON.Color3.Red();
  8589. this.outlineWidth = 0.02;
  8590. this.renderOverlay = false;
  8591. this.overlayColor = BABYLON.Color3.Red();
  8592. this.overlayAlpha = 0.5;
  8593. this.hasVertexAlpha = false;
  8594. this.useVertexColors = true;
  8595. this.applyFog = true;
  8596. this.useOctreeForRenderingSelection = true;
  8597. this.useOctreeForPicking = true;
  8598. this.useOctreeForCollisions = true;
  8599. this.layerMask = 0xFFFFFFFF;
  8600. // Physics
  8601. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8602. // Collisions
  8603. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8604. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8605. this._collider = new BABYLON.Collider();
  8606. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8607. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8608. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8609. // Cache
  8610. this._localScaling = BABYLON.Matrix.Zero();
  8611. this._localRotation = BABYLON.Matrix.Zero();
  8612. this._localTranslation = BABYLON.Matrix.Zero();
  8613. this._localBillboard = BABYLON.Matrix.Zero();
  8614. this._localPivotScaling = BABYLON.Matrix.Zero();
  8615. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8616. this._localWorld = BABYLON.Matrix.Zero();
  8617. this._worldMatrix = BABYLON.Matrix.Zero();
  8618. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8619. this._absolutePosition = BABYLON.Vector3.Zero();
  8620. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8621. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8622. this._isDirty = false;
  8623. this._pivotMatrix = BABYLON.Matrix.Identity();
  8624. this._isDisposed = false;
  8625. this._renderId = 0;
  8626. this._intersectionsInProgress = new Array();
  8627. this._onAfterWorldMatrixUpdate = new Array();
  8628. scene.meshes.push(this);
  8629. }
  8630. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8631. get: function () {
  8632. return AbstractMesh._BILLBOARDMODE_NONE;
  8633. },
  8634. enumerable: true,
  8635. configurable: true
  8636. });
  8637. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8638. get: function () {
  8639. return AbstractMesh._BILLBOARDMODE_X;
  8640. },
  8641. enumerable: true,
  8642. configurable: true
  8643. });
  8644. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8645. get: function () {
  8646. return AbstractMesh._BILLBOARDMODE_Y;
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8652. get: function () {
  8653. return AbstractMesh._BILLBOARDMODE_Z;
  8654. },
  8655. enumerable: true,
  8656. configurable: true
  8657. });
  8658. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8659. get: function () {
  8660. return AbstractMesh._BILLBOARDMODE_ALL;
  8661. },
  8662. enumerable: true,
  8663. configurable: true
  8664. });
  8665. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8666. // Methods
  8667. get: function () {
  8668. return false;
  8669. },
  8670. enumerable: true,
  8671. configurable: true
  8672. });
  8673. AbstractMesh.prototype.getLOD = function (camera) {
  8674. return this;
  8675. };
  8676. AbstractMesh.prototype.getTotalVertices = function () {
  8677. return 0;
  8678. };
  8679. AbstractMesh.prototype.getIndices = function () {
  8680. return null;
  8681. };
  8682. AbstractMesh.prototype.getVerticesData = function (kind) {
  8683. return null;
  8684. };
  8685. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8686. return false;
  8687. };
  8688. AbstractMesh.prototype.getBoundingInfo = function () {
  8689. if (this._masterMesh) {
  8690. return this._masterMesh.getBoundingInfo();
  8691. }
  8692. if (!this._boundingInfo) {
  8693. this._updateBoundingInfo();
  8694. }
  8695. return this._boundingInfo;
  8696. };
  8697. AbstractMesh.prototype._preActivate = function () {
  8698. };
  8699. AbstractMesh.prototype._activate = function (renderId) {
  8700. this._renderId = renderId;
  8701. };
  8702. AbstractMesh.prototype.getWorldMatrix = function () {
  8703. if (this._masterMesh) {
  8704. return this._masterMesh.getWorldMatrix();
  8705. }
  8706. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8707. this.computeWorldMatrix();
  8708. }
  8709. return this._worldMatrix;
  8710. };
  8711. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8712. get: function () {
  8713. return this._worldMatrix;
  8714. },
  8715. enumerable: true,
  8716. configurable: true
  8717. });
  8718. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8719. get: function () {
  8720. return this._absolutePosition;
  8721. },
  8722. enumerable: true,
  8723. configurable: true
  8724. });
  8725. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8726. if (!this.rotationQuaternion) {
  8727. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8728. this.rotation = BABYLON.Vector3.Zero();
  8729. }
  8730. if (!space || space == 0 /* LOCAL */) {
  8731. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8732. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8733. } else {
  8734. if (this.parent) {
  8735. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8736. invertParentWorldMatrix.invert();
  8737. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8738. }
  8739. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8740. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8741. }
  8742. };
  8743. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8744. var displacementVector = axis.scale(distance);
  8745. if (!space || space == 0 /* LOCAL */) {
  8746. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8747. this.setPositionWithLocalVector(tempV3);
  8748. } else {
  8749. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8750. }
  8751. };
  8752. AbstractMesh.prototype.getAbsolutePosition = function () {
  8753. this.computeWorldMatrix();
  8754. return this._absolutePosition;
  8755. };
  8756. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8757. if (!absolutePosition) {
  8758. return;
  8759. }
  8760. var absolutePositionX;
  8761. var absolutePositionY;
  8762. var absolutePositionZ;
  8763. if (absolutePosition.x === undefined) {
  8764. if (arguments.length < 3) {
  8765. return;
  8766. }
  8767. absolutePositionX = arguments[0];
  8768. absolutePositionY = arguments[1];
  8769. absolutePositionZ = arguments[2];
  8770. } else {
  8771. absolutePositionX = absolutePosition.x;
  8772. absolutePositionY = absolutePosition.y;
  8773. absolutePositionZ = absolutePosition.z;
  8774. }
  8775. if (this.parent) {
  8776. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8777. invertParentWorldMatrix.invert();
  8778. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8779. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8780. } else {
  8781. this.position.x = absolutePositionX;
  8782. this.position.y = absolutePositionY;
  8783. this.position.z = absolutePositionZ;
  8784. }
  8785. };
  8786. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8787. this._pivotMatrix = matrix;
  8788. this._cache.pivotMatrixUpdated = true;
  8789. };
  8790. AbstractMesh.prototype.getPivotMatrix = function () {
  8791. return this._pivotMatrix;
  8792. };
  8793. AbstractMesh.prototype._isSynchronized = function () {
  8794. if (this._isDirty) {
  8795. return false;
  8796. }
  8797. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8798. return false;
  8799. if (this._cache.pivotMatrixUpdated) {
  8800. return false;
  8801. }
  8802. if (this.infiniteDistance) {
  8803. return false;
  8804. }
  8805. if (!this._cache.position.equals(this.position))
  8806. return false;
  8807. if (this.rotationQuaternion) {
  8808. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8809. return false;
  8810. } else {
  8811. if (!this._cache.rotation.equals(this.rotation))
  8812. return false;
  8813. }
  8814. if (!this._cache.scaling.equals(this.scaling))
  8815. return false;
  8816. return true;
  8817. };
  8818. AbstractMesh.prototype._initCache = function () {
  8819. _super.prototype._initCache.call(this);
  8820. this._cache.localMatrixUpdated = false;
  8821. this._cache.position = BABYLON.Vector3.Zero();
  8822. this._cache.scaling = BABYLON.Vector3.Zero();
  8823. this._cache.rotation = BABYLON.Vector3.Zero();
  8824. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8825. };
  8826. AbstractMesh.prototype.markAsDirty = function (property) {
  8827. if (property === "rotation") {
  8828. this.rotationQuaternion = null;
  8829. }
  8830. this._currentRenderId = Number.MAX_VALUE;
  8831. this._isDirty = true;
  8832. };
  8833. AbstractMesh.prototype._updateBoundingInfo = function () {
  8834. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8835. this._boundingInfo._update(this.worldMatrixFromCache);
  8836. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8837. };
  8838. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8839. if (!this.subMeshes) {
  8840. return;
  8841. }
  8842. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8843. var subMesh = this.subMeshes[subIndex];
  8844. subMesh.updateBoundingInfo(matrix);
  8845. }
  8846. };
  8847. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8848. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8849. return this._worldMatrix;
  8850. }
  8851. this._cache.position.copyFrom(this.position);
  8852. this._cache.scaling.copyFrom(this.scaling);
  8853. this._cache.pivotMatrixUpdated = false;
  8854. this._currentRenderId = this.getScene().getRenderId();
  8855. this._isDirty = false;
  8856. // Scaling
  8857. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8858. // Rotation
  8859. if (this.rotationQuaternion) {
  8860. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8861. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8862. } else {
  8863. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8864. this._cache.rotation.copyFrom(this.rotation);
  8865. }
  8866. // Translation
  8867. if (this.infiniteDistance && !this.parent) {
  8868. var camera = this.getScene().activeCamera;
  8869. var cameraWorldMatrix = camera.getWorldMatrix();
  8870. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8871. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8872. } else {
  8873. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8874. }
  8875. // Composing transformations
  8876. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8877. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8878. // Billboarding
  8879. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8880. var localPosition = this.position.clone();
  8881. var zero = this.getScene().activeCamera.position.clone();
  8882. if (this.parent && this.parent.position) {
  8883. localPosition.addInPlace(this.parent.position);
  8884. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8885. }
  8886. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8887. zero = this.getScene().activeCamera.position;
  8888. } else {
  8889. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8890. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8891. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8892. zero.y = localPosition.y + 0.001;
  8893. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8894. zero.z = localPosition.z + 0.001;
  8895. }
  8896. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8897. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8898. this._localBillboard.invert();
  8899. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8900. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8901. }
  8902. // Local world
  8903. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8904. // Parent
  8905. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8906. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8907. } else {
  8908. this._worldMatrix.copyFrom(this._localWorld);
  8909. }
  8910. // Bounding info
  8911. this._updateBoundingInfo();
  8912. // Absolute position
  8913. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8914. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8915. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8916. }
  8917. return this._worldMatrix;
  8918. };
  8919. /**
  8920. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8921. * @param func: callback function to add
  8922. */
  8923. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8924. this._onAfterWorldMatrixUpdate.push(func);
  8925. };
  8926. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8927. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8928. if (index > -1) {
  8929. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8930. }
  8931. };
  8932. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8933. this.computeWorldMatrix();
  8934. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8935. };
  8936. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8937. this.computeWorldMatrix();
  8938. var invLocalWorldMatrix = this._localWorld.clone();
  8939. invLocalWorldMatrix.invert();
  8940. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8941. };
  8942. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8943. this.computeWorldMatrix();
  8944. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8945. };
  8946. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8947. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8948. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  8949. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8950. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8951. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8952. /// <returns>Mesh oriented towards targetMesh</returns>
  8953. yawCor = yawCor || 0; // default to zero if undefined
  8954. pitchCor = pitchCor || 0;
  8955. rollCor = rollCor || 0;
  8956. var dv = targetPoint.subtract(this.position);
  8957. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8958. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8959. var pitch = Math.atan2(dv.y, len);
  8960. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8961. };
  8962. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8963. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8964. return false;
  8965. }
  8966. return true;
  8967. };
  8968. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8969. if (!camera) {
  8970. camera = this.getScene().activeCamera;
  8971. }
  8972. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8973. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8974. return false;
  8975. }
  8976. return true;
  8977. };
  8978. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8979. if (!this._boundingInfo || !mesh._boundingInfo) {
  8980. return false;
  8981. }
  8982. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8983. };
  8984. AbstractMesh.prototype.intersectsPoint = function (point) {
  8985. if (!this._boundingInfo) {
  8986. return false;
  8987. }
  8988. return this._boundingInfo.intersectsPoint(point);
  8989. };
  8990. // Physics
  8991. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8992. var physicsEngine = this.getScene().getPhysicsEngine();
  8993. if (!physicsEngine) {
  8994. return;
  8995. }
  8996. if (impostor.impostor) {
  8997. // Old API
  8998. options = impostor;
  8999. impostor = impostor.impostor;
  9000. }
  9001. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9002. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9003. physicsEngine._unregisterMesh(this);
  9004. return;
  9005. }
  9006. options.mass = options.mass || 0;
  9007. options.friction = options.friction || 0.2;
  9008. options.restitution = options.restitution || 0.2;
  9009. this._physicImpostor = impostor;
  9010. this._physicsMass = options.mass;
  9011. this._physicsFriction = options.friction;
  9012. this._physicRestitution = options.restitution;
  9013. return physicsEngine._registerMesh(this, impostor, options);
  9014. };
  9015. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9016. if (!this._physicImpostor) {
  9017. return BABYLON.PhysicsEngine.NoImpostor;
  9018. }
  9019. return this._physicImpostor;
  9020. };
  9021. AbstractMesh.prototype.getPhysicsMass = function () {
  9022. if (!this._physicsMass) {
  9023. return 0;
  9024. }
  9025. return this._physicsMass;
  9026. };
  9027. AbstractMesh.prototype.getPhysicsFriction = function () {
  9028. if (!this._physicsFriction) {
  9029. return 0;
  9030. }
  9031. return this._physicsFriction;
  9032. };
  9033. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9034. if (!this._physicRestitution) {
  9035. return 0;
  9036. }
  9037. return this._physicRestitution;
  9038. };
  9039. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9040. if (!camera) {
  9041. camera = this.getScene().activeCamera;
  9042. }
  9043. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9044. };
  9045. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9046. if (!camera) {
  9047. camera = this.getScene().activeCamera;
  9048. }
  9049. return this.absolutePosition.subtract(camera.position).length();
  9050. };
  9051. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9052. if (!this._physicImpostor) {
  9053. return;
  9054. }
  9055. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9056. };
  9057. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9058. if (!this._physicImpostor) {
  9059. return;
  9060. }
  9061. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9062. };
  9063. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9064. if (!this._physicImpostor) {
  9065. return;
  9066. }
  9067. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9068. };
  9069. // Collisions
  9070. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9071. var globalPosition = this.getAbsolutePosition();
  9072. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9073. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9074. this._collider.radius = this.ellipsoid;
  9075. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9076. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9077. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9078. this.position.addInPlace(this._diffPositionForCollisions);
  9079. }
  9080. };
  9081. // Submeshes octree
  9082. /**
  9083. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9084. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9085. */
  9086. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9087. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  9088. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  9089. if (!this._submeshesOctree) {
  9090. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9091. }
  9092. this.computeWorldMatrix(true);
  9093. // Update octree
  9094. var bbox = this.getBoundingInfo().boundingBox;
  9095. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9096. return this._submeshesOctree;
  9097. };
  9098. // Collisions
  9099. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9100. this._generatePointsArray();
  9101. // Transformation
  9102. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9103. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9104. subMesh._lastColliderWorldVertices = [];
  9105. subMesh._trianglePlanes = [];
  9106. var start = subMesh.verticesStart;
  9107. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9108. for (var i = start; i < end; i++) {
  9109. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9110. }
  9111. }
  9112. // Collide
  9113. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9114. };
  9115. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9116. var subMeshes;
  9117. var len;
  9118. // Octrees
  9119. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9120. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9121. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9122. len = intersections.length;
  9123. subMeshes = intersections.data;
  9124. } else {
  9125. subMeshes = this.subMeshes;
  9126. len = subMeshes.length;
  9127. }
  9128. for (var index = 0; index < len; index++) {
  9129. var subMesh = subMeshes[index];
  9130. // Bounding test
  9131. if (len > 1 && !subMesh._checkCollision(collider))
  9132. continue;
  9133. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9134. }
  9135. };
  9136. AbstractMesh.prototype._checkCollision = function (collider) {
  9137. // Bounding box test
  9138. if (!this._boundingInfo._checkCollision(collider))
  9139. return;
  9140. // Transformation matrix
  9141. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9142. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9143. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9144. };
  9145. // Picking
  9146. AbstractMesh.prototype._generatePointsArray = function () {
  9147. return false;
  9148. };
  9149. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9150. var pickingInfo = new BABYLON.PickingInfo();
  9151. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9152. return pickingInfo;
  9153. }
  9154. if (!this._generatePointsArray()) {
  9155. return pickingInfo;
  9156. }
  9157. var intersectInfo = null;
  9158. // Octrees
  9159. var subMeshes;
  9160. var len;
  9161. if (this._submeshesOctree && this.useOctreeForPicking) {
  9162. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9163. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9164. len = intersections.length;
  9165. subMeshes = intersections.data;
  9166. } else {
  9167. subMeshes = this.subMeshes;
  9168. len = subMeshes.length;
  9169. }
  9170. for (var index = 0; index < len; index++) {
  9171. var subMesh = subMeshes[index];
  9172. // Bounding test
  9173. if (len > 1 && !subMesh.canIntersects(ray))
  9174. continue;
  9175. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9176. if (currentIntersectInfo) {
  9177. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9178. intersectInfo = currentIntersectInfo;
  9179. if (fastCheck) {
  9180. break;
  9181. }
  9182. }
  9183. }
  9184. }
  9185. if (intersectInfo) {
  9186. // Get picked point
  9187. var world = this.getWorldMatrix();
  9188. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9189. var direction = ray.direction.clone();
  9190. direction.normalize();
  9191. direction = direction.scale(intersectInfo.distance);
  9192. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9193. var pickedPoint = worldOrigin.add(worldDirection);
  9194. // Return result
  9195. pickingInfo.hit = true;
  9196. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9197. pickingInfo.pickedPoint = pickedPoint;
  9198. pickingInfo.pickedMesh = this;
  9199. pickingInfo.bu = intersectInfo.bu;
  9200. pickingInfo.bv = intersectInfo.bv;
  9201. pickingInfo.faceId = intersectInfo.faceId;
  9202. return pickingInfo;
  9203. }
  9204. return pickingInfo;
  9205. };
  9206. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9207. return null;
  9208. };
  9209. AbstractMesh.prototype.releaseSubMeshes = function () {
  9210. if (this.subMeshes) {
  9211. while (this.subMeshes.length) {
  9212. this.subMeshes[0].dispose();
  9213. }
  9214. } else {
  9215. this.subMeshes = new Array();
  9216. }
  9217. };
  9218. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9219. // Physics
  9220. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9221. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9222. }
  9223. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9224. var other = this._intersectionsInProgress[index];
  9225. var pos = other._intersectionsInProgress.indexOf(this);
  9226. other._intersectionsInProgress.splice(pos, 1);
  9227. }
  9228. this._intersectionsInProgress = [];
  9229. // SubMeshes
  9230. this.releaseSubMeshes();
  9231. // Remove from scene
  9232. var index = this.getScene().meshes.indexOf(this);
  9233. if (index != -1) {
  9234. // Remove from the scene if mesh found
  9235. this.getScene().meshes.splice(index, 1);
  9236. }
  9237. if (!doNotRecurse) {
  9238. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9239. if (this.getScene().particleSystems[index].emitter == this) {
  9240. this.getScene().particleSystems[index].dispose();
  9241. index--;
  9242. }
  9243. }
  9244. // Children
  9245. var objects = this.getScene().meshes.slice(0);
  9246. for (index = 0; index < objects.length; index++) {
  9247. if (objects[index].parent == this) {
  9248. objects[index].dispose();
  9249. }
  9250. }
  9251. } else {
  9252. for (index = 0; index < this.getScene().meshes.length; index++) {
  9253. var obj = this.getScene().meshes[index];
  9254. if (obj.parent === this) {
  9255. obj.parent = null;
  9256. obj.computeWorldMatrix(true);
  9257. }
  9258. }
  9259. }
  9260. this._onAfterWorldMatrixUpdate = [];
  9261. this._isDisposed = true;
  9262. // Callback
  9263. if (this.onDispose) {
  9264. this.onDispose();
  9265. }
  9266. };
  9267. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9268. AbstractMesh._BILLBOARDMODE_X = 1;
  9269. AbstractMesh._BILLBOARDMODE_Y = 2;
  9270. AbstractMesh._BILLBOARDMODE_Z = 4;
  9271. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9272. return AbstractMesh;
  9273. })(BABYLON.Node);
  9274. BABYLON.AbstractMesh = AbstractMesh;
  9275. })(BABYLON || (BABYLON = {}));
  9276. //# sourceMappingURL=babylon.abstractMesh.js.map
  9277. var BABYLON;
  9278. (function (BABYLON) {
  9279. var _InstancesBatch = (function () {
  9280. function _InstancesBatch() {
  9281. this.mustReturn = false;
  9282. this.visibleInstances = new Array();
  9283. this.renderSelf = new Array();
  9284. }
  9285. return _InstancesBatch;
  9286. })();
  9287. BABYLON._InstancesBatch = _InstancesBatch;
  9288. var Mesh = (function (_super) {
  9289. __extends(Mesh, _super);
  9290. /**
  9291. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9292. * @param {BABYLON.Scene} scene - The scene to add this mesh to.
  9293. * @param {BABYLON.Node} parent - The parent of this mesh, if it has one
  9294. * @param {BABYLON.Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9295. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9296. * When false, achieved by calling a clone(), also passing False.
  9297. * This will make creation of children, recursive.
  9298. */
  9299. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9300. if (typeof parent === "undefined") { parent = null; }
  9301. _super.call(this, name, scene);
  9302. // Members
  9303. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9304. this.instances = new Array();
  9305. this._LODLevels = new Array();
  9306. this._onBeforeRenderCallbacks = new Array();
  9307. this._onAfterRenderCallbacks = new Array();
  9308. this._visibleInstances = {};
  9309. this._renderIdForInstances = new Array();
  9310. this._batchCache = new _InstancesBatch();
  9311. this._instancesBufferSize = 32 * 16 * 4;
  9312. if (source) {
  9313. // Geometry
  9314. if (source._geometry) {
  9315. source._geometry.applyToMesh(this);
  9316. }
  9317. // Deep copy
  9318. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9319. // Material
  9320. this.material = source.material;
  9321. if (!doNotCloneChildren) {
  9322. for (var index = 0; index < scene.meshes.length; index++) {
  9323. var mesh = scene.meshes[index];
  9324. if (mesh.parent === source) {
  9325. // doNotCloneChildren is always going to be False
  9326. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9327. }
  9328. }
  9329. }
  9330. for (index = 0; index < scene.particleSystems.length; index++) {
  9331. var system = scene.particleSystems[index];
  9332. if (system.emitter === source) {
  9333. system.clone(system.name, this);
  9334. }
  9335. }
  9336. this.computeWorldMatrix(true);
  9337. }
  9338. // Parent
  9339. if (parent !== null) {
  9340. this.parent = parent;
  9341. }
  9342. }
  9343. Mesh.prototype._clone = function () {
  9344. };
  9345. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9346. // Methods
  9347. get: function () {
  9348. return this._LODLevels.length > 0;
  9349. },
  9350. enumerable: true,
  9351. configurable: true
  9352. });
  9353. Mesh.prototype._sortLODLevels = function () {
  9354. this._LODLevels.sort(function (a, b) {
  9355. if (a.distance < b.distance) {
  9356. return 1;
  9357. }
  9358. if (a.distance > b.distance) {
  9359. return -1;
  9360. }
  9361. return 0;
  9362. });
  9363. };
  9364. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9365. if (mesh && mesh._masterMesh) {
  9366. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9367. return this;
  9368. }
  9369. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9370. this._LODLevels.push(level);
  9371. if (mesh) {
  9372. mesh._masterMesh = this;
  9373. }
  9374. this._sortLODLevels();
  9375. return this;
  9376. };
  9377. Mesh.prototype.removeLODLevel = function (mesh) {
  9378. for (var index = 0; index < this._LODLevels.length; index++) {
  9379. if (this._LODLevels[index].mesh === mesh) {
  9380. this._LODLevels.splice(index, 1);
  9381. if (mesh) {
  9382. mesh._masterMesh = null;
  9383. }
  9384. }
  9385. }
  9386. this._sortLODLevels();
  9387. return this;
  9388. };
  9389. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9390. if (!this._LODLevels || this._LODLevels.length === 0) {
  9391. return this;
  9392. }
  9393. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9394. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9395. return this;
  9396. }
  9397. for (var index = 0; index < this._LODLevels.length; index++) {
  9398. var level = this._LODLevels[index];
  9399. if (level.distance < distanceToCamera) {
  9400. if (level.mesh) {
  9401. level.mesh._preActivate();
  9402. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9403. }
  9404. return level.mesh;
  9405. }
  9406. }
  9407. return this;
  9408. };
  9409. Object.defineProperty(Mesh.prototype, "geometry", {
  9410. get: function () {
  9411. return this._geometry;
  9412. },
  9413. enumerable: true,
  9414. configurable: true
  9415. });
  9416. Mesh.prototype.getTotalVertices = function () {
  9417. if (!this._geometry) {
  9418. return 0;
  9419. }
  9420. return this._geometry.getTotalVertices();
  9421. };
  9422. Mesh.prototype.getVerticesData = function (kind) {
  9423. if (!this._geometry) {
  9424. return null;
  9425. }
  9426. return this._geometry.getVerticesData(kind);
  9427. };
  9428. Mesh.prototype.getVertexBuffer = function (kind) {
  9429. if (!this._geometry) {
  9430. return undefined;
  9431. }
  9432. return this._geometry.getVertexBuffer(kind);
  9433. };
  9434. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9435. if (!this._geometry) {
  9436. if (this._delayInfo) {
  9437. return this._delayInfo.indexOf(kind) !== -1;
  9438. }
  9439. return false;
  9440. }
  9441. return this._geometry.isVerticesDataPresent(kind);
  9442. };
  9443. Mesh.prototype.getVerticesDataKinds = function () {
  9444. if (!this._geometry) {
  9445. var result = [];
  9446. if (this._delayInfo) {
  9447. for (var kind in this._delayInfo) {
  9448. result.push(kind);
  9449. }
  9450. }
  9451. return result;
  9452. }
  9453. return this._geometry.getVerticesDataKinds();
  9454. };
  9455. Mesh.prototype.getTotalIndices = function () {
  9456. if (!this._geometry) {
  9457. return 0;
  9458. }
  9459. return this._geometry.getTotalIndices();
  9460. };
  9461. Mesh.prototype.getIndices = function () {
  9462. if (!this._geometry) {
  9463. return [];
  9464. }
  9465. return this._geometry.getIndices();
  9466. };
  9467. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9468. get: function () {
  9469. return this._masterMesh !== null && this._masterMesh !== undefined;
  9470. },
  9471. enumerable: true,
  9472. configurable: true
  9473. });
  9474. Mesh.prototype.isReady = function () {
  9475. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9476. return false;
  9477. }
  9478. return _super.prototype.isReady.call(this);
  9479. };
  9480. Mesh.prototype.isDisposed = function () {
  9481. return this._isDisposed;
  9482. };
  9483. // Methods
  9484. Mesh.prototype._preActivate = function () {
  9485. var sceneRenderId = this.getScene().getRenderId();
  9486. if (this._preActivateId == sceneRenderId) {
  9487. return;
  9488. }
  9489. this._preActivateId = sceneRenderId;
  9490. this._visibleInstances = null;
  9491. };
  9492. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9493. if (!this._visibleInstances) {
  9494. this._visibleInstances = {};
  9495. this._visibleInstances.defaultRenderId = renderId;
  9496. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9497. }
  9498. if (!this._visibleInstances[renderId]) {
  9499. this._visibleInstances[renderId] = new Array();
  9500. }
  9501. this._visibleInstances[renderId].push(instance);
  9502. };
  9503. Mesh.prototype.refreshBoundingInfo = function () {
  9504. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9505. if (data) {
  9506. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9507. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9508. }
  9509. if (this.subMeshes) {
  9510. for (var index = 0; index < this.subMeshes.length; index++) {
  9511. this.subMeshes[index].refreshBoundingInfo();
  9512. }
  9513. }
  9514. this._updateBoundingInfo();
  9515. };
  9516. Mesh.prototype._createGlobalSubMesh = function () {
  9517. var totalVertices = this.getTotalVertices();
  9518. if (!totalVertices || !this.getIndices()) {
  9519. return null;
  9520. }
  9521. this.releaseSubMeshes();
  9522. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9523. };
  9524. Mesh.prototype.subdivide = function (count) {
  9525. if (count < 1) {
  9526. return;
  9527. }
  9528. var totalIndices = this.getTotalIndices();
  9529. var subdivisionSize = (totalIndices / count) | 0;
  9530. var offset = 0;
  9531. while (subdivisionSize % 3 != 0) {
  9532. subdivisionSize++;
  9533. }
  9534. this.releaseSubMeshes();
  9535. for (var index = 0; index < count; index++) {
  9536. if (offset >= totalIndices) {
  9537. break;
  9538. }
  9539. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9540. offset += subdivisionSize;
  9541. }
  9542. this.synchronizeInstances();
  9543. };
  9544. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9545. if (kind instanceof Array) {
  9546. var temp = data;
  9547. data = kind;
  9548. kind = temp;
  9549. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9550. }
  9551. if (!this._geometry) {
  9552. var vertexData = new BABYLON.VertexData();
  9553. vertexData.set(data, kind);
  9554. var scene = this.getScene();
  9555. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9556. } else {
  9557. this._geometry.setVerticesData(kind, data, updatable, stride);
  9558. }
  9559. };
  9560. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9561. if (!this._geometry) {
  9562. return;
  9563. }
  9564. if (!makeItUnique) {
  9565. this._geometry.updateVerticesData(kind, data, updateExtends);
  9566. } else {
  9567. this.makeGeometryUnique();
  9568. this.updateVerticesData(kind, data, updateExtends, false);
  9569. }
  9570. };
  9571. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9572. if (!this._geometry) {
  9573. return;
  9574. }
  9575. if (!makeItUnique) {
  9576. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9577. } else {
  9578. this.makeGeometryUnique();
  9579. this.updateVerticesDataDirectly(kind, data, offset, false);
  9580. }
  9581. };
  9582. Mesh.prototype.makeGeometryUnique = function () {
  9583. if (!this._geometry) {
  9584. return;
  9585. }
  9586. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9587. geometry.applyToMesh(this);
  9588. };
  9589. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9590. if (!this._geometry) {
  9591. var vertexData = new BABYLON.VertexData();
  9592. vertexData.indices = indices;
  9593. var scene = this.getScene();
  9594. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9595. } else {
  9596. this._geometry.setIndices(indices, totalVertices);
  9597. }
  9598. };
  9599. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9600. var engine = this.getScene().getEngine();
  9601. // Wireframe
  9602. var indexToBind;
  9603. switch (fillMode) {
  9604. case BABYLON.Material.PointFillMode:
  9605. indexToBind = null;
  9606. break;
  9607. case BABYLON.Material.WireFrameFillMode:
  9608. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9609. break;
  9610. default:
  9611. case BABYLON.Material.TriangleFillMode:
  9612. indexToBind = this._geometry.getIndexBuffer();
  9613. break;
  9614. }
  9615. // VBOs
  9616. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9617. };
  9618. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9619. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9620. return;
  9621. }
  9622. var engine = this.getScene().getEngine();
  9623. switch (fillMode) {
  9624. case BABYLON.Material.PointFillMode:
  9625. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9626. break;
  9627. case BABYLON.Material.WireFrameFillMode:
  9628. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9629. break;
  9630. default:
  9631. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9632. }
  9633. };
  9634. Mesh.prototype.registerBeforeRender = function (func) {
  9635. this._onBeforeRenderCallbacks.push(func);
  9636. };
  9637. Mesh.prototype.unregisterBeforeRender = function (func) {
  9638. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9639. if (index > -1) {
  9640. this._onBeforeRenderCallbacks.splice(index, 1);
  9641. }
  9642. };
  9643. Mesh.prototype.registerAfterRender = function (func) {
  9644. this._onAfterRenderCallbacks.push(func);
  9645. };
  9646. Mesh.prototype.unregisterAfterRender = function (func) {
  9647. var index = this._onAfterRenderCallbacks.indexOf(func);
  9648. if (index > -1) {
  9649. this._onAfterRenderCallbacks.splice(index, 1);
  9650. }
  9651. };
  9652. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9653. var scene = this.getScene();
  9654. this._batchCache.mustReturn = false;
  9655. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9656. this._batchCache.visibleInstances[subMeshId] = null;
  9657. if (this._visibleInstances) {
  9658. var currentRenderId = scene.getRenderId();
  9659. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9660. var selfRenderId = this._renderId;
  9661. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9662. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9663. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9664. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9665. }
  9666. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9667. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9668. this._batchCache.mustReturn = true;
  9669. return this._batchCache;
  9670. }
  9671. if (currentRenderId !== selfRenderId) {
  9672. this._batchCache.renderSelf[subMeshId] = false;
  9673. }
  9674. }
  9675. this._renderIdForInstances[subMeshId] = currentRenderId;
  9676. }
  9677. return this._batchCache;
  9678. };
  9679. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9680. var visibleInstances = batch.visibleInstances[subMesh._id];
  9681. var matricesCount = visibleInstances.length + 1;
  9682. var bufferSize = matricesCount * 16 * 4;
  9683. while (this._instancesBufferSize < bufferSize) {
  9684. this._instancesBufferSize *= 2;
  9685. }
  9686. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9687. if (this._worldMatricesInstancesBuffer) {
  9688. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9689. }
  9690. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9691. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9692. }
  9693. var offset = 0;
  9694. var instancesCount = 0;
  9695. var world = this.getWorldMatrix();
  9696. if (batch.renderSelf[subMesh._id]) {
  9697. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9698. offset += 16;
  9699. instancesCount++;
  9700. }
  9701. if (visibleInstances) {
  9702. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9703. var instance = visibleInstances[instanceIndex];
  9704. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9705. offset += 16;
  9706. instancesCount++;
  9707. }
  9708. }
  9709. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9710. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9711. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9712. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9713. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9714. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9715. this._draw(subMesh, fillMode, instancesCount);
  9716. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9717. };
  9718. Mesh.prototype.render = function (subMesh) {
  9719. var scene = this.getScene();
  9720. // Managing instances
  9721. var batch = this._getInstancesRenderList(subMesh._id);
  9722. if (batch.mustReturn) {
  9723. return;
  9724. }
  9725. // Checking geometry state
  9726. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9727. return;
  9728. }
  9729. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9730. this._onBeforeRenderCallbacks[callbackIndex]();
  9731. }
  9732. var engine = scene.getEngine();
  9733. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9734. // Material
  9735. var effectiveMaterial = subMesh.getMaterial();
  9736. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9737. return;
  9738. }
  9739. // Outline - step 1
  9740. var savedDepthWrite = engine.getDepthWrite();
  9741. if (this.renderOutline) {
  9742. engine.setDepthWrite(false);
  9743. scene.getOutlineRenderer().render(subMesh, batch);
  9744. engine.setDepthWrite(savedDepthWrite);
  9745. }
  9746. effectiveMaterial._preBind();
  9747. var effect = effectiveMaterial.getEffect();
  9748. // Bind
  9749. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9750. this._bind(subMesh, effect, fillMode);
  9751. var world = this.getWorldMatrix();
  9752. effectiveMaterial.bind(world, this);
  9753. // Instances rendering
  9754. if (hardwareInstancedRendering) {
  9755. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9756. } else {
  9757. if (batch.renderSelf[subMesh._id]) {
  9758. // Draw
  9759. this._draw(subMesh, fillMode);
  9760. }
  9761. if (batch.visibleInstances[subMesh._id]) {
  9762. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9763. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9764. // World
  9765. world = instance.getWorldMatrix();
  9766. effectiveMaterial.bindOnlyWorldMatrix(world);
  9767. // Draw
  9768. this._draw(subMesh, fillMode);
  9769. }
  9770. }
  9771. }
  9772. // Unbind
  9773. effectiveMaterial.unbind();
  9774. // Outline - step 2
  9775. if (this.renderOutline && savedDepthWrite) {
  9776. engine.setDepthWrite(true);
  9777. engine.setColorWrite(false);
  9778. scene.getOutlineRenderer().render(subMesh, batch);
  9779. engine.setColorWrite(true);
  9780. }
  9781. // Overlay
  9782. if (this.renderOverlay) {
  9783. var currentMode = engine.getAlphaMode();
  9784. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9785. scene.getOutlineRenderer().render(subMesh, batch, true);
  9786. engine.setAlphaMode(currentMode);
  9787. }
  9788. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9789. this._onAfterRenderCallbacks[callbackIndex]();
  9790. }
  9791. };
  9792. Mesh.prototype.getEmittedParticleSystems = function () {
  9793. var results = new Array();
  9794. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9795. var particleSystem = this.getScene().particleSystems[index];
  9796. if (particleSystem.emitter === this) {
  9797. results.push(particleSystem);
  9798. }
  9799. }
  9800. return results;
  9801. };
  9802. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9803. var results = new Array();
  9804. var descendants = this.getDescendants();
  9805. descendants.push(this);
  9806. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9807. var particleSystem = this.getScene().particleSystems[index];
  9808. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9809. results.push(particleSystem);
  9810. }
  9811. }
  9812. return results;
  9813. };
  9814. Mesh.prototype.getChildren = function () {
  9815. var results = [];
  9816. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9817. var mesh = this.getScene().meshes[index];
  9818. if (mesh.parent == this) {
  9819. results.push(mesh);
  9820. }
  9821. }
  9822. return results;
  9823. };
  9824. Mesh.prototype._checkDelayState = function () {
  9825. var _this = this;
  9826. var that = this;
  9827. var scene = this.getScene();
  9828. if (this._geometry) {
  9829. this._geometry.load(scene);
  9830. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9831. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9832. scene._addPendingData(that);
  9833. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9834. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9835. if (data instanceof ArrayBuffer) {
  9836. _this._delayLoadingFunction(data, _this);
  9837. } else {
  9838. _this._delayLoadingFunction(JSON.parse(data), _this);
  9839. }
  9840. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9841. scene._removePendingData(_this);
  9842. }, function () {
  9843. }, scene.database, getBinaryData);
  9844. }
  9845. };
  9846. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9847. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9848. return false;
  9849. }
  9850. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9851. return false;
  9852. }
  9853. this._checkDelayState();
  9854. return true;
  9855. };
  9856. Mesh.prototype.setMaterialByID = function (id) {
  9857. var materials = this.getScene().materials;
  9858. for (var index = 0; index < materials.length; index++) {
  9859. if (materials[index].id == id) {
  9860. this.material = materials[index];
  9861. return;
  9862. }
  9863. }
  9864. // Multi
  9865. var multiMaterials = this.getScene().multiMaterials;
  9866. for (index = 0; index < multiMaterials.length; index++) {
  9867. if (multiMaterials[index].id == id) {
  9868. this.material = multiMaterials[index];
  9869. return;
  9870. }
  9871. }
  9872. };
  9873. Mesh.prototype.getAnimatables = function () {
  9874. var results = [];
  9875. if (this.material) {
  9876. results.push(this.material);
  9877. }
  9878. if (this.skeleton) {
  9879. results.push(this.skeleton);
  9880. }
  9881. return results;
  9882. };
  9883. // Geometry
  9884. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9885. // Position
  9886. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9887. return;
  9888. }
  9889. this._resetPointsArrayCache();
  9890. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9891. var temp = [];
  9892. for (var index = 0; index < data.length; index += 3) {
  9893. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9894. }
  9895. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9896. // Normals
  9897. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9898. return;
  9899. }
  9900. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9901. for (index = 0; index < data.length; index += 3) {
  9902. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9903. }
  9904. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9905. };
  9906. // Cache
  9907. Mesh.prototype._resetPointsArrayCache = function () {
  9908. this._positions = null;
  9909. };
  9910. Mesh.prototype._generatePointsArray = function () {
  9911. if (this._positions)
  9912. return true;
  9913. this._positions = [];
  9914. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9915. if (!data) {
  9916. return false;
  9917. }
  9918. for (var index = 0; index < data.length; index += 3) {
  9919. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9920. }
  9921. return true;
  9922. };
  9923. // Clone
  9924. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9925. return new BABYLON.Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  9926. };
  9927. // Dispose
  9928. Mesh.prototype.dispose = function (doNotRecurse) {
  9929. if (this._geometry) {
  9930. this._geometry.releaseForMesh(this, true);
  9931. }
  9932. // Instances
  9933. if (this._worldMatricesInstancesBuffer) {
  9934. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9935. this._worldMatricesInstancesBuffer = null;
  9936. }
  9937. while (this.instances.length) {
  9938. this.instances[0].dispose();
  9939. }
  9940. _super.prototype.dispose.call(this, doNotRecurse);
  9941. };
  9942. // Geometric tools
  9943. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9944. var _this = this;
  9945. var scene = this.getScene();
  9946. var onload = function (img) {
  9947. // Getting height map data
  9948. var canvas = document.createElement("canvas");
  9949. var context = canvas.getContext("2d");
  9950. var heightMapWidth = img.width;
  9951. var heightMapHeight = img.height;
  9952. canvas.width = heightMapWidth;
  9953. canvas.height = heightMapHeight;
  9954. context.drawImage(img, 0, 0);
  9955. // Create VertexData from map data
  9956. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9957. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9958. };
  9959. BABYLON.Tools.LoadImage(url, onload, function () {
  9960. }, scene.database);
  9961. };
  9962. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9963. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9964. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9965. return;
  9966. }
  9967. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9968. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9969. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9970. var position = BABYLON.Vector3.Zero();
  9971. var normal = BABYLON.Vector3.Zero();
  9972. var uv = BABYLON.Vector2.Zero();
  9973. for (var index = 0; index < positions.length; index += 3) {
  9974. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9975. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9976. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9977. // Compute height
  9978. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9979. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9980. var pos = (u + v * heightMapWidth) * 4;
  9981. var r = buffer[pos] / 255.0;
  9982. var g = buffer[pos + 1] / 255.0;
  9983. var b = buffer[pos + 2] / 255.0;
  9984. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9985. normal.normalize();
  9986. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9987. position = position.add(normal);
  9988. position.toArray(positions, index);
  9989. }
  9990. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9991. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9992. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9993. };
  9994. Mesh.prototype.convertToFlatShadedMesh = function () {
  9995. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  9996. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  9997. var kinds = this.getVerticesDataKinds();
  9998. var vbs = [];
  9999. var data = [];
  10000. var newdata = [];
  10001. var updatableNormals = false;
  10002. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10003. var kind = kinds[kindIndex];
  10004. var vertexBuffer = this.getVertexBuffer(kind);
  10005. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10006. updatableNormals = vertexBuffer.isUpdatable();
  10007. kinds.splice(kindIndex, 1);
  10008. kindIndex--;
  10009. continue;
  10010. }
  10011. vbs[kind] = vertexBuffer;
  10012. data[kind] = vbs[kind].getData();
  10013. newdata[kind] = [];
  10014. }
  10015. // Save previous submeshes
  10016. var previousSubmeshes = this.subMeshes.slice(0);
  10017. var indices = this.getIndices();
  10018. var totalIndices = this.getTotalIndices();
  10019. for (index = 0; index < totalIndices; index++) {
  10020. var vertexIndex = indices[index];
  10021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10022. kind = kinds[kindIndex];
  10023. var stride = vbs[kind].getStrideSize();
  10024. for (var offset = 0; offset < stride; offset++) {
  10025. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10026. }
  10027. }
  10028. }
  10029. // Updating faces & normal
  10030. var normals = [];
  10031. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10032. for (var index = 0; index < totalIndices; index += 3) {
  10033. indices[index] = index;
  10034. indices[index + 1] = index + 1;
  10035. indices[index + 2] = index + 2;
  10036. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10037. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10038. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10039. var p1p2 = p1.subtract(p2);
  10040. var p3p2 = p3.subtract(p2);
  10041. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10042. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10043. normals.push(normal.x);
  10044. normals.push(normal.y);
  10045. normals.push(normal.z);
  10046. }
  10047. }
  10048. this.setIndices(indices);
  10049. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10050. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10051. kind = kinds[kindIndex];
  10052. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10053. }
  10054. // Updating submeshes
  10055. this.releaseSubMeshes();
  10056. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10057. var previousOne = previousSubmeshes[submeshIndex];
  10058. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10059. }
  10060. this.synchronizeInstances();
  10061. };
  10062. // Instances
  10063. Mesh.prototype.createInstance = function (name) {
  10064. return new BABYLON.InstancedMesh(name, this);
  10065. };
  10066. Mesh.prototype.synchronizeInstances = function () {
  10067. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10068. var instance = this.instances[instanceIndex];
  10069. instance._syncSubMeshes();
  10070. }
  10071. };
  10072. /**
  10073. * Simplify the mesh according to the given array of settings.
  10074. * Function will return immediately and will simplify asnyc.
  10075. * @param settings a collection of simplification settings.
  10076. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10077. * @param type the type of simplification to run.
  10078. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10079. */
  10080. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10081. var _this = this;
  10082. if (typeof parallelProcessing === "undefined") { parallelProcessing = true; }
  10083. if (typeof type === "undefined") { type = 0 /* QUADRATIC */; }
  10084. var getSimplifier = function () {
  10085. switch (type) {
  10086. case 0 /* QUADRATIC */:
  10087. default:
  10088. return new BABYLON.QuadraticErrorSimplification(_this);
  10089. }
  10090. };
  10091. if (parallelProcessing) {
  10092. //parallel simplifier
  10093. settings.forEach(function (setting) {
  10094. var simplifier = getSimplifier();
  10095. simplifier.simplify(setting, function (newMesh) {
  10096. _this.addLODLevel(setting.distance, newMesh);
  10097. //check if it is the last
  10098. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10099. //all done, run the success callback.
  10100. successCallback();
  10101. }
  10102. });
  10103. });
  10104. } else {
  10105. //single simplifier.
  10106. var simplifier = getSimplifier();
  10107. var runDecimation = function (setting, callback) {
  10108. simplifier.simplify(setting, function (newMesh) {
  10109. _this.addLODLevel(setting.distance, newMesh);
  10110. //run the next quality level
  10111. callback();
  10112. });
  10113. };
  10114. var asyncLoop = new BABYLON.AsyncLoop(settings.length, function (loop) {
  10115. runDecimation(settings[loop.index], function () {
  10116. loop.executeNext();
  10117. });
  10118. }, function () {
  10119. //execution ended, run the success callback.
  10120. successCallback();
  10121. });
  10122. }
  10123. };
  10124. // Statics
  10125. Mesh.CreateBox = function (name, size, scene, updatable) {
  10126. var box = new BABYLON.Mesh(name, scene);
  10127. var vertexData = BABYLON.VertexData.CreateBox(size);
  10128. vertexData.applyToMesh(box, updatable);
  10129. return box;
  10130. };
  10131. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10132. var sphere = new BABYLON.Mesh(name, scene);
  10133. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10134. vertexData.applyToMesh(sphere, updatable);
  10135. return sphere;
  10136. };
  10137. // Cylinder and cone (Code inspired by SharpDX.org)
  10138. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10139. // subdivisions is a new parameter, we need to support old signature
  10140. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10141. if (scene !== undefined) {
  10142. updatable = scene;
  10143. }
  10144. scene = subdivisions;
  10145. subdivisions = 1;
  10146. }
  10147. var cylinder = new BABYLON.Mesh(name, scene);
  10148. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10149. vertexData.applyToMesh(cylinder, updatable);
  10150. return cylinder;
  10151. };
  10152. // Torus (Code from SharpDX.org)
  10153. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10154. var torus = new BABYLON.Mesh(name, scene);
  10155. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10156. vertexData.applyToMesh(torus, updatable);
  10157. return torus;
  10158. };
  10159. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10160. var torusKnot = new BABYLON.Mesh(name, scene);
  10161. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10162. vertexData.applyToMesh(torusKnot, updatable);
  10163. return torusKnot;
  10164. };
  10165. // Lines
  10166. Mesh.CreateLines = function (name, points, scene, updatable) {
  10167. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10168. var vertexData = BABYLON.VertexData.CreateLines(points);
  10169. vertexData.applyToMesh(lines, updatable);
  10170. return lines;
  10171. };
  10172. // Plane & ground
  10173. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10174. var plane = new BABYLON.Mesh(name, scene);
  10175. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10176. vertexData.applyToMesh(plane, updatable);
  10177. return plane;
  10178. };
  10179. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10180. var ground = new BABYLON.GroundMesh(name, scene);
  10181. ground._setReady(false);
  10182. ground._subdivisions = subdivisions;
  10183. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10184. vertexData.applyToMesh(ground, updatable);
  10185. ground._setReady(true);
  10186. return ground;
  10187. };
  10188. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10189. var tiledGround = new BABYLON.Mesh(name, scene);
  10190. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10191. vertexData.applyToMesh(tiledGround, updatable);
  10192. return tiledGround;
  10193. };
  10194. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10195. var ground = new BABYLON.GroundMesh(name, scene);
  10196. ground._subdivisions = subdivisions;
  10197. ground._setReady(false);
  10198. var onload = function (img) {
  10199. // Getting height map data
  10200. var canvas = document.createElement("canvas");
  10201. var context = canvas.getContext("2d");
  10202. var heightMapWidth = img.width;
  10203. var heightMapHeight = img.height;
  10204. canvas.width = heightMapWidth;
  10205. canvas.height = heightMapHeight;
  10206. context.drawImage(img, 0, 0);
  10207. // Create VertexData from map data
  10208. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10209. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10210. vertexData.applyToMesh(ground, updatable);
  10211. ground._setReady(true);
  10212. };
  10213. BABYLON.Tools.LoadImage(url, onload, function () {
  10214. }, scene.database);
  10215. return ground;
  10216. };
  10217. // Tools
  10218. Mesh.MinMax = function (meshes) {
  10219. var minVector = null;
  10220. var maxVector = null;
  10221. for (var i in meshes) {
  10222. var mesh = meshes[i];
  10223. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10224. if (!minVector) {
  10225. minVector = boundingBox.minimumWorld;
  10226. maxVector = boundingBox.maximumWorld;
  10227. continue;
  10228. }
  10229. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10230. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10231. }
  10232. return {
  10233. min: minVector,
  10234. max: maxVector
  10235. };
  10236. };
  10237. Mesh.Center = function (meshesOrMinMaxVector) {
  10238. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10239. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10240. };
  10241. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10242. if (typeof disposeSource === "undefined") { disposeSource = true; }
  10243. var source = meshes[0];
  10244. var material = source.material;
  10245. var scene = source.getScene();
  10246. if (!allow32BitsIndices) {
  10247. var totalVertices = 0;
  10248. for (var index = 0; index < meshes.length; index++) {
  10249. totalVertices += meshes[index].getTotalVertices();
  10250. if (totalVertices > 65536) {
  10251. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10252. return null;
  10253. }
  10254. }
  10255. }
  10256. // Merge
  10257. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10258. vertexData.transform(source.getWorldMatrix());
  10259. for (index = 1; index < meshes.length; index++) {
  10260. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10261. otherVertexData.transform(meshes[index].getWorldMatrix());
  10262. vertexData.merge(otherVertexData);
  10263. }
  10264. var newMesh = new Mesh(source.name + "_merged", scene);
  10265. vertexData.applyToMesh(newMesh);
  10266. // Setting properties
  10267. newMesh.material = material;
  10268. newMesh.checkCollisions = source.checkCollisions;
  10269. // Cleaning
  10270. if (disposeSource) {
  10271. for (index = 0; index < meshes.length; index++) {
  10272. meshes[index].dispose();
  10273. }
  10274. }
  10275. return newMesh;
  10276. };
  10277. return Mesh;
  10278. })(BABYLON.AbstractMesh);
  10279. BABYLON.Mesh = Mesh;
  10280. })(BABYLON || (BABYLON = {}));
  10281. //# sourceMappingURL=babylon.mesh.js.map
  10282. var BABYLON;
  10283. (function (BABYLON) {
  10284. var GroundMesh = (function (_super) {
  10285. __extends(GroundMesh, _super);
  10286. function GroundMesh(name, scene) {
  10287. _super.call(this, name, scene);
  10288. this.generateOctree = false;
  10289. this._worldInverse = new BABYLON.Matrix();
  10290. }
  10291. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10292. get: function () {
  10293. return this._subdivisions;
  10294. },
  10295. enumerable: true,
  10296. configurable: true
  10297. });
  10298. GroundMesh.prototype.optimize = function (chunksCount) {
  10299. this.subdivide(this._subdivisions);
  10300. this.createOrUpdateSubmeshesOctree(32);
  10301. };
  10302. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10303. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10304. this.getWorldMatrix().invertToRef(this._worldInverse);
  10305. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10306. var pickInfo = this.intersects(ray);
  10307. if (pickInfo.hit) {
  10308. return pickInfo.pickedPoint.y;
  10309. }
  10310. return 0;
  10311. };
  10312. return GroundMesh;
  10313. })(BABYLON.Mesh);
  10314. BABYLON.GroundMesh = GroundMesh;
  10315. })(BABYLON || (BABYLON = {}));
  10316. //# sourceMappingURL=babylon.groundMesh.js.map
  10317. var BABYLON;
  10318. (function (BABYLON) {
  10319. var InstancedMesh = (function (_super) {
  10320. __extends(InstancedMesh, _super);
  10321. function InstancedMesh(name, source) {
  10322. _super.call(this, name, source.getScene());
  10323. source.instances.push(this);
  10324. this._sourceMesh = source;
  10325. this.position.copyFrom(source.position);
  10326. this.rotation.copyFrom(source.rotation);
  10327. this.scaling.copyFrom(source.scaling);
  10328. if (source.rotationQuaternion) {
  10329. this.rotationQuaternion = source.rotationQuaternion.clone();
  10330. }
  10331. this.infiniteDistance = source.infiniteDistance;
  10332. this.setPivotMatrix(source.getPivotMatrix());
  10333. this.refreshBoundingInfo();
  10334. this._syncSubMeshes();
  10335. }
  10336. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10337. // Methods
  10338. get: function () {
  10339. return this._sourceMesh.receiveShadows;
  10340. },
  10341. enumerable: true,
  10342. configurable: true
  10343. });
  10344. Object.defineProperty(InstancedMesh.prototype, "material", {
  10345. get: function () {
  10346. return this._sourceMesh.material;
  10347. },
  10348. enumerable: true,
  10349. configurable: true
  10350. });
  10351. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10352. get: function () {
  10353. return this._sourceMesh.visibility;
  10354. },
  10355. enumerable: true,
  10356. configurable: true
  10357. });
  10358. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10359. get: function () {
  10360. return this._sourceMesh.skeleton;
  10361. },
  10362. enumerable: true,
  10363. configurable: true
  10364. });
  10365. InstancedMesh.prototype.getTotalVertices = function () {
  10366. return this._sourceMesh.getTotalVertices();
  10367. };
  10368. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10369. get: function () {
  10370. return this._sourceMesh;
  10371. },
  10372. enumerable: true,
  10373. configurable: true
  10374. });
  10375. InstancedMesh.prototype.getVerticesData = function (kind) {
  10376. return this._sourceMesh.getVerticesData(kind);
  10377. };
  10378. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10379. return this._sourceMesh.isVerticesDataPresent(kind);
  10380. };
  10381. InstancedMesh.prototype.getIndices = function () {
  10382. return this._sourceMesh.getIndices();
  10383. };
  10384. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10385. get: function () {
  10386. return this._sourceMesh._positions;
  10387. },
  10388. enumerable: true,
  10389. configurable: true
  10390. });
  10391. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10392. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10393. if (data) {
  10394. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10395. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10396. }
  10397. this._updateBoundingInfo();
  10398. };
  10399. InstancedMesh.prototype._preActivate = function () {
  10400. if (this._currentLOD) {
  10401. this._currentLOD._preActivate();
  10402. }
  10403. };
  10404. InstancedMesh.prototype._activate = function (renderId) {
  10405. if (this._currentLOD) {
  10406. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10407. }
  10408. };
  10409. InstancedMesh.prototype.getLOD = function (camera) {
  10410. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10411. if (this._currentLOD === this.sourceMesh) {
  10412. return this;
  10413. }
  10414. return this._currentLOD;
  10415. };
  10416. InstancedMesh.prototype._syncSubMeshes = function () {
  10417. this.releaseSubMeshes();
  10418. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10419. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10420. }
  10421. };
  10422. InstancedMesh.prototype._generatePointsArray = function () {
  10423. return this._sourceMesh._generatePointsArray();
  10424. };
  10425. // Clone
  10426. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10427. var result = this._sourceMesh.createInstance(name);
  10428. // Deep copy
  10429. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10430. // Bounding info
  10431. this.refreshBoundingInfo();
  10432. // Parent
  10433. if (newParent) {
  10434. result.parent = newParent;
  10435. }
  10436. if (!doNotCloneChildren) {
  10437. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10438. var mesh = this.getScene().meshes[index];
  10439. if (mesh.parent == this) {
  10440. mesh.clone(mesh.name, result);
  10441. }
  10442. }
  10443. }
  10444. result.computeWorldMatrix(true);
  10445. return result;
  10446. };
  10447. // Dispoe
  10448. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10449. // Remove from mesh
  10450. var index = this._sourceMesh.instances.indexOf(this);
  10451. this._sourceMesh.instances.splice(index, 1);
  10452. _super.prototype.dispose.call(this, doNotRecurse);
  10453. };
  10454. return InstancedMesh;
  10455. })(BABYLON.AbstractMesh);
  10456. BABYLON.InstancedMesh = InstancedMesh;
  10457. })(BABYLON || (BABYLON = {}));
  10458. //# sourceMappingURL=babylon.instancedMesh.js.map
  10459. var BABYLON;
  10460. (function (BABYLON) {
  10461. var SubMesh = (function () {
  10462. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10463. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10464. this.materialIndex = materialIndex;
  10465. this.verticesStart = verticesStart;
  10466. this.verticesCount = verticesCount;
  10467. this.indexStart = indexStart;
  10468. this.indexCount = indexCount;
  10469. this._renderId = 0;
  10470. this._mesh = mesh;
  10471. this._renderingMesh = renderingMesh || mesh;
  10472. mesh.subMeshes.push(this);
  10473. this._id = mesh.subMeshes.length - 1;
  10474. if (createBoundingBox) {
  10475. this.refreshBoundingInfo();
  10476. }
  10477. }
  10478. SubMesh.prototype.getBoundingInfo = function () {
  10479. return this._boundingInfo;
  10480. };
  10481. SubMesh.prototype.getMesh = function () {
  10482. return this._mesh;
  10483. };
  10484. SubMesh.prototype.getRenderingMesh = function () {
  10485. return this._renderingMesh;
  10486. };
  10487. SubMesh.prototype.getMaterial = function () {
  10488. var rootMaterial = this._renderingMesh.material;
  10489. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10490. var multiMaterial = rootMaterial;
  10491. return multiMaterial.getSubMaterial(this.materialIndex);
  10492. }
  10493. if (!rootMaterial) {
  10494. return this._mesh.getScene().defaultMaterial;
  10495. }
  10496. return rootMaterial;
  10497. };
  10498. // Methods
  10499. SubMesh.prototype.refreshBoundingInfo = function () {
  10500. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10501. if (!data) {
  10502. this._boundingInfo = this._mesh._boundingInfo;
  10503. return;
  10504. }
  10505. var indices = this._renderingMesh.getIndices();
  10506. var extend;
  10507. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10508. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10509. } else {
  10510. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10511. }
  10512. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10513. };
  10514. SubMesh.prototype._checkCollision = function (collider) {
  10515. return this._boundingInfo._checkCollision(collider);
  10516. };
  10517. SubMesh.prototype.updateBoundingInfo = function (world) {
  10518. if (!this._boundingInfo) {
  10519. this.refreshBoundingInfo();
  10520. }
  10521. this._boundingInfo._update(world);
  10522. };
  10523. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10524. return this._boundingInfo.isInFrustum(frustumPlanes);
  10525. };
  10526. SubMesh.prototype.render = function () {
  10527. this._renderingMesh.render(this);
  10528. };
  10529. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10530. if (!this._linesIndexBuffer) {
  10531. var linesIndices = [];
  10532. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10533. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10534. }
  10535. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10536. this.linesIndexCount = linesIndices.length;
  10537. }
  10538. return this._linesIndexBuffer;
  10539. };
  10540. SubMesh.prototype.canIntersects = function (ray) {
  10541. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10542. };
  10543. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10544. var intersectInfo = null;
  10545. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10546. var p0 = positions[indices[index]];
  10547. var p1 = positions[indices[index + 1]];
  10548. var p2 = positions[indices[index + 2]];
  10549. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10550. if (currentIntersectInfo) {
  10551. if (currentIntersectInfo.distance < 0) {
  10552. continue;
  10553. }
  10554. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10555. intersectInfo = currentIntersectInfo;
  10556. intersectInfo.faceId = index / 3;
  10557. if (fastCheck) {
  10558. break;
  10559. }
  10560. }
  10561. }
  10562. }
  10563. return intersectInfo;
  10564. };
  10565. // Clone
  10566. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10567. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10568. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10569. return result;
  10570. };
  10571. // Dispose
  10572. SubMesh.prototype.dispose = function () {
  10573. if (this._linesIndexBuffer) {
  10574. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10575. this._linesIndexBuffer = null;
  10576. }
  10577. // Remove from mesh
  10578. var index = this._mesh.subMeshes.indexOf(this);
  10579. this._mesh.subMeshes.splice(index, 1);
  10580. };
  10581. // Statics
  10582. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10583. var minVertexIndex = Number.MAX_VALUE;
  10584. var maxVertexIndex = -Number.MAX_VALUE;
  10585. renderingMesh = renderingMesh || mesh;
  10586. var indices = renderingMesh.getIndices();
  10587. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10588. var vertexIndex = indices[index];
  10589. if (vertexIndex < minVertexIndex)
  10590. minVertexIndex = vertexIndex;
  10591. if (vertexIndex > maxVertexIndex)
  10592. maxVertexIndex = vertexIndex;
  10593. }
  10594. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10595. };
  10596. return SubMesh;
  10597. })();
  10598. BABYLON.SubMesh = SubMesh;
  10599. })(BABYLON || (BABYLON = {}));
  10600. //# sourceMappingURL=babylon.subMesh.js.map
  10601. var BABYLON;
  10602. (function (BABYLON) {
  10603. var BaseTexture = (function () {
  10604. function BaseTexture(scene) {
  10605. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10606. this.hasAlpha = false;
  10607. this.getAlphaFromRGB = false;
  10608. this.level = 1;
  10609. this.isCube = false;
  10610. this.isRenderTarget = false;
  10611. this.animations = new Array();
  10612. this.coordinatesIndex = 0;
  10613. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10614. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10615. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10616. this.anisotropicFilteringLevel = 4;
  10617. this._scene = scene;
  10618. this._scene.textures.push(this);
  10619. }
  10620. BaseTexture.prototype.getScene = function () {
  10621. return this._scene;
  10622. };
  10623. BaseTexture.prototype.getTextureMatrix = function () {
  10624. return null;
  10625. };
  10626. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10627. return null;
  10628. };
  10629. BaseTexture.prototype.getInternalTexture = function () {
  10630. return this._texture;
  10631. };
  10632. BaseTexture.prototype.isReady = function () {
  10633. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10634. return true;
  10635. }
  10636. if (this._texture) {
  10637. return this._texture.isReady;
  10638. }
  10639. return false;
  10640. };
  10641. BaseTexture.prototype.getSize = function () {
  10642. if (this._texture._width) {
  10643. return { width: this._texture._width, height: this._texture._height };
  10644. }
  10645. if (this._texture._size) {
  10646. return { width: this._texture._size, height: this._texture._size };
  10647. }
  10648. return { width: 0, height: 0 };
  10649. };
  10650. BaseTexture.prototype.getBaseSize = function () {
  10651. if (!this.isReady())
  10652. return { width: 0, height: 0 };
  10653. if (this._texture._size) {
  10654. return { width: this._texture._size, height: this._texture._size };
  10655. }
  10656. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10657. };
  10658. BaseTexture.prototype.scale = function (ratio) {
  10659. };
  10660. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10661. get: function () {
  10662. return false;
  10663. },
  10664. enumerable: true,
  10665. configurable: true
  10666. });
  10667. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10668. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10669. for (var index = 0; index < texturesCache.length; index++) {
  10670. var texturesCacheEntry = texturesCache[index];
  10671. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10672. texturesCache.splice(index, 1);
  10673. return;
  10674. }
  10675. }
  10676. };
  10677. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10678. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10679. for (var index = 0; index < texturesCache.length; index++) {
  10680. var texturesCacheEntry = texturesCache[index];
  10681. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10682. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10683. texturesCacheEntry.references++;
  10684. return texturesCacheEntry;
  10685. }
  10686. }
  10687. }
  10688. return null;
  10689. };
  10690. BaseTexture.prototype.delayLoad = function () {
  10691. };
  10692. BaseTexture.prototype.releaseInternalTexture = function () {
  10693. if (!this._texture) {
  10694. return;
  10695. }
  10696. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10697. this._texture.references--;
  10698. // Final reference ?
  10699. if (this._texture.references === 0) {
  10700. var index = texturesCache.indexOf(this._texture);
  10701. texturesCache.splice(index, 1);
  10702. this._scene.getEngine()._releaseTexture(this._texture);
  10703. delete this._texture;
  10704. }
  10705. };
  10706. BaseTexture.prototype.clone = function () {
  10707. return null;
  10708. };
  10709. BaseTexture.prototype.dispose = function () {
  10710. // Remove from scene
  10711. var index = this._scene.textures.indexOf(this);
  10712. if (index >= 0) {
  10713. this._scene.textures.splice(index, 1);
  10714. }
  10715. if (this._texture === undefined) {
  10716. return;
  10717. }
  10718. this.releaseInternalTexture();
  10719. // Callback
  10720. if (this.onDispose) {
  10721. this.onDispose();
  10722. }
  10723. };
  10724. return BaseTexture;
  10725. })();
  10726. BABYLON.BaseTexture = BaseTexture;
  10727. })(BABYLON || (BABYLON = {}));
  10728. //# sourceMappingURL=babylon.baseTexture.js.map
  10729. var BABYLON;
  10730. (function (BABYLON) {
  10731. var RenderingGroup = (function () {
  10732. function RenderingGroup(index, scene) {
  10733. this.index = index;
  10734. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10735. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10736. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10737. this._scene = scene;
  10738. }
  10739. RenderingGroup.prototype.render = function (customRenderFunction) {
  10740. if (customRenderFunction) {
  10741. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10742. return true;
  10743. }
  10744. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10745. return false;
  10746. }
  10747. var engine = this._scene.getEngine();
  10748. // Opaque
  10749. var subIndex;
  10750. var submesh;
  10751. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10752. submesh = this._opaqueSubMeshes.data[subIndex];
  10753. submesh.render();
  10754. }
  10755. // Alpha test
  10756. engine.setAlphaTesting(true);
  10757. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10758. submesh = this._alphaTestSubMeshes.data[subIndex];
  10759. submesh.render();
  10760. }
  10761. engine.setAlphaTesting(false);
  10762. // Transparent
  10763. if (this._transparentSubMeshes.length) {
  10764. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10765. submesh = this._transparentSubMeshes.data[subIndex];
  10766. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10767. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10768. }
  10769. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10770. sortedArray.sort(function (a, b) {
  10771. // Alpha index first
  10772. if (a._alphaIndex > b._alphaIndex) {
  10773. return 1;
  10774. }
  10775. if (a._alphaIndex < b._alphaIndex) {
  10776. return -1;
  10777. }
  10778. // Then distance to camera
  10779. if (a._distanceToCamera < b._distanceToCamera) {
  10780. return 1;
  10781. }
  10782. if (a._distanceToCamera > b._distanceToCamera) {
  10783. return -1;
  10784. }
  10785. return 0;
  10786. });
  10787. // Rendering
  10788. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10789. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10790. submesh = sortedArray[subIndex];
  10791. submesh.render();
  10792. }
  10793. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10794. }
  10795. return true;
  10796. };
  10797. RenderingGroup.prototype.prepare = function () {
  10798. this._opaqueSubMeshes.reset();
  10799. this._transparentSubMeshes.reset();
  10800. this._alphaTestSubMeshes.reset();
  10801. };
  10802. RenderingGroup.prototype.dispatch = function (subMesh) {
  10803. var material = subMesh.getMaterial();
  10804. var mesh = subMesh.getMesh();
  10805. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10806. this._transparentSubMeshes.push(subMesh);
  10807. } else if (material.needAlphaTesting()) {
  10808. this._alphaTestSubMeshes.push(subMesh);
  10809. } else {
  10810. this._opaqueSubMeshes.push(subMesh); // Opaque
  10811. }
  10812. };
  10813. return RenderingGroup;
  10814. })();
  10815. BABYLON.RenderingGroup = RenderingGroup;
  10816. })(BABYLON || (BABYLON = {}));
  10817. //# sourceMappingURL=babylon.renderingGroup.js.map
  10818. var BABYLON;
  10819. (function (BABYLON) {
  10820. var RenderingManager = (function () {
  10821. function RenderingManager(scene) {
  10822. this._renderingGroups = new Array();
  10823. this._scene = scene;
  10824. }
  10825. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10826. if (this._scene._activeParticleSystems.length === 0) {
  10827. return;
  10828. }
  10829. // Particles
  10830. var beforeParticlesDate = BABYLON.Tools.Now;
  10831. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10832. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10833. if (particleSystem.renderingGroupId !== index) {
  10834. continue;
  10835. }
  10836. this._clearDepthBuffer();
  10837. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10838. this._scene._activeParticles += particleSystem.render();
  10839. }
  10840. }
  10841. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10842. };
  10843. RenderingManager.prototype._renderSprites = function (index) {
  10844. if (this._scene.spriteManagers.length === 0) {
  10845. return;
  10846. }
  10847. // Sprites
  10848. var beforeSpritessDate = BABYLON.Tools.Now;
  10849. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10850. var spriteManager = this._scene.spriteManagers[id];
  10851. if (spriteManager.renderingGroupId === index) {
  10852. this._clearDepthBuffer();
  10853. spriteManager.render();
  10854. }
  10855. }
  10856. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10857. };
  10858. RenderingManager.prototype._clearDepthBuffer = function () {
  10859. if (this._depthBufferAlreadyCleaned) {
  10860. return;
  10861. }
  10862. this._scene.getEngine().clear(0, false, true);
  10863. this._depthBufferAlreadyCleaned = true;
  10864. };
  10865. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10866. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10867. this._depthBufferAlreadyCleaned = false;
  10868. var renderingGroup = this._renderingGroups[index];
  10869. if (renderingGroup) {
  10870. this._clearDepthBuffer();
  10871. if (!renderingGroup.render(customRenderFunction)) {
  10872. this._renderingGroups.splice(index, 1);
  10873. }
  10874. }
  10875. this._renderSprites(index);
  10876. if (renderParticles) {
  10877. this._renderParticles(index, activeMeshes);
  10878. }
  10879. }
  10880. };
  10881. RenderingManager.prototype.reset = function () {
  10882. for (var index in this._renderingGroups) {
  10883. var renderingGroup = this._renderingGroups[index];
  10884. renderingGroup.prepare();
  10885. }
  10886. };
  10887. RenderingManager.prototype.dispatch = function (subMesh) {
  10888. var mesh = subMesh.getMesh();
  10889. var renderingGroupId = mesh.renderingGroupId || 0;
  10890. if (!this._renderingGroups[renderingGroupId]) {
  10891. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10892. }
  10893. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10894. };
  10895. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10896. return RenderingManager;
  10897. })();
  10898. BABYLON.RenderingManager = RenderingManager;
  10899. })(BABYLON || (BABYLON = {}));
  10900. //# sourceMappingURL=babylon.renderingManager.js.map
  10901. var BABYLON;
  10902. (function (BABYLON) {
  10903. var Texture = (function (_super) {
  10904. __extends(Texture, _super);
  10905. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10906. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10907. if (typeof onLoad === "undefined") { onLoad = null; }
  10908. if (typeof onError === "undefined") { onError = null; }
  10909. if (typeof buffer === "undefined") { buffer = null; }
  10910. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10911. _super.call(this, scene);
  10912. this.uOffset = 0;
  10913. this.vOffset = 0;
  10914. this.uScale = 1.0;
  10915. this.vScale = 1.0;
  10916. this.uAng = 0;
  10917. this.vAng = 0;
  10918. this.wAng = 0;
  10919. this.name = url;
  10920. this.url = url;
  10921. this._noMipmap = noMipmap;
  10922. this._invertY = invertY;
  10923. this._samplingMode = samplingMode;
  10924. this._buffer = buffer;
  10925. this._deleteBuffer = deleteBuffer;
  10926. if (!url) {
  10927. return;
  10928. }
  10929. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  10930. if (!this._texture) {
  10931. if (!scene.useDelayedTextureLoading) {
  10932. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10933. if (deleteBuffer) {
  10934. delete this._buffer;
  10935. }
  10936. } else {
  10937. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10938. }
  10939. }
  10940. }
  10941. Texture.prototype.delayLoad = function () {
  10942. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10943. return;
  10944. }
  10945. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10946. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  10947. if (!this._texture) {
  10948. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10949. if (this._deleteBuffer) {
  10950. delete this._buffer;
  10951. }
  10952. }
  10953. };
  10954. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10955. x -= this.uOffset + 0.5;
  10956. y -= this.vOffset + 0.5;
  10957. z -= 0.5;
  10958. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10959. t.x *= this.uScale;
  10960. t.y *= this.vScale;
  10961. t.x += 0.5;
  10962. t.y += 0.5;
  10963. t.z += 0.5;
  10964. };
  10965. Texture.prototype.getTextureMatrix = function () {
  10966. 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) {
  10967. return this._cachedTextureMatrix;
  10968. }
  10969. this._cachedUOffset = this.uOffset;
  10970. this._cachedVOffset = this.vOffset;
  10971. this._cachedUScale = this.uScale;
  10972. this._cachedVScale = this.vScale;
  10973. this._cachedUAng = this.uAng;
  10974. this._cachedVAng = this.vAng;
  10975. this._cachedWAng = this.wAng;
  10976. if (!this._cachedTextureMatrix) {
  10977. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10978. this._rowGenerationMatrix = new BABYLON.Matrix();
  10979. this._t0 = BABYLON.Vector3.Zero();
  10980. this._t1 = BABYLON.Vector3.Zero();
  10981. this._t2 = BABYLON.Vector3.Zero();
  10982. }
  10983. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10984. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10985. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10986. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10987. this._t1.subtractInPlace(this._t0);
  10988. this._t2.subtractInPlace(this._t0);
  10989. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10990. this._cachedTextureMatrix.m[0] = this._t1.x;
  10991. this._cachedTextureMatrix.m[1] = this._t1.y;
  10992. this._cachedTextureMatrix.m[2] = this._t1.z;
  10993. this._cachedTextureMatrix.m[4] = this._t2.x;
  10994. this._cachedTextureMatrix.m[5] = this._t2.y;
  10995. this._cachedTextureMatrix.m[6] = this._t2.z;
  10996. this._cachedTextureMatrix.m[8] = this._t0.x;
  10997. this._cachedTextureMatrix.m[9] = this._t0.y;
  10998. this._cachedTextureMatrix.m[10] = this._t0.z;
  10999. return this._cachedTextureMatrix;
  11000. };
  11001. Texture.prototype.getReflectionTextureMatrix = function () {
  11002. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11003. return this._cachedTextureMatrix;
  11004. }
  11005. if (!this._cachedTextureMatrix) {
  11006. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11007. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11008. }
  11009. this._cachedCoordinatesMode = this.coordinatesMode;
  11010. switch (this.coordinatesMode) {
  11011. case BABYLON.Texture.SPHERICAL_MODE:
  11012. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11013. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11014. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11015. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11016. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11017. break;
  11018. case BABYLON.Texture.PLANAR_MODE:
  11019. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11020. this._cachedTextureMatrix[0] = this.uScale;
  11021. this._cachedTextureMatrix[5] = this.vScale;
  11022. this._cachedTextureMatrix[12] = this.uOffset;
  11023. this._cachedTextureMatrix[13] = this.vOffset;
  11024. break;
  11025. case BABYLON.Texture.PROJECTION_MODE:
  11026. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11027. this._projectionModeMatrix.m[0] = 0.5;
  11028. this._projectionModeMatrix.m[5] = -0.5;
  11029. this._projectionModeMatrix.m[10] = 0.0;
  11030. this._projectionModeMatrix.m[12] = 0.5;
  11031. this._projectionModeMatrix.m[13] = 0.5;
  11032. this._projectionModeMatrix.m[14] = 1.0;
  11033. this._projectionModeMatrix.m[15] = 1.0;
  11034. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11035. break;
  11036. default:
  11037. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11038. break;
  11039. }
  11040. return this._cachedTextureMatrix;
  11041. };
  11042. Texture.prototype.clone = function () {
  11043. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  11044. // Base texture
  11045. newTexture.hasAlpha = this.hasAlpha;
  11046. newTexture.level = this.level;
  11047. newTexture.wrapU = this.wrapU;
  11048. newTexture.wrapV = this.wrapV;
  11049. newTexture.coordinatesIndex = this.coordinatesIndex;
  11050. newTexture.coordinatesMode = this.coordinatesMode;
  11051. // Texture
  11052. newTexture.uOffset = this.uOffset;
  11053. newTexture.vOffset = this.vOffset;
  11054. newTexture.uScale = this.uScale;
  11055. newTexture.vScale = this.vScale;
  11056. newTexture.uAng = this.uAng;
  11057. newTexture.vAng = this.vAng;
  11058. newTexture.wAng = this.wAng;
  11059. return newTexture;
  11060. };
  11061. // Statics
  11062. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11063. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11064. if (typeof onLoad === "undefined") { onLoad = null; }
  11065. if (typeof onError === "undefined") { onError = null; }
  11066. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11067. };
  11068. Texture.NEAREST_SAMPLINGMODE = 1;
  11069. Texture.BILINEAR_SAMPLINGMODE = 2;
  11070. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11071. Texture.EXPLICIT_MODE = 0;
  11072. Texture.SPHERICAL_MODE = 1;
  11073. Texture.PLANAR_MODE = 2;
  11074. Texture.CUBIC_MODE = 3;
  11075. Texture.PROJECTION_MODE = 4;
  11076. Texture.SKYBOX_MODE = 5;
  11077. Texture.CLAMP_ADDRESSMODE = 0;
  11078. Texture.WRAP_ADDRESSMODE = 1;
  11079. Texture.MIRROR_ADDRESSMODE = 2;
  11080. return Texture;
  11081. })(BABYLON.BaseTexture);
  11082. BABYLON.Texture = Texture;
  11083. })(BABYLON || (BABYLON = {}));
  11084. //# sourceMappingURL=babylon.texture.js.map
  11085. var BABYLON;
  11086. (function (BABYLON) {
  11087. var CubeTexture = (function (_super) {
  11088. __extends(CubeTexture, _super);
  11089. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11090. _super.call(this, scene);
  11091. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11092. this.name = rootUrl;
  11093. this.url = rootUrl;
  11094. this._noMipmap = noMipmap;
  11095. this.hasAlpha = false;
  11096. this._texture = this._getFromCache(rootUrl, noMipmap);
  11097. if (!extensions) {
  11098. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11099. }
  11100. this._extensions = extensions;
  11101. if (!this._texture) {
  11102. if (!scene.useDelayedTextureLoading) {
  11103. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11104. } else {
  11105. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11106. }
  11107. }
  11108. this.isCube = true;
  11109. this._textureMatrix = BABYLON.Matrix.Identity();
  11110. }
  11111. CubeTexture.prototype.clone = function () {
  11112. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11113. // Base texture
  11114. newTexture.level = this.level;
  11115. newTexture.wrapU = this.wrapU;
  11116. newTexture.wrapV = this.wrapV;
  11117. newTexture.coordinatesIndex = this.coordinatesIndex;
  11118. newTexture.coordinatesMode = this.coordinatesMode;
  11119. return newTexture;
  11120. };
  11121. // Methods
  11122. CubeTexture.prototype.delayLoad = function () {
  11123. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11124. return;
  11125. }
  11126. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11127. this._texture = this._getFromCache(this.url, this._noMipmap);
  11128. if (!this._texture) {
  11129. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11130. }
  11131. };
  11132. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11133. return this._textureMatrix;
  11134. };
  11135. return CubeTexture;
  11136. })(BABYLON.BaseTexture);
  11137. BABYLON.CubeTexture = CubeTexture;
  11138. })(BABYLON || (BABYLON = {}));
  11139. //# sourceMappingURL=babylon.cubeTexture.js.map
  11140. var BABYLON;
  11141. (function (BABYLON) {
  11142. var RenderTargetTexture = (function (_super) {
  11143. __extends(RenderTargetTexture, _super);
  11144. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  11145. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  11146. _super.call(this, null, scene, !generateMipMaps);
  11147. this.renderList = new Array();
  11148. this.renderParticles = true;
  11149. this.renderSprites = false;
  11150. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11151. this._currentRefreshId = -1;
  11152. this._refreshRate = 1;
  11153. this.name = name;
  11154. this.isRenderTarget = true;
  11155. this._size = size;
  11156. this._generateMipMaps = generateMipMaps;
  11157. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11158. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11159. // Rendering groups
  11160. this._renderingManager = new BABYLON.RenderingManager(scene);
  11161. }
  11162. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11163. this._currentRefreshId = -1;
  11164. };
  11165. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11166. get: function () {
  11167. return this._refreshRate;
  11168. },
  11169. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11170. set: function (value) {
  11171. this._refreshRate = value;
  11172. this.resetRefreshCounter();
  11173. },
  11174. enumerable: true,
  11175. configurable: true
  11176. });
  11177. RenderTargetTexture.prototype._shouldRender = function () {
  11178. if (this._currentRefreshId === -1) {
  11179. this._currentRefreshId = 1;
  11180. return true;
  11181. }
  11182. if (this.refreshRate == this._currentRefreshId) {
  11183. this._currentRefreshId = 1;
  11184. return true;
  11185. }
  11186. this._currentRefreshId++;
  11187. return false;
  11188. };
  11189. RenderTargetTexture.prototype.isReady = function () {
  11190. if (!this.getScene().renderTargetsEnabled) {
  11191. return false;
  11192. }
  11193. return _super.prototype.isReady.call(this);
  11194. };
  11195. RenderTargetTexture.prototype.getRenderSize = function () {
  11196. return this._size;
  11197. };
  11198. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11199. get: function () {
  11200. return true;
  11201. },
  11202. enumerable: true,
  11203. configurable: true
  11204. });
  11205. RenderTargetTexture.prototype.scale = function (ratio) {
  11206. var newSize = this._size * ratio;
  11207. this.resize(newSize, this._generateMipMaps);
  11208. };
  11209. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11210. this.releaseInternalTexture();
  11211. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11212. };
  11213. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11214. var scene = this.getScene();
  11215. var engine = scene.getEngine();
  11216. if (this._waitingRenderList) {
  11217. this.renderList = [];
  11218. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11219. var id = this._waitingRenderList[index];
  11220. this.renderList.push(scene.getMeshByID(id));
  11221. }
  11222. delete this._waitingRenderList;
  11223. }
  11224. if (!this.renderList) {
  11225. return;
  11226. }
  11227. // Bind
  11228. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11229. engine.bindFramebuffer(this._texture);
  11230. }
  11231. // Clear
  11232. engine.clear(scene.clearColor, true, true);
  11233. this._renderingManager.reset();
  11234. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  11235. var mesh = this.renderList[meshIndex];
  11236. if (mesh) {
  11237. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11238. // Reset _currentRefreshId
  11239. this.resetRefreshCounter();
  11240. continue;
  11241. }
  11242. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  11243. mesh._activate(scene.getRenderId());
  11244. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11245. var subMesh = mesh.subMeshes[subIndex];
  11246. scene._activeVertices += subMesh.indexCount;
  11247. this._renderingManager.dispatch(subMesh);
  11248. }
  11249. }
  11250. }
  11251. }
  11252. if (!this._doNotChangeAspectRatio) {
  11253. scene.updateTransformMatrix(true);
  11254. }
  11255. if (this.onBeforeRender) {
  11256. this.onBeforeRender();
  11257. }
  11258. // Render
  11259. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  11260. if (useCameraPostProcess) {
  11261. scene.postProcessManager._finalizeFrame(false, this._texture);
  11262. }
  11263. if (this.onAfterRender) {
  11264. this.onAfterRender();
  11265. }
  11266. // Unbind
  11267. engine.unBindFramebuffer(this._texture);
  11268. if (!this._doNotChangeAspectRatio) {
  11269. scene.updateTransformMatrix(true);
  11270. }
  11271. };
  11272. RenderTargetTexture.prototype.clone = function () {
  11273. var textureSize = this.getSize();
  11274. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11275. // Base texture
  11276. newTexture.hasAlpha = this.hasAlpha;
  11277. newTexture.level = this.level;
  11278. // RenderTarget Texture
  11279. newTexture.coordinatesMode = this.coordinatesMode;
  11280. newTexture.renderList = this.renderList.slice(0);
  11281. return newTexture;
  11282. };
  11283. return RenderTargetTexture;
  11284. })(BABYLON.Texture);
  11285. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11286. })(BABYLON || (BABYLON = {}));
  11287. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11288. var BABYLON;
  11289. (function (BABYLON) {
  11290. var ProceduralTexture = (function (_super) {
  11291. __extends(ProceduralTexture, _super);
  11292. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11293. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11294. _super.call(this, null, scene, !generateMipMaps);
  11295. this._currentRefreshId = -1;
  11296. this._refreshRate = 1;
  11297. this._vertexDeclaration = [2];
  11298. this._vertexStrideSize = 2 * 4;
  11299. this._uniforms = new Array();
  11300. this._samplers = new Array();
  11301. this._textures = new Array();
  11302. this._floats = new Array();
  11303. this._floatsArrays = {};
  11304. this._colors3 = new Array();
  11305. this._colors4 = new Array();
  11306. this._vectors2 = new Array();
  11307. this._vectors3 = new Array();
  11308. this._matrices = new Array();
  11309. this._fallbackTextureUsed = false;
  11310. scene._proceduralTextures.push(this);
  11311. this.name = name;
  11312. this.isRenderTarget = true;
  11313. this._size = size;
  11314. this._generateMipMaps = generateMipMaps;
  11315. this.setFragment(fragment);
  11316. this._fallbackTexture = fallbackTexture;
  11317. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11318. // VBO
  11319. var vertices = [];
  11320. vertices.push(1, 1);
  11321. vertices.push(-1, 1);
  11322. vertices.push(-1, -1);
  11323. vertices.push(1, -1);
  11324. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11325. // Indices
  11326. var indices = [];
  11327. indices.push(0);
  11328. indices.push(1);
  11329. indices.push(2);
  11330. indices.push(0);
  11331. indices.push(2);
  11332. indices.push(3);
  11333. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11334. }
  11335. ProceduralTexture.prototype.reset = function () {
  11336. if (this._effect === undefined) {
  11337. return;
  11338. }
  11339. var engine = this.getScene().getEngine();
  11340. engine._releaseEffect(this._effect);
  11341. };
  11342. ProceduralTexture.prototype.isReady = function () {
  11343. var _this = this;
  11344. var engine = this.getScene().getEngine();
  11345. var shaders;
  11346. if (!this._fragment) {
  11347. return false;
  11348. }
  11349. if (this._fallbackTextureUsed) {
  11350. return true;
  11351. }
  11352. if (this._fragment.fragmentElement !== undefined) {
  11353. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11354. } else {
  11355. shaders = { vertex: "procedural", fragment: this._fragment };
  11356. }
  11357. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11358. _this.releaseInternalTexture();
  11359. if (_this._fallbackTexture) {
  11360. _this._texture = _this._fallbackTexture._texture;
  11361. _this._texture.references++;
  11362. }
  11363. _this._fallbackTextureUsed = true;
  11364. });
  11365. return this._effect.isReady();
  11366. };
  11367. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11368. this._currentRefreshId = -1;
  11369. };
  11370. ProceduralTexture.prototype.setFragment = function (fragment) {
  11371. this._fragment = fragment;
  11372. };
  11373. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11374. get: function () {
  11375. return this._refreshRate;
  11376. },
  11377. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11378. set: function (value) {
  11379. this._refreshRate = value;
  11380. this.resetRefreshCounter();
  11381. },
  11382. enumerable: true,
  11383. configurable: true
  11384. });
  11385. ProceduralTexture.prototype._shouldRender = function () {
  11386. if (!this.isReady() || !this._texture) {
  11387. return false;
  11388. }
  11389. if (this._fallbackTextureUsed) {
  11390. return false;
  11391. }
  11392. if (this._currentRefreshId === -1) {
  11393. this._currentRefreshId = 1;
  11394. return true;
  11395. }
  11396. if (this.refreshRate === this._currentRefreshId) {
  11397. this._currentRefreshId = 1;
  11398. return true;
  11399. }
  11400. this._currentRefreshId++;
  11401. return false;
  11402. };
  11403. ProceduralTexture.prototype.getRenderSize = function () {
  11404. return this._size;
  11405. };
  11406. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11407. if (this._fallbackTextureUsed) {
  11408. return;
  11409. }
  11410. this.releaseInternalTexture();
  11411. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11412. };
  11413. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11414. if (this._uniforms.indexOf(uniformName) === -1) {
  11415. this._uniforms.push(uniformName);
  11416. }
  11417. };
  11418. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11419. if (this._samplers.indexOf(name) === -1) {
  11420. this._samplers.push(name);
  11421. }
  11422. this._textures[name] = texture;
  11423. return this;
  11424. };
  11425. ProceduralTexture.prototype.setFloat = function (name, value) {
  11426. this._checkUniform(name);
  11427. this._floats[name] = value;
  11428. return this;
  11429. };
  11430. ProceduralTexture.prototype.setFloats = function (name, value) {
  11431. this._checkUniform(name);
  11432. this._floatsArrays[name] = value;
  11433. return this;
  11434. };
  11435. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11436. this._checkUniform(name);
  11437. this._colors3[name] = value;
  11438. return this;
  11439. };
  11440. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11441. this._checkUniform(name);
  11442. this._colors4[name] = value;
  11443. return this;
  11444. };
  11445. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11446. this._checkUniform(name);
  11447. this._vectors2[name] = value;
  11448. return this;
  11449. };
  11450. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11451. this._checkUniform(name);
  11452. this._vectors3[name] = value;
  11453. return this;
  11454. };
  11455. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11456. this._checkUniform(name);
  11457. this._matrices[name] = value;
  11458. return this;
  11459. };
  11460. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11461. var scene = this.getScene();
  11462. var engine = scene.getEngine();
  11463. engine.bindFramebuffer(this._texture);
  11464. // Clear
  11465. engine.clear(scene.clearColor, true, true);
  11466. // Render
  11467. engine.enableEffect(this._effect);
  11468. engine.setState(false);
  11469. for (var name in this._textures) {
  11470. this._effect.setTexture(name, this._textures[name]);
  11471. }
  11472. for (name in this._floats) {
  11473. this._effect.setFloat(name, this._floats[name]);
  11474. }
  11475. for (name in this._floatsArrays) {
  11476. this._effect.setArray(name, this._floatsArrays[name]);
  11477. }
  11478. for (name in this._colors3) {
  11479. this._effect.setColor3(name, this._colors3[name]);
  11480. }
  11481. for (name in this._colors4) {
  11482. var color = this._colors4[name];
  11483. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11484. }
  11485. for (name in this._vectors2) {
  11486. this._effect.setVector2(name, this._vectors2[name]);
  11487. }
  11488. for (name in this._vectors3) {
  11489. this._effect.setVector3(name, this._vectors3[name]);
  11490. }
  11491. for (name in this._matrices) {
  11492. this._effect.setMatrix(name, this._matrices[name]);
  11493. }
  11494. // VBOs
  11495. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11496. // Draw order
  11497. engine.draw(true, 0, 6);
  11498. // Unbind
  11499. engine.unBindFramebuffer(this._texture);
  11500. };
  11501. ProceduralTexture.prototype.clone = function () {
  11502. var textureSize = this.getSize();
  11503. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11504. // Base texture
  11505. newTexture.hasAlpha = this.hasAlpha;
  11506. newTexture.level = this.level;
  11507. // RenderTarget Texture
  11508. newTexture.coordinatesMode = this.coordinatesMode;
  11509. return newTexture;
  11510. };
  11511. ProceduralTexture.prototype.dispose = function () {
  11512. var index = this.getScene()._proceduralTextures.indexOf(this);
  11513. if (index >= 0) {
  11514. this.getScene()._proceduralTextures.splice(index, 1);
  11515. }
  11516. _super.prototype.dispose.call(this);
  11517. };
  11518. return ProceduralTexture;
  11519. })(BABYLON.Texture);
  11520. BABYLON.ProceduralTexture = ProceduralTexture;
  11521. })(BABYLON || (BABYLON = {}));
  11522. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11523. var BABYLON;
  11524. (function (BABYLON) {
  11525. var WoodProceduralTexture = (function (_super) {
  11526. __extends(WoodProceduralTexture, _super);
  11527. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11528. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11529. this._ampScale = 100.0;
  11530. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11531. this.updateShaderUniforms();
  11532. this.refreshRate = 0;
  11533. }
  11534. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11535. this.setFloat("ampScale", this._ampScale);
  11536. this.setColor3("woodColor", this._woodColor);
  11537. };
  11538. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11539. get: function () {
  11540. return this._ampScale;
  11541. },
  11542. set: function (value) {
  11543. this._ampScale = value;
  11544. this.updateShaderUniforms();
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11550. get: function () {
  11551. return this._woodColor;
  11552. },
  11553. set: function (value) {
  11554. this._woodColor = value;
  11555. this.updateShaderUniforms();
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. return WoodProceduralTexture;
  11561. })(BABYLON.ProceduralTexture);
  11562. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11563. var FireProceduralTexture = (function (_super) {
  11564. __extends(FireProceduralTexture, _super);
  11565. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11566. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11567. this._time = 0.0;
  11568. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11569. this._shift = 1.6;
  11570. this._autoGenerateTime = true;
  11571. this._alphaThreshold = 0.5;
  11572. this._fireColors = FireProceduralTexture.RedFireColors;
  11573. this.updateShaderUniforms();
  11574. this.refreshRate = 1;
  11575. }
  11576. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11577. this.setFloat("time", this._time);
  11578. this.setVector2("speed", this._speed);
  11579. this.setFloat("shift", this._shift);
  11580. this.setColor3("c1", this._fireColors[0]);
  11581. this.setColor3("c2", this._fireColors[1]);
  11582. this.setColor3("c3", this._fireColors[2]);
  11583. this.setColor3("c4", this._fireColors[3]);
  11584. this.setColor3("c5", this._fireColors[4]);
  11585. this.setColor3("c6", this._fireColors[5]);
  11586. this.setFloat("alphaThreshold", this._alphaThreshold);
  11587. };
  11588. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11589. if (this._autoGenerateTime) {
  11590. this._time += this.getScene().getAnimationRatio() * 0.03;
  11591. this.updateShaderUniforms();
  11592. }
  11593. _super.prototype.render.call(this, useCameraPostProcess);
  11594. };
  11595. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11596. get: function () {
  11597. return [
  11598. new BABYLON.Color3(0.5, 0.0, 1.0),
  11599. new BABYLON.Color3(0.9, 0.0, 1.0),
  11600. new BABYLON.Color3(0.2, 0.0, 1.0),
  11601. new BABYLON.Color3(1.0, 0.9, 1.0),
  11602. new BABYLON.Color3(0.1, 0.1, 1.0),
  11603. new BABYLON.Color3(0.9, 0.9, 1.0)
  11604. ];
  11605. },
  11606. enumerable: true,
  11607. configurable: true
  11608. });
  11609. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11610. get: function () {
  11611. return [
  11612. new BABYLON.Color3(0.5, 1.0, 0.0),
  11613. new BABYLON.Color3(0.5, 1.0, 0.0),
  11614. new BABYLON.Color3(0.3, 0.4, 0.0),
  11615. new BABYLON.Color3(0.5, 1.0, 0.0),
  11616. new BABYLON.Color3(0.2, 0.0, 0.0),
  11617. new BABYLON.Color3(0.5, 1.0, 0.0)
  11618. ];
  11619. },
  11620. enumerable: true,
  11621. configurable: true
  11622. });
  11623. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11624. get: function () {
  11625. return [
  11626. new BABYLON.Color3(0.5, 0.0, 0.1),
  11627. new BABYLON.Color3(0.9, 0.0, 0.0),
  11628. new BABYLON.Color3(0.2, 0.0, 0.0),
  11629. new BABYLON.Color3(1.0, 0.9, 0.0),
  11630. new BABYLON.Color3(0.1, 0.1, 0.1),
  11631. new BABYLON.Color3(0.9, 0.9, 0.9)
  11632. ];
  11633. },
  11634. enumerable: true,
  11635. configurable: true
  11636. });
  11637. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11638. get: function () {
  11639. return [
  11640. new BABYLON.Color3(0.1, 0.0, 0.5),
  11641. new BABYLON.Color3(0.0, 0.0, 0.5),
  11642. new BABYLON.Color3(0.1, 0.0, 0.2),
  11643. new BABYLON.Color3(0.0, 0.0, 1.0),
  11644. new BABYLON.Color3(0.1, 0.2, 0.3),
  11645. new BABYLON.Color3(0.0, 0.2, 0.9)
  11646. ];
  11647. },
  11648. enumerable: true,
  11649. configurable: true
  11650. });
  11651. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11652. get: function () {
  11653. return this._fireColors;
  11654. },
  11655. set: function (value) {
  11656. this._fireColors = value;
  11657. this.updateShaderUniforms();
  11658. },
  11659. enumerable: true,
  11660. configurable: true
  11661. });
  11662. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11663. get: function () {
  11664. return this._time;
  11665. },
  11666. set: function (value) {
  11667. this._time = value;
  11668. this.updateShaderUniforms();
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11674. get: function () {
  11675. return this._speed;
  11676. },
  11677. set: function (value) {
  11678. this._speed = value;
  11679. this.updateShaderUniforms();
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11685. get: function () {
  11686. return this._shift;
  11687. },
  11688. set: function (value) {
  11689. this._shift = value;
  11690. this.updateShaderUniforms();
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11696. get: function () {
  11697. return this._alphaThreshold;
  11698. },
  11699. set: function (value) {
  11700. this._alphaThreshold = value;
  11701. this.updateShaderUniforms();
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. return FireProceduralTexture;
  11707. })(BABYLON.ProceduralTexture);
  11708. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11709. var CloudProceduralTexture = (function (_super) {
  11710. __extends(CloudProceduralTexture, _super);
  11711. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11712. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11713. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11714. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11715. this.updateShaderUniforms();
  11716. this.refreshRate = 0;
  11717. }
  11718. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11719. this.setColor3("skyColor", this._skyColor);
  11720. this.setColor3("cloudColor", this._cloudColor);
  11721. };
  11722. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11723. get: function () {
  11724. return this._skyColor;
  11725. },
  11726. set: function (value) {
  11727. this._skyColor = value;
  11728. this.updateShaderUniforms();
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11734. get: function () {
  11735. return this._cloudColor;
  11736. },
  11737. set: function (value) {
  11738. this._cloudColor = value;
  11739. this.updateShaderUniforms();
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. return CloudProceduralTexture;
  11745. })(BABYLON.ProceduralTexture);
  11746. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11747. var GrassProceduralTexture = (function (_super) {
  11748. __extends(GrassProceduralTexture, _super);
  11749. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11750. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11751. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11752. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11753. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11754. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11755. this._grassColors = [
  11756. new BABYLON.Color3(0.29, 0.38, 0.02),
  11757. new BABYLON.Color3(0.36, 0.49, 0.09),
  11758. new BABYLON.Color3(0.51, 0.6, 0.28)
  11759. ];
  11760. this.updateShaderUniforms();
  11761. this.refreshRate = 0;
  11762. }
  11763. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11764. this.setColor3("herb1Color", this._grassColors[0]);
  11765. this.setColor3("herb2Color", this._grassColors[1]);
  11766. this.setColor3("herb3Color", this._grassColors[2]);
  11767. this.setColor3("groundColor", this._groundColor);
  11768. };
  11769. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11770. get: function () {
  11771. return this._grassColors;
  11772. },
  11773. set: function (value) {
  11774. this._grassColors = value;
  11775. this.updateShaderUniforms();
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11781. get: function () {
  11782. return this._groundColor;
  11783. },
  11784. set: function (value) {
  11785. this.groundColor = value;
  11786. this.updateShaderUniforms();
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. return GrassProceduralTexture;
  11792. })(BABYLON.ProceduralTexture);
  11793. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11794. var RoadProceduralTexture = (function (_super) {
  11795. __extends(RoadProceduralTexture, _super);
  11796. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11797. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11798. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11799. this.updateShaderUniforms();
  11800. this.refreshRate = 0;
  11801. }
  11802. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11803. this.setColor3("roadColor", this._roadColor);
  11804. };
  11805. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11806. get: function () {
  11807. return this._roadColor;
  11808. },
  11809. set: function (value) {
  11810. this._roadColor = value;
  11811. this.updateShaderUniforms();
  11812. },
  11813. enumerable: true,
  11814. configurable: true
  11815. });
  11816. return RoadProceduralTexture;
  11817. })(BABYLON.ProceduralTexture);
  11818. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11819. var BrickProceduralTexture = (function (_super) {
  11820. __extends(BrickProceduralTexture, _super);
  11821. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11822. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11823. this._numberOfBricksHeight = 15;
  11824. this._numberOfBricksWidth = 5;
  11825. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11826. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11827. this.updateShaderUniforms();
  11828. this.refreshRate = 0;
  11829. }
  11830. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11831. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11832. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11833. this.setColor3("brickColor", this._brickColor);
  11834. this.setColor3("jointColor", this._jointColor);
  11835. };
  11836. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11837. get: function () {
  11838. return this._numberOfBricksHeight;
  11839. },
  11840. enumerable: true,
  11841. configurable: true
  11842. });
  11843. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11844. set: function (value) {
  11845. this._numberOfBricksHeight = value;
  11846. this.updateShaderUniforms();
  11847. },
  11848. enumerable: true,
  11849. configurable: true
  11850. });
  11851. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11852. get: function () {
  11853. return this._numberOfBricksWidth;
  11854. },
  11855. set: function (value) {
  11856. this._numberOfBricksHeight = value;
  11857. this.updateShaderUniforms();
  11858. },
  11859. enumerable: true,
  11860. configurable: true
  11861. });
  11862. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11863. get: function () {
  11864. return this._jointColor;
  11865. },
  11866. set: function (value) {
  11867. this._jointColor = value;
  11868. this.updateShaderUniforms();
  11869. },
  11870. enumerable: true,
  11871. configurable: true
  11872. });
  11873. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11874. get: function () {
  11875. return this._brickColor;
  11876. },
  11877. set: function (value) {
  11878. this._brickColor = value;
  11879. this.updateShaderUniforms();
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. return BrickProceduralTexture;
  11885. })(BABYLON.ProceduralTexture);
  11886. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11887. var MarbleProceduralTexture = (function (_super) {
  11888. __extends(MarbleProceduralTexture, _super);
  11889. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11890. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11891. this._numberOfTilesHeight = 3;
  11892. this._numberOfTilesWidth = 3;
  11893. this._amplitude = 9.0;
  11894. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11895. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11896. this.updateShaderUniforms();
  11897. this.refreshRate = 0;
  11898. }
  11899. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11900. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11901. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11902. this.setFloat("amplitude", this._amplitude);
  11903. this.setColor3("marbleColor", this._marbleColor);
  11904. this.setColor3("jointColor", this._jointColor);
  11905. };
  11906. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11907. get: function () {
  11908. return this._numberOfTilesHeight;
  11909. },
  11910. set: function (value) {
  11911. this._numberOfTilesHeight = value;
  11912. this.updateShaderUniforms();
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11918. get: function () {
  11919. return this._numberOfTilesWidth;
  11920. },
  11921. set: function (value) {
  11922. this._numberOfTilesWidth = value;
  11923. this.updateShaderUniforms();
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11929. get: function () {
  11930. return this._jointColor;
  11931. },
  11932. set: function (value) {
  11933. this._jointColor = value;
  11934. this.updateShaderUniforms();
  11935. },
  11936. enumerable: true,
  11937. configurable: true
  11938. });
  11939. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11940. get: function () {
  11941. return this._marbleColor;
  11942. },
  11943. set: function (value) {
  11944. this._marbleColor = value;
  11945. this.updateShaderUniforms();
  11946. },
  11947. enumerable: true,
  11948. configurable: true
  11949. });
  11950. return MarbleProceduralTexture;
  11951. })(BABYLON.ProceduralTexture);
  11952. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  11953. })(BABYLON || (BABYLON = {}));
  11954. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  11955. var BABYLON;
  11956. (function (BABYLON) {
  11957. var CustomProceduralTexture = (function (_super) {
  11958. __extends(CustomProceduralTexture, _super);
  11959. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11960. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  11961. this._animate = true;
  11962. this._time = 0;
  11963. this._texturePath = texturePath;
  11964. //Try to load json
  11965. this.loadJson(texturePath);
  11966. this.refreshRate = 1;
  11967. }
  11968. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11969. var _this = this;
  11970. var that = this;
  11971. function noConfigFile() {
  11972. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  11973. try {
  11974. that.setFragment(that._texturePath);
  11975. } catch (ex) {
  11976. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  11977. }
  11978. }
  11979. var configFileUrl = jsonUrl + "/config.json";
  11980. var xhr = new XMLHttpRequest();
  11981. xhr.open("GET", configFileUrl, true);
  11982. xhr.addEventListener("load", function () {
  11983. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11984. try {
  11985. _this._config = JSON.parse(xhr.response);
  11986. _this.updateShaderUniforms();
  11987. _this.updateTextures();
  11988. _this.setFragment(_this._texturePath + "/custom");
  11989. _this._animate = _this._config.animate;
  11990. _this.refreshRate = _this._config.refreshrate;
  11991. } catch (ex) {
  11992. noConfigFile();
  11993. }
  11994. } else {
  11995. noConfigFile();
  11996. }
  11997. }, false);
  11998. xhr.addEventListener("error", function (event) {
  11999. noConfigFile();
  12000. }, false);
  12001. try {
  12002. xhr.send();
  12003. } catch (ex) {
  12004. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12005. }
  12006. };
  12007. CustomProceduralTexture.prototype.isReady = function () {
  12008. if (!_super.prototype.isReady.call(this)) {
  12009. return false;
  12010. }
  12011. for (var name in this._textures) {
  12012. var texture = this._textures[name];
  12013. if (!texture.isReady()) {
  12014. return false;
  12015. }
  12016. }
  12017. return true;
  12018. };
  12019. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12020. if (this._animate) {
  12021. this._time += this.getScene().getAnimationRatio() * 0.03;
  12022. this.updateShaderUniforms();
  12023. }
  12024. _super.prototype.render.call(this, useCameraPostProcess);
  12025. };
  12026. CustomProceduralTexture.prototype.updateTextures = function () {
  12027. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12028. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12029. }
  12030. };
  12031. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12032. if (this._config) {
  12033. for (var j = 0; j < this._config.uniforms.length; j++) {
  12034. var uniform = this._config.uniforms[j];
  12035. switch (uniform.type) {
  12036. case "float":
  12037. this.setFloat(uniform.name, uniform.value);
  12038. break;
  12039. case "color3":
  12040. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12041. break;
  12042. case "color4":
  12043. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12044. break;
  12045. case "vector2":
  12046. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12047. break;
  12048. case "vector3":
  12049. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12050. break;
  12051. }
  12052. }
  12053. }
  12054. this.setFloat("time", this._time);
  12055. };
  12056. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12057. get: function () {
  12058. return this._animate;
  12059. },
  12060. set: function (value) {
  12061. this._animate = value;
  12062. },
  12063. enumerable: true,
  12064. configurable: true
  12065. });
  12066. return CustomProceduralTexture;
  12067. })(BABYLON.ProceduralTexture);
  12068. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12069. })(BABYLON || (BABYLON = {}));
  12070. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12071. var BABYLON;
  12072. (function (BABYLON) {
  12073. var MirrorTexture = (function (_super) {
  12074. __extends(MirrorTexture, _super);
  12075. function MirrorTexture(name, size, scene, generateMipMaps) {
  12076. var _this = this;
  12077. _super.call(this, name, size, scene, generateMipMaps, true);
  12078. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12079. this._transformMatrix = BABYLON.Matrix.Zero();
  12080. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12081. this.onBeforeRender = function () {
  12082. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12083. _this._savedViewMatrix = scene.getViewMatrix();
  12084. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12085. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12086. scene.clipPlane = _this.mirrorPlane;
  12087. scene.getEngine().cullBackFaces = false;
  12088. };
  12089. this.onAfterRender = function () {
  12090. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12091. scene.getEngine().cullBackFaces = true;
  12092. delete scene.clipPlane;
  12093. };
  12094. }
  12095. MirrorTexture.prototype.clone = function () {
  12096. var textureSize = this.getSize();
  12097. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12098. // Base texture
  12099. newTexture.hasAlpha = this.hasAlpha;
  12100. newTexture.level = this.level;
  12101. // Mirror Texture
  12102. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12103. newTexture.renderList = this.renderList.slice(0);
  12104. return newTexture;
  12105. };
  12106. return MirrorTexture;
  12107. })(BABYLON.RenderTargetTexture);
  12108. BABYLON.MirrorTexture = MirrorTexture;
  12109. })(BABYLON || (BABYLON = {}));
  12110. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12111. var BABYLON;
  12112. (function (BABYLON) {
  12113. var DynamicTexture = (function (_super) {
  12114. __extends(DynamicTexture, _super);
  12115. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12116. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12117. _super.call(this, null, scene, !generateMipMaps);
  12118. this.name = name;
  12119. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12120. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12121. this._generateMipMaps = generateMipMaps;
  12122. if (options.getContext) {
  12123. this._canvas = options;
  12124. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12125. } else {
  12126. this._canvas = document.createElement("canvas");
  12127. if (options.width) {
  12128. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12129. } else {
  12130. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12131. }
  12132. }
  12133. var textureSize = this.getSize();
  12134. this._canvas.width = textureSize.width;
  12135. this._canvas.height = textureSize.height;
  12136. this._context = this._canvas.getContext("2d");
  12137. }
  12138. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12139. get: function () {
  12140. return true;
  12141. },
  12142. enumerable: true,
  12143. configurable: true
  12144. });
  12145. DynamicTexture.prototype.scale = function (ratio) {
  12146. var textureSize = this.getSize();
  12147. textureSize.width *= ratio;
  12148. textureSize.height *= ratio;
  12149. this._canvas.width = textureSize.width;
  12150. this._canvas.height = textureSize.height;
  12151. this.releaseInternalTexture();
  12152. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12153. };
  12154. DynamicTexture.prototype.getContext = function () {
  12155. return this._context;
  12156. };
  12157. DynamicTexture.prototype.clear = function () {
  12158. var size = this.getSize();
  12159. this._context.fillRect(0, 0, size.width, size.height);
  12160. };
  12161. DynamicTexture.prototype.update = function (invertY) {
  12162. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12163. };
  12164. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12165. if (typeof update === "undefined") { update = true; }
  12166. var size = this.getSize();
  12167. if (clearColor) {
  12168. this._context.fillStyle = clearColor;
  12169. this._context.fillRect(0, 0, size.width, size.height);
  12170. }
  12171. this._context.font = font;
  12172. if (x === null) {
  12173. var textSize = this._context.measureText(text);
  12174. x = (size.width - textSize.width) / 2;
  12175. }
  12176. this._context.fillStyle = color;
  12177. this._context.fillText(text, x, y);
  12178. if (update) {
  12179. this.update(invertY);
  12180. }
  12181. };
  12182. DynamicTexture.prototype.clone = function () {
  12183. var textureSize = this.getSize();
  12184. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12185. // Base texture
  12186. newTexture.hasAlpha = this.hasAlpha;
  12187. newTexture.level = this.level;
  12188. // Dynamic Texture
  12189. newTexture.wrapU = this.wrapU;
  12190. newTexture.wrapV = this.wrapV;
  12191. return newTexture;
  12192. };
  12193. return DynamicTexture;
  12194. })(BABYLON.Texture);
  12195. BABYLON.DynamicTexture = DynamicTexture;
  12196. })(BABYLON || (BABYLON = {}));
  12197. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12198. var BABYLON;
  12199. (function (BABYLON) {
  12200. var VideoTexture = (function (_super) {
  12201. __extends(VideoTexture, _super);
  12202. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12203. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12204. var _this = this;
  12205. _super.call(this, null, scene, !generateMipMaps, invertY);
  12206. this._autoLaunch = true;
  12207. this.name = name;
  12208. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12209. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12210. var requiredWidth = size.width || size;
  12211. var requiredHeight = size.height || size;
  12212. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12213. var textureSize = this.getSize();
  12214. this.video = document.createElement("video");
  12215. this.video.width = textureSize.width;
  12216. this.video.height = textureSize.height;
  12217. this.video.autoplay = false;
  12218. this.video.loop = true;
  12219. this.video.addEventListener("canplaythrough", function () {
  12220. if (_this._texture) {
  12221. _this._texture.isReady = true;
  12222. }
  12223. });
  12224. urls.forEach(function (url) {
  12225. var source = document.createElement("source");
  12226. source.src = url;
  12227. _this.video.appendChild(source);
  12228. });
  12229. this._lastUpdate = BABYLON.Tools.Now;
  12230. }
  12231. VideoTexture.prototype.update = function () {
  12232. if (this._autoLaunch) {
  12233. this._autoLaunch = false;
  12234. this.video.play();
  12235. }
  12236. var now = BABYLON.Tools.Now;
  12237. if (now - this._lastUpdate < 15) {
  12238. return false;
  12239. }
  12240. this._lastUpdate = now;
  12241. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12242. return true;
  12243. };
  12244. return VideoTexture;
  12245. })(BABYLON.Texture);
  12246. BABYLON.VideoTexture = VideoTexture;
  12247. })(BABYLON || (BABYLON = {}));
  12248. //# sourceMappingURL=babylon.videoTexture.js.map
  12249. var BABYLON;
  12250. (function (BABYLON) {
  12251. var EffectFallbacks = (function () {
  12252. function EffectFallbacks() {
  12253. this._defines = {};
  12254. this._currentRank = 32;
  12255. this._maxRank = -1;
  12256. }
  12257. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12258. if (!this._defines[rank]) {
  12259. if (rank < this._currentRank) {
  12260. this._currentRank = rank;
  12261. }
  12262. if (rank > this._maxRank) {
  12263. this._maxRank = rank;
  12264. }
  12265. this._defines[rank] = new Array();
  12266. }
  12267. this._defines[rank].push(define);
  12268. };
  12269. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12270. get: function () {
  12271. return this._currentRank <= this._maxRank;
  12272. },
  12273. enumerable: true,
  12274. configurable: true
  12275. });
  12276. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12277. var currentFallbacks = this._defines[this._currentRank];
  12278. for (var index = 0; index < currentFallbacks.length; index++) {
  12279. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12280. }
  12281. this._currentRank++;
  12282. return currentDefines;
  12283. };
  12284. return EffectFallbacks;
  12285. })();
  12286. BABYLON.EffectFallbacks = EffectFallbacks;
  12287. var Effect = (function () {
  12288. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12289. var _this = this;
  12290. this._isReady = false;
  12291. this._compilationError = "";
  12292. this._valueCache = [];
  12293. this._engine = engine;
  12294. this.name = baseName;
  12295. this.defines = defines;
  12296. this._uniformsNames = uniformsNames.concat(samplers);
  12297. this._samplers = samplers;
  12298. this._attributesNames = attributesNames;
  12299. this.onError = onError;
  12300. this.onCompiled = onCompiled;
  12301. var vertexSource;
  12302. var fragmentSource;
  12303. if (baseName.vertexElement) {
  12304. vertexSource = document.getElementById(baseName.vertexElement);
  12305. if (!vertexSource) {
  12306. vertexSource = baseName.vertexElement;
  12307. }
  12308. } else {
  12309. vertexSource = baseName.vertex || baseName;
  12310. }
  12311. if (baseName.fragmentElement) {
  12312. fragmentSource = document.getElementById(baseName.fragmentElement);
  12313. if (!fragmentSource) {
  12314. fragmentSource = baseName.fragmentElement;
  12315. }
  12316. } else {
  12317. fragmentSource = baseName.fragment || baseName;
  12318. }
  12319. this._loadVertexShader(vertexSource, function (vertexCode) {
  12320. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12321. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12322. });
  12323. });
  12324. }
  12325. // Properties
  12326. Effect.prototype.isReady = function () {
  12327. return this._isReady;
  12328. };
  12329. Effect.prototype.getProgram = function () {
  12330. return this._program;
  12331. };
  12332. Effect.prototype.getAttributesNames = function () {
  12333. return this._attributesNames;
  12334. };
  12335. Effect.prototype.getAttributeLocation = function (index) {
  12336. return this._attributes[index];
  12337. };
  12338. Effect.prototype.getAttributeLocationByName = function (name) {
  12339. var index = this._attributesNames.indexOf(name);
  12340. return this._attributes[index];
  12341. };
  12342. Effect.prototype.getAttributesCount = function () {
  12343. return this._attributes.length;
  12344. };
  12345. Effect.prototype.getUniformIndex = function (uniformName) {
  12346. return this._uniformsNames.indexOf(uniformName);
  12347. };
  12348. Effect.prototype.getUniform = function (uniformName) {
  12349. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12350. };
  12351. Effect.prototype.getSamplers = function () {
  12352. return this._samplers;
  12353. };
  12354. Effect.prototype.getCompilationError = function () {
  12355. return this._compilationError;
  12356. };
  12357. // Methods
  12358. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12359. // DOM element ?
  12360. if (vertex instanceof HTMLElement) {
  12361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12362. callback(vertexCode);
  12363. return;
  12364. }
  12365. // Is in local store ?
  12366. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12367. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12368. return;
  12369. }
  12370. var vertexShaderUrl;
  12371. if (vertex[0] === ".") {
  12372. vertexShaderUrl = vertex;
  12373. } else {
  12374. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12375. }
  12376. // Vertex shader
  12377. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12378. };
  12379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12380. // DOM element ?
  12381. if (fragment instanceof HTMLElement) {
  12382. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12383. callback(fragmentCode);
  12384. return;
  12385. }
  12386. // Is in local store ?
  12387. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12388. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12389. return;
  12390. }
  12391. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12392. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12393. return;
  12394. }
  12395. var fragmentShaderUrl;
  12396. if (fragment[0] === ".") {
  12397. fragmentShaderUrl = fragment;
  12398. } else {
  12399. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12400. }
  12401. // Fragment shader
  12402. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12403. };
  12404. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12405. try {
  12406. var engine = this._engine;
  12407. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12408. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12409. this._attributes = engine.getAttributes(this._program, attributesNames);
  12410. for (var index = 0; index < this._samplers.length; index++) {
  12411. var sampler = this.getUniform(this._samplers[index]);
  12412. if (sampler == null) {
  12413. this._samplers.splice(index, 1);
  12414. index--;
  12415. }
  12416. }
  12417. engine.bindSamplers(this);
  12418. this._isReady = true;
  12419. if (this.onCompiled) {
  12420. this.onCompiled(this);
  12421. }
  12422. } catch (e) {
  12423. // Is it a problem with precision?
  12424. if (e.message.indexOf("highp") !== -1) {
  12425. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12426. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12427. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12428. return;
  12429. }
  12430. // Let's go through fallbacks then
  12431. if (fallbacks && fallbacks.isMoreFallbacks) {
  12432. defines = fallbacks.reduce(defines);
  12433. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12434. } else {
  12435. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12436. BABYLON.Tools.Error("Defines: " + defines);
  12437. BABYLON.Tools.Error("Error: " + e.message);
  12438. this._compilationError = e.message;
  12439. if (this.onError) {
  12440. this.onError(this, this._compilationError);
  12441. }
  12442. }
  12443. }
  12444. };
  12445. Effect.prototype._bindTexture = function (channel, texture) {
  12446. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12447. };
  12448. Effect.prototype.setTexture = function (channel, texture) {
  12449. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12450. };
  12451. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12452. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12453. };
  12454. //public _cacheMatrix(uniformName, matrix) {
  12455. // if (!this._valueCache[uniformName]) {
  12456. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12457. // }
  12458. // for (var index = 0; index < 16; index++) {
  12459. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12460. // }
  12461. //};
  12462. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12463. if (!this._valueCache[uniformName]) {
  12464. this._valueCache[uniformName] = [x, y];
  12465. return;
  12466. }
  12467. this._valueCache[uniformName][0] = x;
  12468. this._valueCache[uniformName][1] = y;
  12469. };
  12470. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12471. if (!this._valueCache[uniformName]) {
  12472. this._valueCache[uniformName] = [x, y, z];
  12473. return;
  12474. }
  12475. this._valueCache[uniformName][0] = x;
  12476. this._valueCache[uniformName][1] = y;
  12477. this._valueCache[uniformName][2] = z;
  12478. };
  12479. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12480. if (!this._valueCache[uniformName]) {
  12481. this._valueCache[uniformName] = [x, y, z, w];
  12482. return;
  12483. }
  12484. this._valueCache[uniformName][0] = x;
  12485. this._valueCache[uniformName][1] = y;
  12486. this._valueCache[uniformName][2] = z;
  12487. this._valueCache[uniformName][3] = w;
  12488. };
  12489. Effect.prototype.setArray = function (uniformName, array) {
  12490. this._engine.setArray(this.getUniform(uniformName), array);
  12491. return this;
  12492. };
  12493. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12494. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12495. return this;
  12496. };
  12497. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12498. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12499. // return;
  12500. //this._cacheMatrix(uniformName, matrix);
  12501. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12502. return this;
  12503. };
  12504. Effect.prototype.setFloat = function (uniformName, value) {
  12505. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12506. return this;
  12507. this._valueCache[uniformName] = value;
  12508. this._engine.setFloat(this.getUniform(uniformName), value);
  12509. return this;
  12510. };
  12511. Effect.prototype.setBool = function (uniformName, bool) {
  12512. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12513. return this;
  12514. this._valueCache[uniformName] = bool;
  12515. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12516. return this;
  12517. };
  12518. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12519. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12520. return this;
  12521. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12522. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12523. return this;
  12524. };
  12525. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12526. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12527. return this;
  12528. this._cacheFloat2(uniformName, x, y);
  12529. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12530. return this;
  12531. };
  12532. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12533. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12534. return this;
  12535. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12536. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12537. return this;
  12538. };
  12539. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12540. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12541. return this;
  12542. this._cacheFloat3(uniformName, x, y, z);
  12543. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12544. return this;
  12545. };
  12546. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12547. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12548. return this;
  12549. this._cacheFloat4(uniformName, x, y, z, w);
  12550. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12551. return this;
  12552. };
  12553. Effect.prototype.setColor3 = function (uniformName, color3) {
  12554. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12555. return this;
  12556. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12557. this._engine.setColor3(this.getUniform(uniformName), color3);
  12558. return this;
  12559. };
  12560. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12561. 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)
  12562. return this;
  12563. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12564. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12565. return this;
  12566. };
  12567. 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}",
  12568. 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}",
  12569. 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}",
  12570. 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}",
  12571. 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}",
  12572. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12573. 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}",
  12574. 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}",
  12575. 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;\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;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  12576. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\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\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;\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\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 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 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}",
  12577. 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}",
  12578. 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}",
  12579. 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}",
  12580. 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}",
  12581. 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}",
  12582. 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}",
  12583. 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}",
  12584. 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}",
  12585. 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}",
  12586. 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}",
  12587. 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}",
  12588. 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}",
  12589. 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}",
  12590. 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}",
  12591. 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}",
  12592. 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}",
  12593. 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}",
  12594. 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}",
  12595. 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}",
  12596. 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}",
  12597. 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}",
  12598. 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}",
  12599. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  12600. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  12601. 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}",
  12602. 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}",
  12603. 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}",
  12604. };
  12605. return Effect;
  12606. })();
  12607. BABYLON.Effect = Effect;
  12608. })(BABYLON || (BABYLON = {}));
  12609. //# sourceMappingURL=babylon.effect.js.map
  12610. var BABYLON;
  12611. (function (BABYLON) {
  12612. var Material = (function () {
  12613. function Material(name, scene, doNotAdd) {
  12614. this.name = name;
  12615. this.checkReadyOnEveryCall = true;
  12616. this.checkReadyOnlyOnce = false;
  12617. this.state = "";
  12618. this.alpha = 1.0;
  12619. this.backFaceCulling = true;
  12620. this._wasPreviouslyReady = false;
  12621. this._fillMode = Material.TriangleFillMode;
  12622. this.pointSize = 1.0;
  12623. this.id = name;
  12624. this._scene = scene;
  12625. if (!doNotAdd) {
  12626. scene.materials.push(this);
  12627. }
  12628. }
  12629. Object.defineProperty(Material, "TriangleFillMode", {
  12630. get: function () {
  12631. return Material._TriangleFillMode;
  12632. },
  12633. enumerable: true,
  12634. configurable: true
  12635. });
  12636. Object.defineProperty(Material, "WireFrameFillMode", {
  12637. get: function () {
  12638. return Material._WireFrameFillMode;
  12639. },
  12640. enumerable: true,
  12641. configurable: true
  12642. });
  12643. Object.defineProperty(Material, "PointFillMode", {
  12644. get: function () {
  12645. return Material._PointFillMode;
  12646. },
  12647. enumerable: true,
  12648. configurable: true
  12649. });
  12650. Object.defineProperty(Material.prototype, "wireframe", {
  12651. get: function () {
  12652. return this._fillMode === Material.WireFrameFillMode;
  12653. },
  12654. set: function (value) {
  12655. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12656. },
  12657. enumerable: true,
  12658. configurable: true
  12659. });
  12660. Object.defineProperty(Material.prototype, "pointsCloud", {
  12661. get: function () {
  12662. return this._fillMode === Material.PointFillMode;
  12663. },
  12664. set: function (value) {
  12665. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12666. },
  12667. enumerable: true,
  12668. configurable: true
  12669. });
  12670. Object.defineProperty(Material.prototype, "fillMode", {
  12671. get: function () {
  12672. return this._fillMode;
  12673. },
  12674. set: function (value) {
  12675. this._fillMode = value;
  12676. },
  12677. enumerable: true,
  12678. configurable: true
  12679. });
  12680. Material.prototype.isReady = function (mesh, useInstances) {
  12681. return true;
  12682. };
  12683. Material.prototype.getEffect = function () {
  12684. return this._effect;
  12685. };
  12686. Material.prototype.getScene = function () {
  12687. return this._scene;
  12688. };
  12689. Material.prototype.needAlphaBlending = function () {
  12690. return (this.alpha < 1.0);
  12691. };
  12692. Material.prototype.needAlphaTesting = function () {
  12693. return false;
  12694. };
  12695. Material.prototype.getAlphaTestTexture = function () {
  12696. return null;
  12697. };
  12698. Material.prototype.trackCreation = function (onCompiled, onError) {
  12699. };
  12700. Material.prototype._preBind = function () {
  12701. var engine = this._scene.getEngine();
  12702. engine.enableEffect(this._effect);
  12703. engine.setState(this.backFaceCulling);
  12704. };
  12705. Material.prototype.bind = function (world, mesh) {
  12706. this._scene._cachedMaterial = this;
  12707. if (this.onBind) {
  12708. this.onBind(this);
  12709. }
  12710. };
  12711. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12712. };
  12713. Material.prototype.unbind = function () {
  12714. };
  12715. Material.prototype.dispose = function (forceDisposeEffect) {
  12716. // Remove from scene
  12717. var index = this._scene.materials.indexOf(this);
  12718. this._scene.materials.splice(index, 1);
  12719. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12720. if (forceDisposeEffect && this._effect) {
  12721. this._scene.getEngine()._releaseEffect(this._effect);
  12722. this._effect = null;
  12723. }
  12724. // Callback
  12725. if (this.onDispose) {
  12726. this.onDispose();
  12727. }
  12728. };
  12729. Material._TriangleFillMode = 0;
  12730. Material._WireFrameFillMode = 1;
  12731. Material._PointFillMode = 2;
  12732. return Material;
  12733. })();
  12734. BABYLON.Material = Material;
  12735. })(BABYLON || (BABYLON = {}));
  12736. //# sourceMappingURL=babylon.material.js.map
  12737. var BABYLON;
  12738. (function (BABYLON) {
  12739. var maxSimultaneousLights = 4;
  12740. var FresnelParameters = (function () {
  12741. function FresnelParameters() {
  12742. this.isEnabled = true;
  12743. this.leftColor = BABYLON.Color3.White();
  12744. this.rightColor = BABYLON.Color3.Black();
  12745. this.bias = 0;
  12746. this.power = 1;
  12747. }
  12748. return FresnelParameters;
  12749. })();
  12750. BABYLON.FresnelParameters = FresnelParameters;
  12751. var StandardMaterial = (function (_super) {
  12752. __extends(StandardMaterial, _super);
  12753. function StandardMaterial(name, scene) {
  12754. var _this = this;
  12755. _super.call(this, name, scene);
  12756. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12757. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12758. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12759. this.specularPower = 64;
  12760. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12761. this.useAlphaFromDiffuseTexture = false;
  12762. this.useSpecularOverAlpha = true;
  12763. this.fogEnabled = true;
  12764. this._cachedDefines = null;
  12765. this._renderTargets = new BABYLON.SmartArray(16);
  12766. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12767. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12768. this._scaledDiffuse = new BABYLON.Color3();
  12769. this._scaledSpecular = new BABYLON.Color3();
  12770. this.getRenderTargetTextures = function () {
  12771. _this._renderTargets.reset();
  12772. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12773. _this._renderTargets.push(_this.reflectionTexture);
  12774. }
  12775. return _this._renderTargets;
  12776. };
  12777. }
  12778. StandardMaterial.prototype.needAlphaBlending = function () {
  12779. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12780. };
  12781. StandardMaterial.prototype.needAlphaTesting = function () {
  12782. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12783. };
  12784. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12785. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12786. };
  12787. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12788. return this.diffuseTexture;
  12789. };
  12790. // Methods
  12791. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12792. if (this.checkReadyOnlyOnce) {
  12793. if (this._wasPreviouslyReady) {
  12794. return true;
  12795. }
  12796. }
  12797. var scene = this.getScene();
  12798. if (!this.checkReadyOnEveryCall) {
  12799. if (this._renderId === scene.getRenderId()) {
  12800. return true;
  12801. }
  12802. }
  12803. var engine = scene.getEngine();
  12804. var defines = [];
  12805. var fallbacks = new BABYLON.EffectFallbacks();
  12806. // Textures
  12807. if (scene.texturesEnabled) {
  12808. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12809. if (!this.diffuseTexture.isReady()) {
  12810. return false;
  12811. } else {
  12812. defines.push("#define DIFFUSE");
  12813. }
  12814. }
  12815. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12816. if (!this.ambientTexture.isReady()) {
  12817. return false;
  12818. } else {
  12819. defines.push("#define AMBIENT");
  12820. }
  12821. }
  12822. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12823. if (!this.opacityTexture.isReady()) {
  12824. return false;
  12825. } else {
  12826. defines.push("#define OPACITY");
  12827. if (this.opacityTexture.getAlphaFromRGB) {
  12828. defines.push("#define OPACITYRGB");
  12829. }
  12830. }
  12831. }
  12832. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12833. if (!this.reflectionTexture.isReady()) {
  12834. return false;
  12835. } else {
  12836. defines.push("#define REFLECTION");
  12837. fallbacks.addFallback(0, "REFLECTION");
  12838. }
  12839. }
  12840. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12841. if (!this.emissiveTexture.isReady()) {
  12842. return false;
  12843. } else {
  12844. defines.push("#define EMISSIVE");
  12845. }
  12846. }
  12847. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12848. if (!this.specularTexture.isReady()) {
  12849. return false;
  12850. } else {
  12851. defines.push("#define SPECULAR");
  12852. fallbacks.addFallback(0, "SPECULAR");
  12853. }
  12854. }
  12855. }
  12856. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12857. if (!this.bumpTexture.isReady()) {
  12858. return false;
  12859. } else {
  12860. defines.push("#define BUMP");
  12861. fallbacks.addFallback(0, "BUMP");
  12862. }
  12863. }
  12864. // Effect
  12865. if (this.useSpecularOverAlpha) {
  12866. defines.push("#define SPECULAROVERALPHA");
  12867. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12868. }
  12869. if (scene.clipPlane) {
  12870. defines.push("#define CLIPPLANE");
  12871. }
  12872. if (engine.getAlphaTesting()) {
  12873. defines.push("#define ALPHATEST");
  12874. }
  12875. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12876. defines.push("#define ALPHAFROMDIFFUSE");
  12877. }
  12878. // Point size
  12879. if (this.pointsCloud || scene.forcePointsCloud) {
  12880. defines.push("#define POINTSIZE");
  12881. }
  12882. // Fog
  12883. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12884. defines.push("#define FOG");
  12885. fallbacks.addFallback(1, "FOG");
  12886. }
  12887. var shadowsActivated = false;
  12888. var lightIndex = 0;
  12889. if (scene.lightsEnabled) {
  12890. for (var index = 0; index < scene.lights.length; index++) {
  12891. var light = scene.lights[index];
  12892. if (!light.isEnabled()) {
  12893. continue;
  12894. }
  12895. // Excluded check
  12896. if (light._excludedMeshesIds.length > 0) {
  12897. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12898. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12899. if (excludedMesh) {
  12900. light.excludedMeshes.push(excludedMesh);
  12901. }
  12902. }
  12903. light._excludedMeshesIds = [];
  12904. }
  12905. // Included check
  12906. if (light._includedOnlyMeshesIds.length > 0) {
  12907. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12908. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12909. if (includedOnlyMesh) {
  12910. light.includedOnlyMeshes.push(includedOnlyMesh);
  12911. }
  12912. }
  12913. light._includedOnlyMeshesIds = [];
  12914. }
  12915. if (!light.canAffectMesh(mesh)) {
  12916. continue;
  12917. }
  12918. defines.push("#define LIGHT" + lightIndex);
  12919. if (lightIndex > 0) {
  12920. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12921. }
  12922. var type;
  12923. if (light instanceof BABYLON.SpotLight) {
  12924. type = "#define SPOTLIGHT" + lightIndex;
  12925. } else if (light instanceof BABYLON.HemisphericLight) {
  12926. type = "#define HEMILIGHT" + lightIndex;
  12927. } else {
  12928. type = "#define POINTDIRLIGHT" + lightIndex;
  12929. }
  12930. defines.push(type);
  12931. if (lightIndex > 0) {
  12932. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12933. }
  12934. // Shadows
  12935. if (scene.shadowsEnabled) {
  12936. var shadowGenerator = light.getShadowGenerator();
  12937. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12938. defines.push("#define SHADOW" + lightIndex);
  12939. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12940. if (!shadowsActivated) {
  12941. defines.push("#define SHADOWS");
  12942. shadowsActivated = true;
  12943. }
  12944. if (shadowGenerator.useVarianceShadowMap) {
  12945. defines.push("#define SHADOWVSM" + lightIndex);
  12946. if (lightIndex > 0) {
  12947. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12948. }
  12949. }
  12950. if (shadowGenerator.usePoissonSampling) {
  12951. defines.push("#define SHADOWPCF" + lightIndex);
  12952. if (lightIndex > 0) {
  12953. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  12954. }
  12955. }
  12956. }
  12957. }
  12958. lightIndex++;
  12959. if (lightIndex === maxSimultaneousLights)
  12960. break;
  12961. }
  12962. }
  12963. if (StandardMaterial.FresnelEnabled) {
  12964. // Fresnel
  12965. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12966. var fresnelRank = 1;
  12967. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12968. defines.push("#define DIFFUSEFRESNEL");
  12969. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  12970. fresnelRank++;
  12971. }
  12972. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12973. defines.push("#define OPACITYFRESNEL");
  12974. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  12975. fresnelRank++;
  12976. }
  12977. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12978. defines.push("#define REFLECTIONFRESNEL");
  12979. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  12980. fresnelRank++;
  12981. }
  12982. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12983. defines.push("#define EMISSIVEFRESNEL");
  12984. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  12985. fresnelRank++;
  12986. }
  12987. defines.push("#define FRESNEL");
  12988. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  12989. }
  12990. }
  12991. // Attribs
  12992. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  12993. if (mesh) {
  12994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12995. attribs.push(BABYLON.VertexBuffer.UVKind);
  12996. defines.push("#define UV1");
  12997. }
  12998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12999. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13000. defines.push("#define UV2");
  13001. }
  13002. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13003. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13004. defines.push("#define VERTEXCOLOR");
  13005. if (mesh.hasVertexAlpha) {
  13006. defines.push("#define VERTEXALPHA");
  13007. }
  13008. }
  13009. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13010. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13011. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13012. defines.push("#define BONES");
  13013. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13014. defines.push("#define BONES4");
  13015. fallbacks.addFallback(0, "BONES4");
  13016. }
  13017. // Instances
  13018. if (useInstances) {
  13019. defines.push("#define INSTANCES");
  13020. attribs.push("world0");
  13021. attribs.push("world1");
  13022. attribs.push("world2");
  13023. attribs.push("world3");
  13024. }
  13025. }
  13026. // Get correct effect
  13027. var join = defines.join("\n");
  13028. if (this._cachedDefines !== join) {
  13029. this._cachedDefines = join;
  13030. scene.resetCachedMaterial();
  13031. // Legacy browser patch
  13032. var shaderName = "default";
  13033. if (!scene.getEngine().getCaps().standardDerivatives) {
  13034. shaderName = "legacydefault";
  13035. }
  13036. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  13037. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  13038. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  13039. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  13040. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  13041. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  13042. "vFogInfos", "vFogColor", "pointSize",
  13043. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  13044. "mBones",
  13045. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  13046. "darkness0", "darkness1", "darkness2", "darkness3",
  13047. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  13048. ], [
  13049. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  13050. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  13051. ], join, fallbacks, this.onCompiled, this.onError);
  13052. }
  13053. if (!this._effect.isReady()) {
  13054. return false;
  13055. }
  13056. this._renderId = scene.getRenderId();
  13057. this._wasPreviouslyReady = true;
  13058. return true;
  13059. };
  13060. StandardMaterial.prototype.unbind = function () {
  13061. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13062. this._effect.setTexture("reflection2DSampler", null);
  13063. }
  13064. };
  13065. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13066. this._effect.setMatrix("world", world);
  13067. };
  13068. StandardMaterial.prototype.bind = function (world, mesh) {
  13069. var scene = this.getScene();
  13070. // Matrices
  13071. this.bindOnlyWorldMatrix(world);
  13072. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13073. // Bones
  13074. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13075. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13076. }
  13077. if (scene.getCachedMaterial() !== this) {
  13078. if (StandardMaterial.FresnelEnabled) {
  13079. // Fresnel
  13080. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13081. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13082. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13083. }
  13084. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13085. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13086. }
  13087. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13088. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13089. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13090. }
  13091. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13092. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13093. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13094. }
  13095. }
  13096. // Textures
  13097. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13098. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13099. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13100. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13101. }
  13102. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13103. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13104. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13105. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13106. }
  13107. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13108. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13109. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13110. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13111. }
  13112. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13113. if (this.reflectionTexture.isCube) {
  13114. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13115. } else {
  13116. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13117. }
  13118. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13119. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13120. }
  13121. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13122. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13123. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13124. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13125. }
  13126. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13127. this._effect.setTexture("specularSampler", this.specularTexture);
  13128. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13129. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13130. }
  13131. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13132. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13133. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13134. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13135. }
  13136. // Clip plane
  13137. if (scene.clipPlane) {
  13138. var clipPlane = scene.clipPlane;
  13139. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13140. }
  13141. // Point size
  13142. if (this.pointsCloud) {
  13143. this._effect.setFloat("pointSize", this.pointSize);
  13144. }
  13145. // Colors
  13146. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13147. // Scaling down color according to emissive
  13148. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13149. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13150. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13151. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13152. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13153. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13154. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13155. }
  13156. // Scaling down color according to emissive
  13157. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13158. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13159. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13160. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13161. if (scene.lightsEnabled) {
  13162. var lightIndex = 0;
  13163. for (var index = 0; index < scene.lights.length; index++) {
  13164. var light = scene.lights[index];
  13165. if (!light.isEnabled()) {
  13166. continue;
  13167. }
  13168. if (!light.canAffectMesh(mesh)) {
  13169. continue;
  13170. }
  13171. if (light instanceof BABYLON.PointLight) {
  13172. // Point Light
  13173. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13174. } else if (light instanceof BABYLON.DirectionalLight) {
  13175. // Directional Light
  13176. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13177. } else if (light instanceof BABYLON.SpotLight) {
  13178. // Spot Light
  13179. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13180. } else if (light instanceof BABYLON.HemisphericLight) {
  13181. // Hemispheric Light
  13182. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13183. }
  13184. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13185. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13186. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13187. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13188. // Shadows
  13189. if (scene.shadowsEnabled) {
  13190. var shadowGenerator = light.getShadowGenerator();
  13191. if (mesh.receiveShadows && shadowGenerator) {
  13192. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13193. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13194. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13195. }
  13196. }
  13197. lightIndex++;
  13198. if (lightIndex === maxSimultaneousLights)
  13199. break;
  13200. }
  13201. }
  13202. // View
  13203. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13204. this._effect.setMatrix("view", scene.getViewMatrix());
  13205. }
  13206. // Fog
  13207. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13208. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13209. this._effect.setColor3("vFogColor", scene.fogColor);
  13210. }
  13211. _super.prototype.bind.call(this, world, mesh);
  13212. };
  13213. StandardMaterial.prototype.getAnimatables = function () {
  13214. var results = [];
  13215. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13216. results.push(this.diffuseTexture);
  13217. }
  13218. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13219. results.push(this.ambientTexture);
  13220. }
  13221. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13222. results.push(this.opacityTexture);
  13223. }
  13224. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13225. results.push(this.reflectionTexture);
  13226. }
  13227. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13228. results.push(this.emissiveTexture);
  13229. }
  13230. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13231. results.push(this.specularTexture);
  13232. }
  13233. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13234. results.push(this.bumpTexture);
  13235. }
  13236. return results;
  13237. };
  13238. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13239. if (this.diffuseTexture) {
  13240. this.diffuseTexture.dispose();
  13241. }
  13242. if (this.ambientTexture) {
  13243. this.ambientTexture.dispose();
  13244. }
  13245. if (this.opacityTexture) {
  13246. this.opacityTexture.dispose();
  13247. }
  13248. if (this.reflectionTexture) {
  13249. this.reflectionTexture.dispose();
  13250. }
  13251. if (this.emissiveTexture) {
  13252. this.emissiveTexture.dispose();
  13253. }
  13254. if (this.specularTexture) {
  13255. this.specularTexture.dispose();
  13256. }
  13257. if (this.bumpTexture) {
  13258. this.bumpTexture.dispose();
  13259. }
  13260. _super.prototype.dispose.call(this, forceDisposeEffect);
  13261. };
  13262. StandardMaterial.prototype.clone = function (name) {
  13263. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13264. // Base material
  13265. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13266. newStandardMaterial.alpha = this.alpha;
  13267. newStandardMaterial.fillMode = this.fillMode;
  13268. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13269. // Standard material
  13270. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13271. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13272. }
  13273. if (this.ambientTexture && this.ambientTexture.clone) {
  13274. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13275. }
  13276. if (this.opacityTexture && this.opacityTexture.clone) {
  13277. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13278. }
  13279. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13280. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13281. }
  13282. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13283. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13284. }
  13285. if (this.specularTexture && this.specularTexture.clone) {
  13286. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13287. }
  13288. if (this.bumpTexture && this.bumpTexture.clone) {
  13289. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13290. }
  13291. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13292. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13293. newStandardMaterial.specularColor = this.specularColor.clone();
  13294. newStandardMaterial.specularPower = this.specularPower;
  13295. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13296. return newStandardMaterial;
  13297. };
  13298. StandardMaterial.DiffuseTextureEnabled = true;
  13299. StandardMaterial.AmbientTextureEnabled = true;
  13300. StandardMaterial.OpacityTextureEnabled = true;
  13301. StandardMaterial.ReflectionTextureEnabled = true;
  13302. StandardMaterial.EmissiveTextureEnabled = true;
  13303. StandardMaterial.SpecularTextureEnabled = true;
  13304. StandardMaterial.BumpTextureEnabled = true;
  13305. StandardMaterial.FresnelEnabled = true;
  13306. return StandardMaterial;
  13307. })(BABYLON.Material);
  13308. BABYLON.StandardMaterial = StandardMaterial;
  13309. })(BABYLON || (BABYLON = {}));
  13310. //# sourceMappingURL=babylon.standardMaterial.js.map
  13311. var BABYLON;
  13312. (function (BABYLON) {
  13313. var MultiMaterial = (function (_super) {
  13314. __extends(MultiMaterial, _super);
  13315. function MultiMaterial(name, scene) {
  13316. _super.call(this, name, scene, true);
  13317. this.subMaterials = new Array();
  13318. scene.multiMaterials.push(this);
  13319. }
  13320. // Properties
  13321. MultiMaterial.prototype.getSubMaterial = function (index) {
  13322. if (index < 0 || index >= this.subMaterials.length) {
  13323. return this.getScene().defaultMaterial;
  13324. }
  13325. return this.subMaterials[index];
  13326. };
  13327. // Methods
  13328. MultiMaterial.prototype.isReady = function (mesh) {
  13329. for (var index = 0; index < this.subMaterials.length; index++) {
  13330. var subMaterial = this.subMaterials[index];
  13331. if (subMaterial) {
  13332. if (!this.subMaterials[index].isReady(mesh)) {
  13333. return false;
  13334. }
  13335. }
  13336. }
  13337. return true;
  13338. };
  13339. return MultiMaterial;
  13340. })(BABYLON.Material);
  13341. BABYLON.MultiMaterial = MultiMaterial;
  13342. })(BABYLON || (BABYLON = {}));
  13343. //# sourceMappingURL=babylon.multiMaterial.js.map
  13344. var BABYLON;
  13345. (function (BABYLON) {
  13346. var Database = (function () {
  13347. function Database(urlToScene, callbackManifestChecked) {
  13348. // Handling various flavors of prefixed version of IndexedDB
  13349. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13350. this.callbackManifestChecked = callbackManifestChecked;
  13351. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13352. this.db = null;
  13353. this.enableSceneOffline = false;
  13354. this.enableTexturesOffline = false;
  13355. this.manifestVersionFound = 0;
  13356. this.mustUpdateRessources = false;
  13357. this.hasReachedQuota = false;
  13358. this.checkManifestFile();
  13359. }
  13360. Database.prototype.checkManifestFile = function () {
  13361. var _this = this;
  13362. function noManifestFile() {
  13363. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13364. that.enableSceneOffline = false;
  13365. that.enableTexturesOffline = false;
  13366. that.callbackManifestChecked(false);
  13367. }
  13368. var that = this;
  13369. var manifestURL = this.currentSceneUrl + ".manifest";
  13370. var xhr = new XMLHttpRequest();
  13371. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13372. xhr.open("GET", manifestURLTimeStamped, true);
  13373. xhr.addEventListener("load", function () {
  13374. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13375. try {
  13376. var manifestFile = JSON.parse(xhr.response);
  13377. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13378. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13379. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13380. _this.manifestVersionFound = manifestFile.version;
  13381. }
  13382. if (_this.callbackManifestChecked) {
  13383. _this.callbackManifestChecked(true);
  13384. }
  13385. } catch (ex) {
  13386. noManifestFile();
  13387. }
  13388. } else {
  13389. noManifestFile();
  13390. }
  13391. }, false);
  13392. xhr.addEventListener("error", function (event) {
  13393. noManifestFile();
  13394. }, false);
  13395. try {
  13396. xhr.send();
  13397. } catch (ex) {
  13398. BABYLON.Tools.Error("Error on XHR send request.");
  13399. that.callbackManifestChecked(false);
  13400. }
  13401. };
  13402. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13403. var _this = this;
  13404. function handleError() {
  13405. that.isSupported = false;
  13406. if (errorCallback)
  13407. errorCallback();
  13408. }
  13409. var that = this;
  13410. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13411. // Your browser doesn't support IndexedDB
  13412. this.isSupported = false;
  13413. if (errorCallback)
  13414. errorCallback();
  13415. } else {
  13416. // If the DB hasn't been opened or created yet
  13417. if (!this.db) {
  13418. this.hasReachedQuota = false;
  13419. this.isSupported = true;
  13420. var request = this.idbFactory.open("babylonjs", 1);
  13421. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13422. request.onerror = function (event) {
  13423. handleError();
  13424. };
  13425. // executes when a version change transaction cannot complete due to other active transactions
  13426. request.onblocked = function (event) {
  13427. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13428. handleError();
  13429. };
  13430. // DB has been opened successfully
  13431. request.onsuccess = function (event) {
  13432. _this.db = request.result;
  13433. successCallback();
  13434. };
  13435. // Initialization of the DB. Creating Scenes & Textures stores
  13436. request.onupgradeneeded = function (event) {
  13437. _this.db = (event.target).result;
  13438. try {
  13439. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13440. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13441. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13442. } catch (ex) {
  13443. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13444. handleError();
  13445. }
  13446. };
  13447. } else {
  13448. if (successCallback)
  13449. successCallback();
  13450. }
  13451. }
  13452. };
  13453. Database.prototype.loadImageFromDB = function (url, image) {
  13454. var _this = this;
  13455. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13456. var saveAndLoadImage = function () {
  13457. if (!_this.hasReachedQuota && _this.db !== null) {
  13458. // the texture is not yet in the DB, let's try to save it
  13459. _this._saveImageIntoDBAsync(completeURL, image);
  13460. } else {
  13461. image.src = url;
  13462. }
  13463. };
  13464. if (!this.mustUpdateRessources) {
  13465. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13466. } else {
  13467. saveAndLoadImage();
  13468. }
  13469. };
  13470. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13471. if (this.isSupported && this.db !== null) {
  13472. var texture;
  13473. var transaction = this.db.transaction(["textures"]);
  13474. transaction.onabort = function (event) {
  13475. image.src = url;
  13476. };
  13477. transaction.oncomplete = function (event) {
  13478. var blobTextureURL;
  13479. if (texture) {
  13480. var URL = window.URL || window.webkitURL;
  13481. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13482. image.onerror = function () {
  13483. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13484. image.src = url;
  13485. };
  13486. image.src = blobTextureURL;
  13487. } else {
  13488. notInDBCallback();
  13489. }
  13490. };
  13491. var getRequest = transaction.objectStore("textures").get(url);
  13492. getRequest.onsuccess = function (event) {
  13493. texture = (event.target).result;
  13494. };
  13495. getRequest.onerror = function (event) {
  13496. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13497. image.src = url;
  13498. };
  13499. } else {
  13500. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13501. image.src = url;
  13502. }
  13503. };
  13504. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13505. var _this = this;
  13506. if (this.isSupported) {
  13507. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13508. var generateBlobUrl = function () {
  13509. var blobTextureURL;
  13510. if (blob) {
  13511. var URL = window.URL || window.webkitURL;
  13512. try {
  13513. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13514. } catch (ex) {
  13515. blobTextureURL = URL.createObjectURL(blob);
  13516. }
  13517. }
  13518. image.src = blobTextureURL;
  13519. };
  13520. if (BABYLON.Database.isUASupportingBlobStorage) {
  13521. var xhr = new XMLHttpRequest(), blob;
  13522. xhr.open("GET", url, true);
  13523. xhr.responseType = "blob";
  13524. xhr.addEventListener("load", function () {
  13525. if (xhr.status === 200) {
  13526. // Blob as response (XHR2)
  13527. blob = xhr.response;
  13528. var transaction = _this.db.transaction(["textures"], "readwrite");
  13529. // the transaction could abort because of a QuotaExceededError error
  13530. transaction.onabort = function (event) {
  13531. try {
  13532. if (event.srcElement.error.name === "QuotaExceededError") {
  13533. this.hasReachedQuota = true;
  13534. }
  13535. } catch (ex) {
  13536. }
  13537. generateBlobUrl();
  13538. };
  13539. transaction.oncomplete = function (event) {
  13540. generateBlobUrl();
  13541. };
  13542. var newTexture = { textureUrl: url, data: blob };
  13543. try {
  13544. // Put the blob into the dabase
  13545. var addRequest = transaction.objectStore("textures").put(newTexture);
  13546. addRequest.onsuccess = function (event) {
  13547. };
  13548. addRequest.onerror = function (event) {
  13549. generateBlobUrl();
  13550. };
  13551. } catch (ex) {
  13552. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13553. if (ex.code === 25) {
  13554. BABYLON.Database.isUASupportingBlobStorage = false;
  13555. }
  13556. image.src = url;
  13557. }
  13558. } else {
  13559. image.src = url;
  13560. }
  13561. }, false);
  13562. xhr.addEventListener("error", function (event) {
  13563. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13564. image.src = url;
  13565. }, false);
  13566. xhr.send();
  13567. } else {
  13568. image.src = url;
  13569. }
  13570. } else {
  13571. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13572. image.src = url;
  13573. }
  13574. };
  13575. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13576. var _this = this;
  13577. var updateVersion = function (event) {
  13578. // the version is not yet in the DB or we need to update it
  13579. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13580. };
  13581. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13582. };
  13583. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13584. var _this = this;
  13585. if (this.isSupported) {
  13586. var version;
  13587. try {
  13588. var transaction = this.db.transaction(["versions"]);
  13589. transaction.oncomplete = function (event) {
  13590. if (version) {
  13591. // If the version in the JSON file is > than the version in DB
  13592. if (_this.manifestVersionFound > version.data) {
  13593. _this.mustUpdateRessources = true;
  13594. updateInDBCallback();
  13595. } else {
  13596. callback(version.data);
  13597. }
  13598. } else {
  13599. _this.mustUpdateRessources = true;
  13600. updateInDBCallback();
  13601. }
  13602. };
  13603. transaction.onabort = function (event) {
  13604. callback(-1);
  13605. };
  13606. var getRequest = transaction.objectStore("versions").get(url);
  13607. getRequest.onsuccess = function (event) {
  13608. version = (event.target).result;
  13609. };
  13610. getRequest.onerror = function (event) {
  13611. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13612. callback(-1);
  13613. };
  13614. } catch (ex) {
  13615. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13616. callback(-1);
  13617. }
  13618. } else {
  13619. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13620. callback(-1);
  13621. }
  13622. };
  13623. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13624. var _this = this;
  13625. if (this.isSupported && !this.hasReachedQuota) {
  13626. try {
  13627. // Open a transaction to the database
  13628. var transaction = this.db.transaction(["versions"], "readwrite");
  13629. // the transaction could abort because of a QuotaExceededError error
  13630. transaction.onabort = function (event) {
  13631. try {
  13632. if (event.srcElement.error.name === "QuotaExceededError") {
  13633. _this.hasReachedQuota = true;
  13634. }
  13635. } catch (ex) {
  13636. }
  13637. callback(-1);
  13638. };
  13639. transaction.oncomplete = function (event) {
  13640. callback(_this.manifestVersionFound);
  13641. };
  13642. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13643. // Put the scene into the database
  13644. var addRequest = transaction.objectStore("versions").put(newVersion);
  13645. addRequest.onsuccess = function (event) {
  13646. };
  13647. addRequest.onerror = function (event) {
  13648. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13649. };
  13650. } catch (ex) {
  13651. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13652. callback(-1);
  13653. }
  13654. } else {
  13655. callback(-1);
  13656. }
  13657. };
  13658. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13659. var _this = this;
  13660. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13661. var saveAndLoadFile = function (event) {
  13662. // the scene is not yet in the DB, let's try to save it
  13663. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13664. };
  13665. this._checkVersionFromDB(completeUrl, function (version) {
  13666. if (version !== -1) {
  13667. if (!_this.mustUpdateRessources) {
  13668. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13669. } else {
  13670. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13671. }
  13672. } else {
  13673. errorCallback();
  13674. }
  13675. });
  13676. };
  13677. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13678. if (this.isSupported) {
  13679. var targetStore;
  13680. if (url.indexOf(".babylon") !== -1) {
  13681. targetStore = "scenes";
  13682. } else {
  13683. targetStore = "textures";
  13684. }
  13685. var file;
  13686. var transaction = this.db.transaction([targetStore]);
  13687. transaction.oncomplete = function (event) {
  13688. if (file) {
  13689. callback(file.data);
  13690. } else {
  13691. notInDBCallback();
  13692. }
  13693. };
  13694. transaction.onabort = function (event) {
  13695. notInDBCallback();
  13696. };
  13697. var getRequest = transaction.objectStore(targetStore).get(url);
  13698. getRequest.onsuccess = function (event) {
  13699. file = (event.target).result;
  13700. };
  13701. getRequest.onerror = function (event) {
  13702. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13703. notInDBCallback();
  13704. };
  13705. } else {
  13706. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13707. callback();
  13708. }
  13709. };
  13710. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13711. var _this = this;
  13712. if (this.isSupported) {
  13713. var targetStore;
  13714. if (url.indexOf(".babylon") !== -1) {
  13715. targetStore = "scenes";
  13716. } else {
  13717. targetStore = "textures";
  13718. }
  13719. // Create XHR
  13720. var xhr = new XMLHttpRequest(), fileData;
  13721. xhr.open("GET", url, true);
  13722. if (useArrayBuffer) {
  13723. xhr.responseType = "arraybuffer";
  13724. }
  13725. xhr.onprogress = progressCallback;
  13726. xhr.addEventListener("load", function () {
  13727. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13728. // Blob as response (XHR2)
  13729. //fileData = xhr.responseText;
  13730. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13731. if (!_this.hasReachedQuota) {
  13732. // Open a transaction to the database
  13733. var transaction = _this.db.transaction([targetStore], "readwrite");
  13734. // the transaction could abort because of a QuotaExceededError error
  13735. transaction.onabort = function (event) {
  13736. try {
  13737. if (event.srcElement.error.name === "QuotaExceededError") {
  13738. this.hasReachedQuota = true;
  13739. }
  13740. } catch (ex) {
  13741. }
  13742. callback(fileData);
  13743. };
  13744. transaction.oncomplete = function (event) {
  13745. callback(fileData);
  13746. };
  13747. var newFile;
  13748. if (targetStore === "scenes") {
  13749. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13750. } else {
  13751. newFile = { textureUrl: url, data: fileData };
  13752. }
  13753. try {
  13754. // Put the scene into the database
  13755. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13756. addRequest.onsuccess = function (event) {
  13757. };
  13758. addRequest.onerror = function (event) {
  13759. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13760. };
  13761. } catch (ex) {
  13762. callback(fileData);
  13763. }
  13764. } else {
  13765. callback(fileData);
  13766. }
  13767. } else {
  13768. callback();
  13769. }
  13770. }, false);
  13771. xhr.addEventListener("error", function (event) {
  13772. BABYLON.Tools.Error("error on XHR request.");
  13773. callback();
  13774. }, false);
  13775. xhr.send();
  13776. } else {
  13777. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13778. callback();
  13779. }
  13780. };
  13781. Database.isUASupportingBlobStorage = true;
  13782. Database.parseURL = function (url) {
  13783. var a = document.createElement('a');
  13784. a.href = url;
  13785. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13786. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13787. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13788. return absLocation;
  13789. };
  13790. Database.ReturnFullUrlLocation = function (url) {
  13791. if (url.indexOf("http:/") === -1) {
  13792. return (BABYLON.Database.parseURL(window.location.href) + url);
  13793. } else {
  13794. return url;
  13795. }
  13796. };
  13797. return Database;
  13798. })();
  13799. BABYLON.Database = Database;
  13800. })(BABYLON || (BABYLON = {}));
  13801. //# sourceMappingURL=babylon.database.js.map
  13802. var BABYLON;
  13803. (function (BABYLON) {
  13804. var SpriteManager = (function () {
  13805. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13806. this.name = name;
  13807. this.cellSize = cellSize;
  13808. this.sprites = new Array();
  13809. this.renderingGroupId = 0;
  13810. this.fogEnabled = true;
  13811. this._vertexDeclaration = [3, 4, 4, 4];
  13812. this._vertexStrideSize = 15 * 4;
  13813. this._capacity = capacity;
  13814. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13815. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13816. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13817. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13818. this._scene = scene;
  13819. this._scene.spriteManagers.push(this);
  13820. // VBO
  13821. this._vertexDeclaration = [3, 4, 4, 4];
  13822. this._vertexStrideSize = 15 * 4;
  13823. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13824. var indices = [];
  13825. var index = 0;
  13826. for (var count = 0; count < capacity; count++) {
  13827. indices.push(index);
  13828. indices.push(index + 1);
  13829. indices.push(index + 2);
  13830. indices.push(index);
  13831. indices.push(index + 2);
  13832. indices.push(index + 3);
  13833. index += 4;
  13834. }
  13835. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13836. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13837. // Effects
  13838. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13839. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13840. }
  13841. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13842. var arrayOffset = index * 15;
  13843. if (offsetX == 0)
  13844. offsetX = this._epsilon;
  13845. else if (offsetX == 1)
  13846. offsetX = 1 - this._epsilon;
  13847. if (offsetY == 0)
  13848. offsetY = this._epsilon;
  13849. else if (offsetY == 1)
  13850. offsetY = 1 - this._epsilon;
  13851. this._vertices[arrayOffset] = sprite.position.x;
  13852. this._vertices[arrayOffset + 1] = sprite.position.y;
  13853. this._vertices[arrayOffset + 2] = sprite.position.z;
  13854. this._vertices[arrayOffset + 3] = sprite.angle;
  13855. this._vertices[arrayOffset + 4] = sprite.size;
  13856. this._vertices[arrayOffset + 5] = offsetX;
  13857. this._vertices[arrayOffset + 6] = offsetY;
  13858. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13859. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13860. var offset = (sprite.cellIndex / rowSize) >> 0;
  13861. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13862. this._vertices[arrayOffset + 10] = offset;
  13863. // Color
  13864. this._vertices[arrayOffset + 11] = sprite.color.r;
  13865. this._vertices[arrayOffset + 12] = sprite.color.g;
  13866. this._vertices[arrayOffset + 13] = sprite.color.b;
  13867. this._vertices[arrayOffset + 14] = sprite.color.a;
  13868. };
  13869. SpriteManager.prototype.render = function () {
  13870. // Check
  13871. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13872. return;
  13873. var engine = this._scene.getEngine();
  13874. var baseSize = this._spriteTexture.getBaseSize();
  13875. // Sprites
  13876. var deltaTime = engine.getDeltaTime();
  13877. var max = Math.min(this._capacity, this.sprites.length);
  13878. var rowSize = baseSize.width / this.cellSize;
  13879. var offset = 0;
  13880. for (var index = 0; index < max; index++) {
  13881. var sprite = this.sprites[index];
  13882. if (!sprite) {
  13883. continue;
  13884. }
  13885. sprite._animate(deltaTime);
  13886. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13887. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13888. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13889. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13890. }
  13891. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13892. // Render
  13893. var effect = this._effectBase;
  13894. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13895. effect = this._effectFog;
  13896. }
  13897. engine.enableEffect(effect);
  13898. var viewMatrix = this._scene.getViewMatrix();
  13899. effect.setTexture("diffuseSampler", this._spriteTexture);
  13900. effect.setMatrix("view", viewMatrix);
  13901. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13902. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13903. // Fog
  13904. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13905. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13906. effect.setColor3("vFogColor", this._scene.fogColor);
  13907. }
  13908. // VBOs
  13909. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13910. // Draw order
  13911. effect.setBool("alphaTest", true);
  13912. engine.setColorWrite(false);
  13913. engine.draw(true, 0, max * 6);
  13914. engine.setColorWrite(true);
  13915. effect.setBool("alphaTest", false);
  13916. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13917. engine.draw(true, 0, max * 6);
  13918. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13919. };
  13920. SpriteManager.prototype.dispose = function () {
  13921. if (this._vertexBuffer) {
  13922. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13923. this._vertexBuffer = null;
  13924. }
  13925. if (this._indexBuffer) {
  13926. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13927. this._indexBuffer = null;
  13928. }
  13929. if (this._spriteTexture) {
  13930. this._spriteTexture.dispose();
  13931. this._spriteTexture = null;
  13932. }
  13933. // Remove from scene
  13934. var index = this._scene.spriteManagers.indexOf(this);
  13935. this._scene.spriteManagers.splice(index, 1);
  13936. // Callback
  13937. if (this.onDispose) {
  13938. this.onDispose();
  13939. }
  13940. };
  13941. return SpriteManager;
  13942. })();
  13943. BABYLON.SpriteManager = SpriteManager;
  13944. })(BABYLON || (BABYLON = {}));
  13945. //# sourceMappingURL=babylon.spriteManager.js.map
  13946. var BABYLON;
  13947. (function (BABYLON) {
  13948. var Sprite = (function () {
  13949. function Sprite(name, manager) {
  13950. this.name = name;
  13951. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13952. this.size = 1.0;
  13953. this.angle = 0;
  13954. this.cellIndex = 0;
  13955. this.invertU = 0;
  13956. this.invertV = 0;
  13957. this.animations = new Array();
  13958. this._animationStarted = false;
  13959. this._loopAnimation = false;
  13960. this._fromIndex = 0;
  13961. this._toIndex = 0;
  13962. this._delay = 0;
  13963. this._direction = 1;
  13964. this._frameCount = 0;
  13965. this._time = 0;
  13966. this._manager = manager;
  13967. this._manager.sprites.push(this);
  13968. this.position = BABYLON.Vector3.Zero();
  13969. }
  13970. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13971. this._fromIndex = from;
  13972. this._toIndex = to;
  13973. this._loopAnimation = loop;
  13974. this._delay = delay;
  13975. this._animationStarted = true;
  13976. this._direction = from < to ? 1 : -1;
  13977. this.cellIndex = from;
  13978. this._time = 0;
  13979. };
  13980. Sprite.prototype.stopAnimation = function () {
  13981. this._animationStarted = false;
  13982. };
  13983. Sprite.prototype._animate = function (deltaTime) {
  13984. if (!this._animationStarted)
  13985. return;
  13986. this._time += deltaTime;
  13987. if (this._time > this._delay) {
  13988. this._time = this._time % this._delay;
  13989. this.cellIndex += this._direction;
  13990. if (this.cellIndex == this._toIndex) {
  13991. if (this._loopAnimation) {
  13992. this.cellIndex = this._fromIndex;
  13993. } else {
  13994. this._animationStarted = false;
  13995. if (this.disposeWhenFinishedAnimating) {
  13996. this.dispose();
  13997. }
  13998. }
  13999. }
  14000. }
  14001. };
  14002. Sprite.prototype.dispose = function () {
  14003. for (var i = 0; i < this._manager.sprites.length; i++) {
  14004. if (this._manager.sprites[i] == this) {
  14005. this._manager.sprites.splice(i, 1);
  14006. }
  14007. }
  14008. };
  14009. return Sprite;
  14010. })();
  14011. BABYLON.Sprite = Sprite;
  14012. })(BABYLON || (BABYLON = {}));
  14013. //# sourceMappingURL=babylon.sprite.js.map
  14014. var BABYLON;
  14015. (function (BABYLON) {
  14016. var Layer = (function () {
  14017. function Layer(name, imgUrl, scene, isBackground, color) {
  14018. this.name = name;
  14019. this._vertexDeclaration = [2];
  14020. this._vertexStrideSize = 2 * 4;
  14021. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14022. this.isBackground = isBackground === undefined ? true : isBackground;
  14023. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14024. this._scene = scene;
  14025. this._scene.layers.push(this);
  14026. // VBO
  14027. var vertices = [];
  14028. vertices.push(1, 1);
  14029. vertices.push(-1, 1);
  14030. vertices.push(-1, -1);
  14031. vertices.push(1, -1);
  14032. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14033. // Indices
  14034. var indices = [];
  14035. indices.push(0);
  14036. indices.push(1);
  14037. indices.push(2);
  14038. indices.push(0);
  14039. indices.push(2);
  14040. indices.push(3);
  14041. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14042. // Effects
  14043. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14044. }
  14045. Layer.prototype.render = function () {
  14046. // Check
  14047. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14048. return;
  14049. var engine = this._scene.getEngine();
  14050. // Render
  14051. engine.enableEffect(this._effect);
  14052. engine.setState(false);
  14053. // Texture
  14054. this._effect.setTexture("textureSampler", this.texture);
  14055. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14056. // Color
  14057. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14058. // VBOs
  14059. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14060. // Draw order
  14061. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14062. engine.draw(true, 0, 6);
  14063. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14064. };
  14065. Layer.prototype.dispose = function () {
  14066. if (this._vertexBuffer) {
  14067. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14068. this._vertexBuffer = null;
  14069. }
  14070. if (this._indexBuffer) {
  14071. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14072. this._indexBuffer = null;
  14073. }
  14074. if (this.texture) {
  14075. this.texture.dispose();
  14076. this.texture = null;
  14077. }
  14078. // Remove from scene
  14079. var index = this._scene.layers.indexOf(this);
  14080. this._scene.layers.splice(index, 1);
  14081. // Callback
  14082. if (this.onDispose) {
  14083. this.onDispose();
  14084. }
  14085. };
  14086. return Layer;
  14087. })();
  14088. BABYLON.Layer = Layer;
  14089. })(BABYLON || (BABYLON = {}));
  14090. //# sourceMappingURL=babylon.layer.js.map
  14091. var BABYLON;
  14092. (function (BABYLON) {
  14093. var Particle = (function () {
  14094. function Particle() {
  14095. this.position = BABYLON.Vector3.Zero();
  14096. this.direction = BABYLON.Vector3.Zero();
  14097. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14098. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14099. this.lifeTime = 1.0;
  14100. this.age = 0;
  14101. this.size = 0;
  14102. this.angle = 0;
  14103. this.angularSpeed = 0;
  14104. }
  14105. Particle.prototype.copyTo = function (other) {
  14106. other.position.copyFrom(this.position);
  14107. other.direction.copyFrom(this.direction);
  14108. other.color.copyFrom(this.color);
  14109. other.colorStep.copyFrom(this.colorStep);
  14110. other.lifeTime = this.lifeTime;
  14111. other.age = this.age;
  14112. other.size = this.size;
  14113. other.angle = this.angle;
  14114. other.angularSpeed = this.angularSpeed;
  14115. };
  14116. return Particle;
  14117. })();
  14118. BABYLON.Particle = Particle;
  14119. })(BABYLON || (BABYLON = {}));
  14120. //# sourceMappingURL=babylon.particle.js.map
  14121. var BABYLON;
  14122. (function (BABYLON) {
  14123. var randomNumber = function (min, max) {
  14124. if (min === max) {
  14125. return (min);
  14126. }
  14127. var random = Math.random();
  14128. return ((random * (max - min)) + min);
  14129. };
  14130. var ParticleSystem = (function () {
  14131. function ParticleSystem(name, capacity, scene, customEffect) {
  14132. var _this = this;
  14133. this.name = name;
  14134. this.renderingGroupId = 0;
  14135. this.emitter = null;
  14136. this.emitRate = 10;
  14137. this.manualEmitCount = -1;
  14138. this.updateSpeed = 0.01;
  14139. this.targetStopDuration = 0;
  14140. this.disposeOnStop = false;
  14141. this.minEmitPower = 1;
  14142. this.maxEmitPower = 1;
  14143. this.minLifeTime = 1;
  14144. this.maxLifeTime = 1;
  14145. this.minSize = 1;
  14146. this.maxSize = 1;
  14147. this.minAngularSpeed = 0;
  14148. this.maxAngularSpeed = 0;
  14149. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14150. this.forceDepthWrite = false;
  14151. this.gravity = BABYLON.Vector3.Zero();
  14152. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14153. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14154. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14155. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14156. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14157. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14158. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14159. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14160. this.particles = new Array();
  14161. this._vertexDeclaration = [3, 4, 4];
  14162. this._vertexStrideSize = 11 * 4;
  14163. this._stockParticles = new Array();
  14164. this._newPartsExcess = 0;
  14165. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14166. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14167. this._scaledDirection = BABYLON.Vector3.Zero();
  14168. this._scaledGravity = BABYLON.Vector3.Zero();
  14169. this._currentRenderId = -1;
  14170. this._started = false;
  14171. this._stopped = false;
  14172. this._actualFrame = 0;
  14173. this.id = name;
  14174. this._capacity = capacity;
  14175. this._scene = scene;
  14176. this._customEffect = customEffect;
  14177. scene.particleSystems.push(this);
  14178. // VBO
  14179. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14180. var indices = [];
  14181. var index = 0;
  14182. for (var count = 0; count < capacity; count++) {
  14183. indices.push(index);
  14184. indices.push(index + 1);
  14185. indices.push(index + 2);
  14186. indices.push(index);
  14187. indices.push(index + 2);
  14188. indices.push(index + 3);
  14189. index += 4;
  14190. }
  14191. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14192. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14193. // Default behaviors
  14194. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14195. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14196. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14197. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14198. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14199. };
  14200. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14201. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14202. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14203. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14204. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14205. };
  14206. this.updateFunction = function (particles) {
  14207. for (var index = 0; index < particles.length; index++) {
  14208. var particle = particles[index];
  14209. particle.age += _this._scaledUpdateSpeed;
  14210. if (particle.age >= particle.lifeTime) {
  14211. _this.recycleParticle(particle);
  14212. index--;
  14213. continue;
  14214. } else {
  14215. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14216. particle.color.addInPlace(_this._scaledColorStep);
  14217. if (particle.color.a < 0)
  14218. particle.color.a = 0;
  14219. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14220. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14221. particle.position.addInPlace(_this._scaledDirection);
  14222. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14223. particle.direction.addInPlace(_this._scaledGravity);
  14224. }
  14225. }
  14226. };
  14227. }
  14228. ParticleSystem.prototype.recycleParticle = function (particle) {
  14229. var lastParticle = this.particles.pop();
  14230. if (lastParticle !== particle) {
  14231. lastParticle.copyTo(particle);
  14232. this._stockParticles.push(lastParticle);
  14233. }
  14234. };
  14235. ParticleSystem.prototype.getCapacity = function () {
  14236. return this._capacity;
  14237. };
  14238. ParticleSystem.prototype.isAlive = function () {
  14239. return this._alive;
  14240. };
  14241. ParticleSystem.prototype.isStarted = function () {
  14242. return this._started;
  14243. };
  14244. ParticleSystem.prototype.start = function () {
  14245. this._started = true;
  14246. this._stopped = false;
  14247. this._actualFrame = 0;
  14248. };
  14249. ParticleSystem.prototype.stop = function () {
  14250. this._stopped = true;
  14251. };
  14252. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14253. var offset = index * 11;
  14254. this._vertices[offset] = particle.position.x;
  14255. this._vertices[offset + 1] = particle.position.y;
  14256. this._vertices[offset + 2] = particle.position.z;
  14257. this._vertices[offset + 3] = particle.color.r;
  14258. this._vertices[offset + 4] = particle.color.g;
  14259. this._vertices[offset + 5] = particle.color.b;
  14260. this._vertices[offset + 6] = particle.color.a;
  14261. this._vertices[offset + 7] = particle.angle;
  14262. this._vertices[offset + 8] = particle.size;
  14263. this._vertices[offset + 9] = offsetX;
  14264. this._vertices[offset + 10] = offsetY;
  14265. };
  14266. ParticleSystem.prototype._update = function (newParticles) {
  14267. // Update current
  14268. this._alive = this.particles.length > 0;
  14269. this.updateFunction(this.particles);
  14270. // Add new ones
  14271. var worldMatrix;
  14272. if (this.emitter.position) {
  14273. worldMatrix = this.emitter.getWorldMatrix();
  14274. } else {
  14275. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14276. }
  14277. for (var index = 0; index < newParticles; index++) {
  14278. if (this.particles.length === this._capacity) {
  14279. break;
  14280. }
  14281. if (this._stockParticles.length !== 0) {
  14282. var particle = this._stockParticles.pop();
  14283. particle.age = 0;
  14284. } else {
  14285. particle = new BABYLON.Particle();
  14286. }
  14287. this.particles.push(particle);
  14288. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14289. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14290. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14291. particle.size = randomNumber(this.minSize, this.maxSize);
  14292. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14293. this.startPositionFunction(worldMatrix, particle.position);
  14294. var step = randomNumber(0, 1.0);
  14295. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14296. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14297. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14298. }
  14299. };
  14300. ParticleSystem.prototype._getEffect = function () {
  14301. if (this._customEffect) {
  14302. return this._customEffect;
  14303. }
  14304. ;
  14305. var defines = [];
  14306. if (this._scene.clipPlane) {
  14307. defines.push("#define CLIPPLANE");
  14308. }
  14309. // Effect
  14310. var join = defines.join("\n");
  14311. if (this._cachedDefines !== join) {
  14312. this._cachedDefines = join;
  14313. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14314. }
  14315. return this._effect;
  14316. };
  14317. ParticleSystem.prototype.animate = function () {
  14318. if (!this._started)
  14319. return;
  14320. var effect = this._getEffect();
  14321. // Check
  14322. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14323. return;
  14324. if (this._currentRenderId === this._scene.getRenderId()) {
  14325. return;
  14326. }
  14327. this._currentRenderId = this._scene.getRenderId();
  14328. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14329. // determine the number of particles we need to create
  14330. var emitCout;
  14331. if (this.manualEmitCount > -1) {
  14332. emitCout = this.manualEmitCount;
  14333. this.manualEmitCount = 0;
  14334. } else {
  14335. emitCout = this.emitRate;
  14336. }
  14337. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14338. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14339. if (this._newPartsExcess > 1.0) {
  14340. newParticles += this._newPartsExcess >> 0;
  14341. this._newPartsExcess -= this._newPartsExcess >> 0;
  14342. }
  14343. this._alive = false;
  14344. if (!this._stopped) {
  14345. this._actualFrame += this._scaledUpdateSpeed;
  14346. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14347. this.stop();
  14348. } else {
  14349. newParticles = 0;
  14350. }
  14351. this._update(newParticles);
  14352. // Stopped?
  14353. if (this._stopped) {
  14354. if (!this._alive) {
  14355. this._started = false;
  14356. if (this.disposeOnStop) {
  14357. this._scene._toBeDisposed.push(this);
  14358. }
  14359. }
  14360. }
  14361. // Update VBO
  14362. var offset = 0;
  14363. for (var index = 0; index < this.particles.length; index++) {
  14364. var particle = this.particles[index];
  14365. this._appendParticleVertex(offset++, particle, 0, 0);
  14366. this._appendParticleVertex(offset++, particle, 1, 0);
  14367. this._appendParticleVertex(offset++, particle, 1, 1);
  14368. this._appendParticleVertex(offset++, particle, 0, 1);
  14369. }
  14370. var engine = this._scene.getEngine();
  14371. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14372. };
  14373. ParticleSystem.prototype.render = function () {
  14374. var effect = this._getEffect();
  14375. // Check
  14376. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14377. return 0;
  14378. var engine = this._scene.getEngine();
  14379. // Render
  14380. engine.enableEffect(effect);
  14381. engine.setState(false);
  14382. var viewMatrix = this._scene.getViewMatrix();
  14383. effect.setTexture("diffuseSampler", this.particleTexture);
  14384. effect.setMatrix("view", viewMatrix);
  14385. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14386. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14387. if (this._scene.clipPlane) {
  14388. var clipPlane = this._scene.clipPlane;
  14389. var invView = viewMatrix.clone();
  14390. invView.invert();
  14391. effect.setMatrix("invView", invView);
  14392. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14393. }
  14394. // VBOs
  14395. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14396. // Draw order
  14397. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14398. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14399. } else {
  14400. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14401. }
  14402. if (this.forceDepthWrite) {
  14403. engine.setDepthWrite(true);
  14404. }
  14405. engine.draw(true, 0, this.particles.length * 6);
  14406. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14407. return this.particles.length;
  14408. };
  14409. ParticleSystem.prototype.dispose = function () {
  14410. if (this._vertexBuffer) {
  14411. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14412. this._vertexBuffer = null;
  14413. }
  14414. if (this._indexBuffer) {
  14415. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14416. this._indexBuffer = null;
  14417. }
  14418. if (this.particleTexture) {
  14419. this.particleTexture.dispose();
  14420. this.particleTexture = null;
  14421. }
  14422. // Remove from scene
  14423. var index = this._scene.particleSystems.indexOf(this);
  14424. this._scene.particleSystems.splice(index, 1);
  14425. // Callback
  14426. if (this.onDispose) {
  14427. this.onDispose();
  14428. }
  14429. };
  14430. // Clone
  14431. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14432. var result = new ParticleSystem(name, this._capacity, this._scene);
  14433. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14434. if (newEmitter === undefined) {
  14435. newEmitter = this.emitter;
  14436. }
  14437. result.emitter = newEmitter;
  14438. if (this.particleTexture) {
  14439. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14440. }
  14441. result.start();
  14442. return result;
  14443. };
  14444. ParticleSystem.BLENDMODE_ONEONE = 0;
  14445. ParticleSystem.BLENDMODE_STANDARD = 1;
  14446. return ParticleSystem;
  14447. })();
  14448. BABYLON.ParticleSystem = ParticleSystem;
  14449. })(BABYLON || (BABYLON = {}));
  14450. //# sourceMappingURL=babylon.particleSystem.js.map
  14451. var BABYLON;
  14452. (function (BABYLON) {
  14453. var Animation = (function () {
  14454. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14455. this.name = name;
  14456. this.targetProperty = targetProperty;
  14457. this.framePerSecond = framePerSecond;
  14458. this.dataType = dataType;
  14459. this.loopMode = loopMode;
  14460. this._offsetsCache = {};
  14461. this._highLimitsCache = {};
  14462. this._stopped = false;
  14463. this.targetPropertyPath = targetProperty.split(".");
  14464. this.dataType = dataType;
  14465. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14466. }
  14467. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14468. var dataType = undefined;
  14469. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14470. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14471. } else if (from instanceof BABYLON.Quaternion) {
  14472. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14473. } else if (from instanceof BABYLON.Vector3) {
  14474. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14475. } else if (from instanceof BABYLON.Vector2) {
  14476. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14477. } else if (from instanceof BABYLON.Color3) {
  14478. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14479. }
  14480. if (dataType == undefined) {
  14481. return;
  14482. }
  14483. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14484. var keys = [];
  14485. keys.push({ frame: 0, value: from });
  14486. keys.push({ frame: totalFrame, value: to });
  14487. animation.setKeys(keys);
  14488. mesh.animations.push(animation);
  14489. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  14490. };
  14491. // Methods
  14492. Animation.prototype.isStopped = function () {
  14493. return this._stopped;
  14494. };
  14495. Animation.prototype.getKeys = function () {
  14496. return this._keys;
  14497. };
  14498. Animation.prototype.getEasingFunction = function () {
  14499. return this._easingFunction;
  14500. };
  14501. Animation.prototype.setEasingFunction = function (easingFunction) {
  14502. this._easingFunction = easingFunction;
  14503. };
  14504. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14505. return startValue + (endValue - startValue) * gradient;
  14506. };
  14507. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14508. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14509. };
  14510. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14511. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14512. };
  14513. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14514. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14515. };
  14516. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14517. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14518. };
  14519. Animation.prototype.clone = function () {
  14520. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14521. clone.setKeys(this._keys);
  14522. return clone;
  14523. };
  14524. Animation.prototype.setKeys = function (values) {
  14525. this._keys = values.slice(0);
  14526. this._offsetsCache = {};
  14527. this._highLimitsCache = {};
  14528. };
  14529. Animation.prototype._getKeyValue = function (value) {
  14530. if (typeof value === "function") {
  14531. return value();
  14532. }
  14533. return value;
  14534. };
  14535. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14536. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14537. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14538. }
  14539. this.currentFrame = currentFrame;
  14540. for (var key = 0; key < this._keys.length; key++) {
  14541. // for each frame, we need the key just before the frame superior
  14542. if (this._keys[key + 1].frame >= currentFrame) {
  14543. var startValue = this._getKeyValue(this._keys[key].value);
  14544. var endValue = this._getKeyValue(this._keys[key + 1].value);
  14545. // gradient : percent of currentFrame between the frame inf and the frame sup
  14546. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14547. // check for easingFunction and correction of gradient
  14548. if (this._easingFunction != null) {
  14549. gradient = this._easingFunction.ease(gradient);
  14550. }
  14551. switch (this.dataType) {
  14552. case Animation.ANIMATIONTYPE_FLOAT:
  14553. switch (loopMode) {
  14554. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14555. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14556. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14557. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14558. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14559. }
  14560. break;
  14561. case Animation.ANIMATIONTYPE_QUATERNION:
  14562. var quaternion = null;
  14563. switch (loopMode) {
  14564. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14565. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14566. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14567. break;
  14568. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14569. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14570. break;
  14571. }
  14572. return quaternion;
  14573. case Animation.ANIMATIONTYPE_VECTOR3:
  14574. switch (loopMode) {
  14575. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14576. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14577. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14578. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14579. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14580. }
  14581. case Animation.ANIMATIONTYPE_VECTOR2:
  14582. switch (loopMode) {
  14583. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14584. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14585. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14586. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14587. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14588. }
  14589. case Animation.ANIMATIONTYPE_COLOR3:
  14590. switch (loopMode) {
  14591. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14592. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14593. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14594. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14595. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14596. }
  14597. case Animation.ANIMATIONTYPE_MATRIX:
  14598. switch (loopMode) {
  14599. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14600. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14601. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14602. return startValue;
  14603. }
  14604. default:
  14605. break;
  14606. }
  14607. break;
  14608. }
  14609. }
  14610. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  14611. };
  14612. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14613. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14614. this._stopped = true;
  14615. return false;
  14616. }
  14617. var returnValue = true;
  14618. // Adding a start key at frame 0 if missing
  14619. if (this._keys[0].frame !== 0) {
  14620. var newKey = { frame: 0, value: this._keys[0].value };
  14621. this._keys.splice(0, 0, newKey);
  14622. }
  14623. // Check limits
  14624. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14625. from = this._keys[0].frame;
  14626. }
  14627. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14628. to = this._keys[this._keys.length - 1].frame;
  14629. }
  14630. // Compute ratio
  14631. var range = to - from;
  14632. var offsetValue;
  14633. // ratio represents the frame delta between from and to
  14634. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14635. var highLimitValue = 0;
  14636. if (ratio > range && !loop) {
  14637. returnValue = false;
  14638. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  14639. } else {
  14640. // Get max value if required
  14641. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  14642. var keyOffset = to.toString() + from.toString();
  14643. if (!this._offsetsCache[keyOffset]) {
  14644. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14645. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14646. switch (this.dataType) {
  14647. case Animation.ANIMATIONTYPE_FLOAT:
  14648. this._offsetsCache[keyOffset] = toValue - fromValue;
  14649. break;
  14650. case Animation.ANIMATIONTYPE_QUATERNION:
  14651. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14652. break;
  14653. case Animation.ANIMATIONTYPE_VECTOR3:
  14654. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14655. case Animation.ANIMATIONTYPE_VECTOR2:
  14656. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14657. case Animation.ANIMATIONTYPE_COLOR3:
  14658. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14659. default:
  14660. break;
  14661. }
  14662. this._highLimitsCache[keyOffset] = toValue;
  14663. }
  14664. highLimitValue = this._highLimitsCache[keyOffset];
  14665. offsetValue = this._offsetsCache[keyOffset];
  14666. }
  14667. }
  14668. if (offsetValue === undefined) {
  14669. switch (this.dataType) {
  14670. case Animation.ANIMATIONTYPE_FLOAT:
  14671. offsetValue = 0;
  14672. break;
  14673. case Animation.ANIMATIONTYPE_QUATERNION:
  14674. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14675. break;
  14676. case Animation.ANIMATIONTYPE_VECTOR3:
  14677. offsetValue = BABYLON.Vector3.Zero();
  14678. break;
  14679. case Animation.ANIMATIONTYPE_VECTOR2:
  14680. offsetValue = BABYLON.Vector2.Zero();
  14681. break;
  14682. case Animation.ANIMATIONTYPE_COLOR3:
  14683. offsetValue = BABYLON.Color3.Black();
  14684. }
  14685. }
  14686. // Compute value
  14687. var repeatCount = (ratio / range) >> 0;
  14688. var currentFrame = returnValue ? from + ratio % range : to;
  14689. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14690. // Set value
  14691. if (this.targetPropertyPath.length > 1) {
  14692. var property = this._target[this.targetPropertyPath[0]];
  14693. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14694. property = property[this.targetPropertyPath[index]];
  14695. }
  14696. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14697. } else {
  14698. this._target[this.targetPropertyPath[0]] = currentValue;
  14699. }
  14700. if (this._target.markAsDirty) {
  14701. this._target.markAsDirty(this.targetProperty);
  14702. }
  14703. if (!returnValue) {
  14704. this._stopped = true;
  14705. }
  14706. return returnValue;
  14707. };
  14708. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14709. get: function () {
  14710. return Animation._ANIMATIONTYPE_FLOAT;
  14711. },
  14712. enumerable: true,
  14713. configurable: true
  14714. });
  14715. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14716. get: function () {
  14717. return Animation._ANIMATIONTYPE_VECTOR3;
  14718. },
  14719. enumerable: true,
  14720. configurable: true
  14721. });
  14722. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14723. get: function () {
  14724. return Animation._ANIMATIONTYPE_VECTOR2;
  14725. },
  14726. enumerable: true,
  14727. configurable: true
  14728. });
  14729. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14730. get: function () {
  14731. return Animation._ANIMATIONTYPE_QUATERNION;
  14732. },
  14733. enumerable: true,
  14734. configurable: true
  14735. });
  14736. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14737. get: function () {
  14738. return Animation._ANIMATIONTYPE_MATRIX;
  14739. },
  14740. enumerable: true,
  14741. configurable: true
  14742. });
  14743. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14744. get: function () {
  14745. return Animation._ANIMATIONTYPE_COLOR3;
  14746. },
  14747. enumerable: true,
  14748. configurable: true
  14749. });
  14750. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14751. get: function () {
  14752. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14753. },
  14754. enumerable: true,
  14755. configurable: true
  14756. });
  14757. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14758. get: function () {
  14759. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14760. },
  14761. enumerable: true,
  14762. configurable: true
  14763. });
  14764. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14765. get: function () {
  14766. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14767. },
  14768. enumerable: true,
  14769. configurable: true
  14770. });
  14771. Animation._ANIMATIONTYPE_FLOAT = 0;
  14772. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14773. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14774. Animation._ANIMATIONTYPE_MATRIX = 3;
  14775. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14776. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14777. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14778. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14779. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14780. return Animation;
  14781. })();
  14782. BABYLON.Animation = Animation;
  14783. })(BABYLON || (BABYLON = {}));
  14784. //# sourceMappingURL=babylon.animation.js.map
  14785. var BABYLON;
  14786. (function (BABYLON) {
  14787. var Animatable = (function () {
  14788. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14789. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14790. if (typeof toFrame === "undefined") { toFrame = 100; }
  14791. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14792. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14793. this.target = target;
  14794. this.fromFrame = fromFrame;
  14795. this.toFrame = toFrame;
  14796. this.loopAnimation = loopAnimation;
  14797. this.speedRatio = speedRatio;
  14798. this.onAnimationEnd = onAnimationEnd;
  14799. this._animations = new Array();
  14800. this._paused = false;
  14801. this.animationStarted = false;
  14802. if (animations) {
  14803. this.appendAnimations(target, animations);
  14804. }
  14805. this._scene = scene;
  14806. scene._activeAnimatables.push(this);
  14807. }
  14808. // Methods
  14809. Animatable.prototype.appendAnimations = function (target, animations) {
  14810. for (var index = 0; index < animations.length; index++) {
  14811. var animation = animations[index];
  14812. animation._target = target;
  14813. this._animations.push(animation);
  14814. }
  14815. };
  14816. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14817. var animations = this._animations;
  14818. for (var index = 0; index < animations.length; index++) {
  14819. if (animations[index].targetProperty === property) {
  14820. return animations[index];
  14821. }
  14822. }
  14823. return null;
  14824. };
  14825. Animatable.prototype.pause = function () {
  14826. if (this._paused) {
  14827. return;
  14828. }
  14829. this._paused = true;
  14830. };
  14831. Animatable.prototype.restart = function () {
  14832. this._paused = false;
  14833. };
  14834. Animatable.prototype.stop = function () {
  14835. var index = this._scene._activeAnimatables.indexOf(this);
  14836. if (index > -1) {
  14837. this._scene._activeAnimatables.splice(index, 1);
  14838. }
  14839. if (this.onAnimationEnd) {
  14840. this.onAnimationEnd();
  14841. }
  14842. };
  14843. Animatable.prototype._animate = function (delay) {
  14844. if (this._paused) {
  14845. if (!this._pausedDelay) {
  14846. this._pausedDelay = delay;
  14847. }
  14848. return true;
  14849. }
  14850. if (!this._localDelayOffset) {
  14851. this._localDelayOffset = delay;
  14852. } else if (this._pausedDelay) {
  14853. this._localDelayOffset += delay - this._pausedDelay;
  14854. this._pausedDelay = null;
  14855. }
  14856. // Animating
  14857. var running = false;
  14858. var animations = this._animations;
  14859. for (var index = 0; index < animations.length; index++) {
  14860. var animation = animations[index];
  14861. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14862. running = running || isRunning;
  14863. }
  14864. if (!running && this.onAnimationEnd) {
  14865. this.onAnimationEnd();
  14866. }
  14867. return running;
  14868. };
  14869. return Animatable;
  14870. })();
  14871. BABYLON.Animatable = Animatable;
  14872. })(BABYLON || (BABYLON = {}));
  14873. //# sourceMappingURL=babylon.animatable.js.map
  14874. var BABYLON;
  14875. (function (BABYLON) {
  14876. var EasingFunction = (function () {
  14877. function EasingFunction() {
  14878. // Properties
  14879. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14880. }
  14881. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14882. get: function () {
  14883. return EasingFunction._EASINGMODE_EASEIN;
  14884. },
  14885. enumerable: true,
  14886. configurable: true
  14887. });
  14888. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14889. get: function () {
  14890. return EasingFunction._EASINGMODE_EASEOUT;
  14891. },
  14892. enumerable: true,
  14893. configurable: true
  14894. });
  14895. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14896. get: function () {
  14897. return EasingFunction._EASINGMODE_EASEINOUT;
  14898. },
  14899. enumerable: true,
  14900. configurable: true
  14901. });
  14902. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14903. var n = Math.min(Math.max(easingMode, 0), 2);
  14904. this._easingMode = n;
  14905. };
  14906. EasingFunction.prototype.getEasingMode = function () {
  14907. return this._easingMode;
  14908. };
  14909. EasingFunction.prototype.easeInCore = function (gradient) {
  14910. throw new Error('You must implement this method');
  14911. };
  14912. EasingFunction.prototype.ease = function (gradient) {
  14913. switch (this._easingMode) {
  14914. case EasingFunction.EASINGMODE_EASEIN:
  14915. return this.easeInCore(gradient);
  14916. case EasingFunction.EASINGMODE_EASEOUT:
  14917. return (1 - this.easeInCore(1 - gradient));
  14918. }
  14919. if (gradient >= 0.5) {
  14920. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14921. }
  14922. return (this.easeInCore(gradient * 2) * 0.5);
  14923. };
  14924. EasingFunction._EASINGMODE_EASEIN = 0;
  14925. EasingFunction._EASINGMODE_EASEOUT = 1;
  14926. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14927. return EasingFunction;
  14928. })();
  14929. BABYLON.EasingFunction = EasingFunction;
  14930. var CircleEase = (function (_super) {
  14931. __extends(CircleEase, _super);
  14932. function CircleEase() {
  14933. _super.apply(this, arguments);
  14934. }
  14935. CircleEase.prototype.easeInCore = function (gradient) {
  14936. gradient = Math.max(0, Math.min(1, gradient));
  14937. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  14938. };
  14939. return CircleEase;
  14940. })(EasingFunction);
  14941. BABYLON.CircleEase = CircleEase;
  14942. var BackEase = (function (_super) {
  14943. __extends(BackEase, _super);
  14944. function BackEase(amplitude) {
  14945. if (typeof amplitude === "undefined") { amplitude = 1; }
  14946. _super.call(this);
  14947. this.amplitude = amplitude;
  14948. }
  14949. BackEase.prototype.easeInCore = function (gradient) {
  14950. var num = Math.max(0, this.amplitude);
  14951. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  14952. };
  14953. return BackEase;
  14954. })(EasingFunction);
  14955. BABYLON.BackEase = BackEase;
  14956. var BounceEase = (function (_super) {
  14957. __extends(BounceEase, _super);
  14958. function BounceEase(bounces, bounciness) {
  14959. if (typeof bounces === "undefined") { bounces = 3; }
  14960. if (typeof bounciness === "undefined") { bounciness = 2; }
  14961. _super.call(this);
  14962. this.bounces = bounces;
  14963. this.bounciness = bounciness;
  14964. }
  14965. BounceEase.prototype.easeInCore = function (gradient) {
  14966. var y = Math.max(0.0, this.bounces);
  14967. var bounciness = this.bounciness;
  14968. if (bounciness <= 1.0) {
  14969. bounciness = 1.001;
  14970. }
  14971. var num9 = Math.pow(bounciness, y);
  14972. var num5 = 1.0 - bounciness;
  14973. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  14974. var num15 = gradient * num4;
  14975. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  14976. var num3 = Math.floor(num65);
  14977. var num13 = num3 + 1.0;
  14978. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  14979. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  14980. var num7 = (num8 + num12) * 0.5;
  14981. var num6 = gradient - num7;
  14982. var num2 = num7 - num8;
  14983. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  14984. };
  14985. return BounceEase;
  14986. })(EasingFunction);
  14987. BABYLON.BounceEase = BounceEase;
  14988. var CubicEase = (function (_super) {
  14989. __extends(CubicEase, _super);
  14990. function CubicEase() {
  14991. _super.apply(this, arguments);
  14992. }
  14993. CubicEase.prototype.easeInCore = function (gradient) {
  14994. return (gradient * gradient * gradient);
  14995. };
  14996. return CubicEase;
  14997. })(EasingFunction);
  14998. BABYLON.CubicEase = CubicEase;
  14999. var ElasticEase = (function (_super) {
  15000. __extends(ElasticEase, _super);
  15001. function ElasticEase(oscillations, springiness) {
  15002. if (typeof oscillations === "undefined") { oscillations = 3; }
  15003. if (typeof springiness === "undefined") { springiness = 3; }
  15004. _super.call(this);
  15005. this.oscillations = oscillations;
  15006. this.springiness = springiness;
  15007. }
  15008. ElasticEase.prototype.easeInCore = function (gradient) {
  15009. var num2;
  15010. var num3 = Math.max(0.0, this.oscillations);
  15011. var num = Math.max(0.0, this.springiness);
  15012. if (num == 0) {
  15013. num2 = gradient;
  15014. } else {
  15015. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15016. }
  15017. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15018. };
  15019. return ElasticEase;
  15020. })(EasingFunction);
  15021. BABYLON.ElasticEase = ElasticEase;
  15022. var ExponentialEase = (function (_super) {
  15023. __extends(ExponentialEase, _super);
  15024. function ExponentialEase(exponent) {
  15025. if (typeof exponent === "undefined") { exponent = 2; }
  15026. _super.call(this);
  15027. this.exponent = exponent;
  15028. }
  15029. ExponentialEase.prototype.easeInCore = function (gradient) {
  15030. if (this.exponent <= 0) {
  15031. return gradient;
  15032. }
  15033. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15034. };
  15035. return ExponentialEase;
  15036. })(EasingFunction);
  15037. BABYLON.ExponentialEase = ExponentialEase;
  15038. var PowerEase = (function (_super) {
  15039. __extends(PowerEase, _super);
  15040. function PowerEase(power) {
  15041. if (typeof power === "undefined") { power = 2; }
  15042. _super.call(this);
  15043. this.power = power;
  15044. }
  15045. PowerEase.prototype.easeInCore = function (gradient) {
  15046. var y = Math.max(0.0, this.power);
  15047. return Math.pow(gradient, y);
  15048. };
  15049. return PowerEase;
  15050. })(EasingFunction);
  15051. BABYLON.PowerEase = PowerEase;
  15052. var QuadraticEase = (function (_super) {
  15053. __extends(QuadraticEase, _super);
  15054. function QuadraticEase() {
  15055. _super.apply(this, arguments);
  15056. }
  15057. QuadraticEase.prototype.easeInCore = function (gradient) {
  15058. return (gradient * gradient);
  15059. };
  15060. return QuadraticEase;
  15061. })(EasingFunction);
  15062. BABYLON.QuadraticEase = QuadraticEase;
  15063. var QuarticEase = (function (_super) {
  15064. __extends(QuarticEase, _super);
  15065. function QuarticEase() {
  15066. _super.apply(this, arguments);
  15067. }
  15068. QuarticEase.prototype.easeInCore = function (gradient) {
  15069. return (gradient * gradient * gradient * gradient);
  15070. };
  15071. return QuarticEase;
  15072. })(EasingFunction);
  15073. BABYLON.QuarticEase = QuarticEase;
  15074. var QuinticEase = (function (_super) {
  15075. __extends(QuinticEase, _super);
  15076. function QuinticEase() {
  15077. _super.apply(this, arguments);
  15078. }
  15079. QuinticEase.prototype.easeInCore = function (gradient) {
  15080. return (gradient * gradient * gradient * gradient * gradient);
  15081. };
  15082. return QuinticEase;
  15083. })(EasingFunction);
  15084. BABYLON.QuinticEase = QuinticEase;
  15085. var SineEase = (function (_super) {
  15086. __extends(SineEase, _super);
  15087. function SineEase() {
  15088. _super.apply(this, arguments);
  15089. }
  15090. SineEase.prototype.easeInCore = function (gradient) {
  15091. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15092. };
  15093. return SineEase;
  15094. })(EasingFunction);
  15095. BABYLON.SineEase = SineEase;
  15096. var BezierCurveEase = (function (_super) {
  15097. __extends(BezierCurveEase, _super);
  15098. function BezierCurveEase(x1, y1, x2, y2) {
  15099. if (typeof x1 === "undefined") { x1 = 0; }
  15100. if (typeof y1 === "undefined") { y1 = 0; }
  15101. if (typeof x2 === "undefined") { x2 = 1; }
  15102. if (typeof y2 === "undefined") { y2 = 1; }
  15103. _super.call(this);
  15104. this.x1 = x1;
  15105. this.y1 = y1;
  15106. this.x2 = x2;
  15107. this.y2 = y2;
  15108. }
  15109. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15110. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15111. };
  15112. return BezierCurveEase;
  15113. })(EasingFunction);
  15114. BABYLON.BezierCurveEase = BezierCurveEase;
  15115. })(BABYLON || (BABYLON = {}));
  15116. //# sourceMappingURL=babylon.easing.js.map
  15117. var BABYLON;
  15118. (function (BABYLON) {
  15119. var Octree = (function () {
  15120. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15121. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  15122. this.maxDepth = maxDepth;
  15123. this.dynamicContent = new Array();
  15124. this._maxBlockCapacity = maxBlockCapacity || 64;
  15125. this._selectionContent = new BABYLON.SmartArray(1024);
  15126. this._creationFunc = creationFunc;
  15127. }
  15128. // Methods
  15129. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15130. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15131. };
  15132. Octree.prototype.addMesh = function (entry) {
  15133. for (var index = 0; index < this.blocks.length; index++) {
  15134. var block = this.blocks[index];
  15135. block.addEntry(entry);
  15136. }
  15137. };
  15138. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15139. this._selectionContent.reset();
  15140. for (var index = 0; index < this.blocks.length; index++) {
  15141. var block = this.blocks[index];
  15142. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15143. }
  15144. if (allowDuplicate) {
  15145. this._selectionContent.concat(this.dynamicContent);
  15146. } else {
  15147. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15148. }
  15149. return this._selectionContent;
  15150. };
  15151. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15152. this._selectionContent.reset();
  15153. for (var index = 0; index < this.blocks.length; index++) {
  15154. var block = this.blocks[index];
  15155. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15156. }
  15157. if (allowDuplicate) {
  15158. this._selectionContent.concat(this.dynamicContent);
  15159. } else {
  15160. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15161. }
  15162. return this._selectionContent;
  15163. };
  15164. Octree.prototype.intersectsRay = function (ray) {
  15165. this._selectionContent.reset();
  15166. for (var index = 0; index < this.blocks.length; index++) {
  15167. var block = this.blocks[index];
  15168. block.intersectsRay(ray, this._selectionContent);
  15169. }
  15170. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15171. return this._selectionContent;
  15172. };
  15173. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15174. target.blocks = new Array();
  15175. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15176. for (var x = 0; x < 2; x++) {
  15177. for (var y = 0; y < 2; y++) {
  15178. for (var z = 0; z < 2; z++) {
  15179. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15180. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15181. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15182. block.addEntries(entries);
  15183. target.blocks.push(block);
  15184. }
  15185. }
  15186. }
  15187. };
  15188. Octree.CreationFuncForMeshes = function (entry, block) {
  15189. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15190. block.entries.push(entry);
  15191. }
  15192. };
  15193. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15194. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15195. block.entries.push(entry);
  15196. }
  15197. };
  15198. return Octree;
  15199. })();
  15200. BABYLON.Octree = Octree;
  15201. })(BABYLON || (BABYLON = {}));
  15202. //# sourceMappingURL=babylon.octree.js.map
  15203. var BABYLON;
  15204. (function (BABYLON) {
  15205. var OctreeBlock = (function () {
  15206. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15207. this.entries = new Array();
  15208. this._boundingVectors = new Array();
  15209. this._capacity = capacity;
  15210. this._depth = depth;
  15211. this._maxDepth = maxDepth;
  15212. this._creationFunc = creationFunc;
  15213. this._minPoint = minPoint;
  15214. this._maxPoint = maxPoint;
  15215. this._boundingVectors.push(minPoint.clone());
  15216. this._boundingVectors.push(maxPoint.clone());
  15217. this._boundingVectors.push(minPoint.clone());
  15218. this._boundingVectors[2].x = maxPoint.x;
  15219. this._boundingVectors.push(minPoint.clone());
  15220. this._boundingVectors[3].y = maxPoint.y;
  15221. this._boundingVectors.push(minPoint.clone());
  15222. this._boundingVectors[4].z = maxPoint.z;
  15223. this._boundingVectors.push(maxPoint.clone());
  15224. this._boundingVectors[5].z = minPoint.z;
  15225. this._boundingVectors.push(maxPoint.clone());
  15226. this._boundingVectors[6].x = minPoint.x;
  15227. this._boundingVectors.push(maxPoint.clone());
  15228. this._boundingVectors[7].y = minPoint.y;
  15229. }
  15230. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15231. // Property
  15232. get: function () {
  15233. return this._capacity;
  15234. },
  15235. enumerable: true,
  15236. configurable: true
  15237. });
  15238. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15239. get: function () {
  15240. return this._minPoint;
  15241. },
  15242. enumerable: true,
  15243. configurable: true
  15244. });
  15245. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15246. get: function () {
  15247. return this._maxPoint;
  15248. },
  15249. enumerable: true,
  15250. configurable: true
  15251. });
  15252. // Methods
  15253. OctreeBlock.prototype.addEntry = function (entry) {
  15254. if (this.blocks) {
  15255. for (var index = 0; index < this.blocks.length; index++) {
  15256. var block = this.blocks[index];
  15257. block.addEntry(entry);
  15258. }
  15259. return;
  15260. }
  15261. this._creationFunc(entry, this);
  15262. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15263. this.createInnerBlocks();
  15264. }
  15265. };
  15266. OctreeBlock.prototype.addEntries = function (entries) {
  15267. for (var index = 0; index < entries.length; index++) {
  15268. var mesh = entries[index];
  15269. this.addEntry(mesh);
  15270. }
  15271. };
  15272. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15273. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15274. if (this.blocks) {
  15275. for (var index = 0; index < this.blocks.length; index++) {
  15276. var block = this.blocks[index];
  15277. block.select(frustumPlanes, selection, allowDuplicate);
  15278. }
  15279. return;
  15280. }
  15281. if (allowDuplicate) {
  15282. selection.concat(this.entries);
  15283. } else {
  15284. selection.concatWithNoDuplicate(this.entries);
  15285. }
  15286. }
  15287. };
  15288. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15289. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15290. if (this.blocks) {
  15291. for (var index = 0; index < this.blocks.length; index++) {
  15292. var block = this.blocks[index];
  15293. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15294. }
  15295. return;
  15296. }
  15297. if (allowDuplicate) {
  15298. selection.concat(this.entries);
  15299. } else {
  15300. selection.concatWithNoDuplicate(this.entries);
  15301. }
  15302. }
  15303. };
  15304. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15305. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15306. if (this.blocks) {
  15307. for (var index = 0; index < this.blocks.length; index++) {
  15308. var block = this.blocks[index];
  15309. block.intersectsRay(ray, selection);
  15310. }
  15311. return;
  15312. }
  15313. selection.concatWithNoDuplicate(this.entries);
  15314. }
  15315. };
  15316. OctreeBlock.prototype.createInnerBlocks = function () {
  15317. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15318. };
  15319. return OctreeBlock;
  15320. })();
  15321. BABYLON.OctreeBlock = OctreeBlock;
  15322. })(BABYLON || (BABYLON = {}));
  15323. //# sourceMappingURL=babylon.octreeBlock.js.map
  15324. var BABYLON;
  15325. (function (BABYLON) {
  15326. var Bone = (function () {
  15327. function Bone(name, skeleton, parentBone, matrix) {
  15328. this.name = name;
  15329. this.children = new Array();
  15330. this.animations = new Array();
  15331. this._worldTransform = new BABYLON.Matrix();
  15332. this._absoluteTransform = new BABYLON.Matrix();
  15333. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15334. this._skeleton = skeleton;
  15335. this._matrix = matrix;
  15336. this._baseMatrix = matrix;
  15337. skeleton.bones.push(this);
  15338. if (parentBone) {
  15339. this._parent = parentBone;
  15340. parentBone.children.push(this);
  15341. } else {
  15342. this._parent = null;
  15343. }
  15344. this._updateDifferenceMatrix();
  15345. }
  15346. // Members
  15347. Bone.prototype.getParent = function () {
  15348. return this._parent;
  15349. };
  15350. Bone.prototype.getLocalMatrix = function () {
  15351. return this._matrix;
  15352. };
  15353. Bone.prototype.getBaseMatrix = function () {
  15354. return this._baseMatrix;
  15355. };
  15356. Bone.prototype.getWorldMatrix = function () {
  15357. return this._worldTransform;
  15358. };
  15359. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15360. return this._invertedAbsoluteTransform;
  15361. };
  15362. Bone.prototype.getAbsoluteMatrix = function () {
  15363. var matrix = this._matrix.clone();
  15364. var parent = this._parent;
  15365. while (parent) {
  15366. matrix = matrix.multiply(parent.getLocalMatrix());
  15367. parent = parent.getParent();
  15368. }
  15369. return matrix;
  15370. };
  15371. // Methods
  15372. Bone.prototype.updateMatrix = function (matrix) {
  15373. this._matrix = matrix;
  15374. this._skeleton._markAsDirty();
  15375. this._updateDifferenceMatrix();
  15376. };
  15377. Bone.prototype._updateDifferenceMatrix = function () {
  15378. if (this._parent) {
  15379. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15380. } else {
  15381. this._absoluteTransform.copyFrom(this._matrix);
  15382. }
  15383. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15384. for (var index = 0; index < this.children.length; index++) {
  15385. this.children[index]._updateDifferenceMatrix();
  15386. }
  15387. };
  15388. Bone.prototype.markAsDirty = function () {
  15389. this._skeleton._markAsDirty();
  15390. };
  15391. return Bone;
  15392. })();
  15393. BABYLON.Bone = Bone;
  15394. })(BABYLON || (BABYLON = {}));
  15395. //# sourceMappingURL=babylon.bone.js.map
  15396. var BABYLON;
  15397. (function (BABYLON) {
  15398. var Skeleton = (function () {
  15399. function Skeleton(name, id, scene) {
  15400. this.name = name;
  15401. this.id = id;
  15402. this.bones = new Array();
  15403. this._isDirty = true;
  15404. this._identity = BABYLON.Matrix.Identity();
  15405. this.bones = [];
  15406. this._scene = scene;
  15407. scene.skeletons.push(this);
  15408. }
  15409. // Members
  15410. Skeleton.prototype.getTransformMatrices = function () {
  15411. return this._transformMatrices;
  15412. };
  15413. // Methods
  15414. Skeleton.prototype._markAsDirty = function () {
  15415. this._isDirty = true;
  15416. };
  15417. Skeleton.prototype.prepare = function () {
  15418. if (!this._isDirty) {
  15419. return;
  15420. }
  15421. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15422. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15423. }
  15424. for (var index = 0; index < this.bones.length; index++) {
  15425. var bone = this.bones[index];
  15426. var parentBone = bone.getParent();
  15427. if (parentBone) {
  15428. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15429. } else {
  15430. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15431. }
  15432. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15433. }
  15434. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15435. this._isDirty = false;
  15436. };
  15437. Skeleton.prototype.getAnimatables = function () {
  15438. if (!this._animatables || this._animatables.length != this.bones.length) {
  15439. this._animatables = [];
  15440. for (var index = 0; index < this.bones.length; index++) {
  15441. this._animatables.push(this.bones[index]);
  15442. }
  15443. }
  15444. return this._animatables;
  15445. };
  15446. Skeleton.prototype.clone = function (name, id) {
  15447. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15448. for (var index = 0; index < this.bones.length; index++) {
  15449. var source = this.bones[index];
  15450. var parentBone = null;
  15451. if (source.getParent()) {
  15452. var parentIndex = this.bones.indexOf(source.getParent());
  15453. parentBone = result.bones[parentIndex];
  15454. }
  15455. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15456. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15457. }
  15458. return result;
  15459. };
  15460. return Skeleton;
  15461. })();
  15462. BABYLON.Skeleton = Skeleton;
  15463. })(BABYLON || (BABYLON = {}));
  15464. //# sourceMappingURL=babylon.skeleton.js.map
  15465. var BABYLON;
  15466. (function (BABYLON) {
  15467. var PostProcess = (function () {
  15468. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15469. this.name = name;
  15470. this.width = -1;
  15471. this.height = -1;
  15472. this._reusable = false;
  15473. this._textures = new BABYLON.SmartArray(2);
  15474. this._currentRenderTextureInd = 0;
  15475. if (camera != null) {
  15476. this._camera = camera;
  15477. this._scene = camera.getScene();
  15478. camera.attachPostProcess(this);
  15479. this._engine = this._scene.getEngine();
  15480. } else {
  15481. this._engine = engine;
  15482. }
  15483. this._renderRatio = ratio;
  15484. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15485. this._reusable = reusable || false;
  15486. samplers = samplers || [];
  15487. samplers.push("textureSampler");
  15488. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15489. }
  15490. PostProcess.prototype.isReusable = function () {
  15491. return this._reusable;
  15492. };
  15493. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15494. camera = camera || this._camera;
  15495. var scene = camera.getScene();
  15496. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15497. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15498. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15499. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15500. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15501. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15502. if (this._textures.length > 0) {
  15503. for (var i = 0; i < this._textures.length; i++) {
  15504. this._engine._releaseTexture(this._textures.data[i]);
  15505. }
  15506. this._textures.reset();
  15507. }
  15508. this.width = desiredWidth;
  15509. this.height = desiredHeight;
  15510. 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 }));
  15511. if (this._reusable) {
  15512. 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 }));
  15513. }
  15514. if (this.onSizeChanged) {
  15515. this.onSizeChanged();
  15516. }
  15517. }
  15518. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15519. if (this.onActivate) {
  15520. this.onActivate(camera);
  15521. }
  15522. // Clear
  15523. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15524. if (this._reusable) {
  15525. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15526. }
  15527. };
  15528. PostProcess.prototype.apply = function () {
  15529. // Check
  15530. if (!this._effect.isReady())
  15531. return null;
  15532. // States
  15533. this._engine.enableEffect(this._effect);
  15534. this._engine.setState(false);
  15535. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15536. this._engine.setDepthBuffer(false);
  15537. this._engine.setDepthWrite(false);
  15538. // Texture
  15539. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15540. // Parameters
  15541. if (this.onApply) {
  15542. this.onApply(this._effect);
  15543. }
  15544. return this._effect;
  15545. };
  15546. PostProcess.prototype.dispose = function (camera) {
  15547. camera = camera || this._camera;
  15548. if (this._textures.length > 0) {
  15549. for (var i = 0; i < this._textures.length; i++) {
  15550. this._engine._releaseTexture(this._textures.data[i]);
  15551. }
  15552. this._textures.reset();
  15553. }
  15554. camera.detachPostProcess(this);
  15555. var index = camera._postProcesses.indexOf(this);
  15556. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15557. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15558. }
  15559. };
  15560. return PostProcess;
  15561. })();
  15562. BABYLON.PostProcess = PostProcess;
  15563. })(BABYLON || (BABYLON = {}));
  15564. //# sourceMappingURL=babylon.postProcess.js.map
  15565. var BABYLON;
  15566. (function (BABYLON) {
  15567. var PostProcessManager = (function () {
  15568. function PostProcessManager(scene) {
  15569. this._vertexDeclaration = [2];
  15570. this._vertexStrideSize = 2 * 4;
  15571. this._scene = scene;
  15572. // VBO
  15573. var vertices = [];
  15574. vertices.push(1, 1);
  15575. vertices.push(-1, 1);
  15576. vertices.push(-1, -1);
  15577. vertices.push(1, -1);
  15578. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15579. // Indices
  15580. var indices = [];
  15581. indices.push(0);
  15582. indices.push(1);
  15583. indices.push(2);
  15584. indices.push(0);
  15585. indices.push(2);
  15586. indices.push(3);
  15587. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15588. }
  15589. // Methods
  15590. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15591. var postProcesses = this._scene.activeCamera._postProcesses;
  15592. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15593. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15594. return false;
  15595. }
  15596. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15597. return true;
  15598. };
  15599. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15600. var postProcesses = this._scene.activeCamera._postProcesses;
  15601. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15602. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15603. return;
  15604. }
  15605. var engine = this._scene.getEngine();
  15606. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15607. if (index < postProcessesTakenIndices.length - 1) {
  15608. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15609. } else {
  15610. if (targetTexture) {
  15611. engine.bindFramebuffer(targetTexture);
  15612. } else {
  15613. engine.restoreDefaultFramebuffer();
  15614. }
  15615. }
  15616. if (doNotPresent) {
  15617. break;
  15618. }
  15619. var pp = postProcesses[postProcessesTakenIndices[index]];
  15620. var effect = pp.apply();
  15621. if (effect) {
  15622. if (pp.onBeforeRender) {
  15623. pp.onBeforeRender(effect);
  15624. }
  15625. // VBOs
  15626. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15627. // Draw order
  15628. engine.draw(true, 0, 6);
  15629. }
  15630. }
  15631. // Restore depth buffer
  15632. engine.setDepthBuffer(true);
  15633. engine.setDepthWrite(true);
  15634. };
  15635. PostProcessManager.prototype.dispose = function () {
  15636. if (this._vertexBuffer) {
  15637. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15638. this._vertexBuffer = null;
  15639. }
  15640. if (this._indexBuffer) {
  15641. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15642. this._indexBuffer = null;
  15643. }
  15644. };
  15645. return PostProcessManager;
  15646. })();
  15647. BABYLON.PostProcessManager = PostProcessManager;
  15648. })(BABYLON || (BABYLON = {}));
  15649. //# sourceMappingURL=babylon.postProcessManager.js.map
  15650. var BABYLON;
  15651. (function (BABYLON) {
  15652. var PassPostProcess = (function (_super) {
  15653. __extends(PassPostProcess, _super);
  15654. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15655. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15656. }
  15657. return PassPostProcess;
  15658. })(BABYLON.PostProcess);
  15659. BABYLON.PassPostProcess = PassPostProcess;
  15660. })(BABYLON || (BABYLON = {}));
  15661. //# sourceMappingURL=babylon.passPostProcess.js.map
  15662. var BABYLON;
  15663. (function (BABYLON) {
  15664. var BlurPostProcess = (function (_super) {
  15665. __extends(BlurPostProcess, _super);
  15666. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15667. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15668. var _this = this;
  15669. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15670. this.direction = direction;
  15671. this.blurWidth = blurWidth;
  15672. this.onApply = function (effect) {
  15673. effect.setFloat2("screenSize", _this.width, _this.height);
  15674. effect.setVector2("direction", _this.direction);
  15675. effect.setFloat("blurWidth", _this.blurWidth);
  15676. };
  15677. }
  15678. return BlurPostProcess;
  15679. })(BABYLON.PostProcess);
  15680. BABYLON.BlurPostProcess = BlurPostProcess;
  15681. })(BABYLON || (BABYLON = {}));
  15682. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15683. var BABYLON;
  15684. (function (BABYLON) {
  15685. var FilterPostProcess = (function (_super) {
  15686. __extends(FilterPostProcess, _super);
  15687. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15688. var _this = this;
  15689. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15690. this.kernelMatrix = kernelMatrix;
  15691. this.onApply = function (effect) {
  15692. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15693. };
  15694. }
  15695. return FilterPostProcess;
  15696. })(BABYLON.PostProcess);
  15697. BABYLON.FilterPostProcess = FilterPostProcess;
  15698. })(BABYLON || (BABYLON = {}));
  15699. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15700. var BABYLON;
  15701. (function (BABYLON) {
  15702. var RefractionPostProcess = (function (_super) {
  15703. __extends(RefractionPostProcess, _super);
  15704. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15705. var _this = this;
  15706. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15707. this.color = color;
  15708. this.depth = depth;
  15709. this.colorLevel = colorLevel;
  15710. this.onActivate = function (cam) {
  15711. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15712. };
  15713. this.onApply = function (effect) {
  15714. effect.setColor3("baseColor", _this.color);
  15715. effect.setFloat("depth", _this.depth);
  15716. effect.setFloat("colorLevel", _this.colorLevel);
  15717. effect.setTexture("refractionSampler", _this._refRexture);
  15718. };
  15719. }
  15720. // Methods
  15721. RefractionPostProcess.prototype.dispose = function (camera) {
  15722. if (this._refRexture) {
  15723. this._refRexture.dispose();
  15724. }
  15725. _super.prototype.dispose.call(this, camera);
  15726. };
  15727. return RefractionPostProcess;
  15728. })(BABYLON.PostProcess);
  15729. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15730. })(BABYLON || (BABYLON = {}));
  15731. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15732. var BABYLON;
  15733. (function (BABYLON) {
  15734. var BlackAndWhitePostProcess = (function (_super) {
  15735. __extends(BlackAndWhitePostProcess, _super);
  15736. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15737. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15738. }
  15739. return BlackAndWhitePostProcess;
  15740. })(BABYLON.PostProcess);
  15741. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15742. })(BABYLON || (BABYLON = {}));
  15743. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15744. var BABYLON;
  15745. (function (BABYLON) {
  15746. var ConvolutionPostProcess = (function (_super) {
  15747. __extends(ConvolutionPostProcess, _super);
  15748. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15749. var _this = this;
  15750. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15751. this.kernel = kernel;
  15752. this.onApply = function (effect) {
  15753. effect.setFloat2("screenSize", _this.width, _this.height);
  15754. effect.setArray("kernel", _this.kernel);
  15755. };
  15756. }
  15757. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15758. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15759. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15760. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15761. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15762. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15763. return ConvolutionPostProcess;
  15764. })(BABYLON.PostProcess);
  15765. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15766. })(BABYLON || (BABYLON = {}));
  15767. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15768. var BABYLON;
  15769. (function (BABYLON) {
  15770. var FxaaPostProcess = (function (_super) {
  15771. __extends(FxaaPostProcess, _super);
  15772. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15773. var _this = this;
  15774. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15775. this.onSizeChanged = function () {
  15776. _this.texelWidth = 1.0 / _this.width;
  15777. _this.texelHeight = 1.0 / _this.height;
  15778. };
  15779. this.onApply = function (effect) {
  15780. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15781. };
  15782. }
  15783. return FxaaPostProcess;
  15784. })(BABYLON.PostProcess);
  15785. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15786. })(BABYLON || (BABYLON = {}));
  15787. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15788. var BABYLON;
  15789. (function (BABYLON) {
  15790. var LensFlare = (function () {
  15791. function LensFlare(size, position, color, imgUrl, system) {
  15792. this.size = size;
  15793. this.position = position;
  15794. this.dispose = function () {
  15795. if (this.texture) {
  15796. this.texture.dispose();
  15797. }
  15798. // Remove from scene
  15799. var index = this._system.lensFlares.indexOf(this);
  15800. this._system.lensFlares.splice(index, 1);
  15801. };
  15802. this.color = color || new BABYLON.Color3(1, 1, 1);
  15803. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15804. this._system = system;
  15805. system.lensFlares.push(this);
  15806. }
  15807. return LensFlare;
  15808. })();
  15809. BABYLON.LensFlare = LensFlare;
  15810. })(BABYLON || (BABYLON = {}));
  15811. //# sourceMappingURL=babylon.lensFlare.js.map
  15812. var BABYLON;
  15813. (function (BABYLON) {
  15814. var LensFlareSystem = (function () {
  15815. function LensFlareSystem(name, emitter, scene) {
  15816. this.name = name;
  15817. this.lensFlares = new Array();
  15818. this.borderLimit = 300;
  15819. this._vertexDeclaration = [2];
  15820. this._vertexStrideSize = 2 * 4;
  15821. this._isEnabled = true;
  15822. this._scene = scene;
  15823. this._emitter = emitter;
  15824. scene.lensFlareSystems.push(this);
  15825. this.meshesSelectionPredicate = function (m) {
  15826. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15827. };
  15828. // VBO
  15829. var vertices = [];
  15830. vertices.push(1, 1);
  15831. vertices.push(-1, 1);
  15832. vertices.push(-1, -1);
  15833. vertices.push(1, -1);
  15834. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15835. // Indices
  15836. var indices = [];
  15837. indices.push(0);
  15838. indices.push(1);
  15839. indices.push(2);
  15840. indices.push(0);
  15841. indices.push(2);
  15842. indices.push(3);
  15843. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15844. // Effects
  15845. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15846. }
  15847. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15848. get: function () {
  15849. return this._isEnabled;
  15850. },
  15851. set: function (value) {
  15852. this._isEnabled = value;
  15853. },
  15854. enumerable: true,
  15855. configurable: true
  15856. });
  15857. LensFlareSystem.prototype.getScene = function () {
  15858. return this._scene;
  15859. };
  15860. LensFlareSystem.prototype.getEmitter = function () {
  15861. return this._emitter;
  15862. };
  15863. LensFlareSystem.prototype.getEmitterPosition = function () {
  15864. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15865. };
  15866. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15867. var position = this.getEmitterPosition();
  15868. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15869. this._positionX = position.x;
  15870. this._positionY = position.y;
  15871. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15872. if (position.z > 0) {
  15873. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15874. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15875. return true;
  15876. }
  15877. }
  15878. return false;
  15879. };
  15880. LensFlareSystem.prototype._isVisible = function () {
  15881. if (!this._isEnabled) {
  15882. return false;
  15883. }
  15884. var emitterPosition = this.getEmitterPosition();
  15885. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15886. var distance = direction.length();
  15887. direction.normalize();
  15888. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15889. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15890. return !pickInfo.hit || pickInfo.distance > distance;
  15891. };
  15892. LensFlareSystem.prototype.render = function () {
  15893. if (!this._effect.isReady())
  15894. return false;
  15895. var engine = this._scene.getEngine();
  15896. var viewport = this._scene.activeCamera.viewport;
  15897. var globalViewport = viewport.toGlobal(engine);
  15898. // Position
  15899. if (!this.computeEffectivePosition(globalViewport)) {
  15900. return false;
  15901. }
  15902. // Visibility
  15903. if (!this._isVisible()) {
  15904. return false;
  15905. }
  15906. // Intensity
  15907. var awayX;
  15908. var awayY;
  15909. if (this._positionX < this.borderLimit + globalViewport.x) {
  15910. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15911. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15912. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15913. } else {
  15914. awayX = 0;
  15915. }
  15916. if (this._positionY < this.borderLimit + globalViewport.y) {
  15917. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15918. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15919. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15920. } else {
  15921. awayY = 0;
  15922. }
  15923. var away = (awayX > awayY) ? awayX : awayY;
  15924. if (away > this.borderLimit) {
  15925. away = this.borderLimit;
  15926. }
  15927. var intensity = 1.0 - (away / this.borderLimit);
  15928. if (intensity < 0) {
  15929. return false;
  15930. }
  15931. if (intensity > 1.0) {
  15932. intensity = 1.0;
  15933. }
  15934. // Position
  15935. var centerX = globalViewport.x + globalViewport.width / 2;
  15936. var centerY = globalViewport.y + globalViewport.height / 2;
  15937. var distX = centerX - this._positionX;
  15938. var distY = centerY - this._positionY;
  15939. // Effects
  15940. engine.enableEffect(this._effect);
  15941. engine.setState(false);
  15942. engine.setDepthBuffer(false);
  15943. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15944. // VBOs
  15945. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15946. for (var index = 0; index < this.lensFlares.length; index++) {
  15947. var flare = this.lensFlares[index];
  15948. var x = centerX - (distX * flare.position);
  15949. var y = centerY - (distY * flare.position);
  15950. var cw = flare.size;
  15951. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  15952. var cx = 2 * (x / globalViewport.width) - 1.0;
  15953. var cy = 1.0 - 2 * (y / globalViewport.height);
  15954. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  15955. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  15956. // Texture
  15957. this._effect.setTexture("textureSampler", flare.texture);
  15958. // Color
  15959. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  15960. // Draw order
  15961. engine.draw(true, 0, 6);
  15962. }
  15963. engine.setDepthBuffer(true);
  15964. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15965. return true;
  15966. };
  15967. LensFlareSystem.prototype.dispose = function () {
  15968. if (this._vertexBuffer) {
  15969. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15970. this._vertexBuffer = null;
  15971. }
  15972. if (this._indexBuffer) {
  15973. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15974. this._indexBuffer = null;
  15975. }
  15976. while (this.lensFlares.length) {
  15977. this.lensFlares[0].dispose();
  15978. }
  15979. // Remove from scene
  15980. var index = this._scene.lensFlareSystems.indexOf(this);
  15981. this._scene.lensFlareSystems.splice(index, 1);
  15982. };
  15983. return LensFlareSystem;
  15984. })();
  15985. BABYLON.LensFlareSystem = LensFlareSystem;
  15986. })(BABYLON || (BABYLON = {}));
  15987. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  15988. var BABYLON;
  15989. (function (BABYLON) {
  15990. var IntersectionInfo = (function () {
  15991. function IntersectionInfo(bu, bv, distance) {
  15992. this.bu = bu;
  15993. this.bv = bv;
  15994. this.distance = distance;
  15995. this.faceId = 0;
  15996. }
  15997. return IntersectionInfo;
  15998. })();
  15999. BABYLON.IntersectionInfo = IntersectionInfo;
  16000. var PickingInfo = (function () {
  16001. function PickingInfo() {
  16002. this.hit = false;
  16003. this.distance = 0;
  16004. this.pickedPoint = null;
  16005. this.pickedMesh = null;
  16006. this.bu = 0;
  16007. this.bv = 0;
  16008. this.faceId = -1;
  16009. }
  16010. // Methods
  16011. PickingInfo.prototype.getNormal = function () {
  16012. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16013. return null;
  16014. }
  16015. var indices = this.pickedMesh.getIndices();
  16016. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16017. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16018. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16019. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16020. normal0 = normal0.scale(this.bu);
  16021. normal1 = normal1.scale(this.bv);
  16022. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16023. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16024. };
  16025. PickingInfo.prototype.getTextureCoordinates = function () {
  16026. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16027. return null;
  16028. }
  16029. var indices = this.pickedMesh.getIndices();
  16030. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16031. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16032. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16033. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16034. uv0 = uv0.scale(this.bu);
  16035. uv1 = uv1.scale(this.bv);
  16036. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16037. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16038. };
  16039. return PickingInfo;
  16040. })();
  16041. BABYLON.PickingInfo = PickingInfo;
  16042. })(BABYLON || (BABYLON = {}));
  16043. //# sourceMappingURL=babylon.pickingInfo.js.map
  16044. var BABYLON;
  16045. (function (BABYLON) {
  16046. var FilesInput = (function () {
  16047. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16048. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16049. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16050. this.engine = p_engine;
  16051. this.canvas = p_canvas;
  16052. this.currentScene = p_scene;
  16053. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16054. this.progressCallback = p_progressCallback;
  16055. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16056. this.textureLoadingCallback = p_textureLoadingCallback;
  16057. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16058. }
  16059. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16060. var _this = this;
  16061. if (p_elementToMonitor) {
  16062. this.elementToMonitor = p_elementToMonitor;
  16063. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16064. _this.drag(e);
  16065. }, false);
  16066. this.elementToMonitor.addEventListener("dragover", function (e) {
  16067. _this.drag(e);
  16068. }, false);
  16069. this.elementToMonitor.addEventListener("drop", function (e) {
  16070. _this.drop(e);
  16071. }, false);
  16072. }
  16073. };
  16074. FilesInput.prototype.renderFunction = function () {
  16075. if (this.additionnalRenderLoopLogicCallback) {
  16076. this.additionnalRenderLoopLogicCallback();
  16077. }
  16078. if (this.currentScene) {
  16079. if (this.textureLoadingCallback) {
  16080. var remaining = this.currentScene.getWaitingItemsCount();
  16081. if (remaining > 0) {
  16082. this.textureLoadingCallback(remaining);
  16083. }
  16084. }
  16085. this.currentScene.render();
  16086. }
  16087. };
  16088. FilesInput.prototype.drag = function (e) {
  16089. e.stopPropagation();
  16090. e.preventDefault();
  16091. };
  16092. FilesInput.prototype.drop = function (eventDrop) {
  16093. eventDrop.stopPropagation();
  16094. eventDrop.preventDefault();
  16095. this.loadFiles(eventDrop);
  16096. };
  16097. FilesInput.prototype.loadFiles = function (event) {
  16098. var _this = this;
  16099. var that = this;
  16100. if (this.startingProcessingFilesCallback)
  16101. this.startingProcessingFilesCallback();
  16102. var sceneFileToLoad;
  16103. var filesToLoad;
  16104. // Handling data transfer via drag'n'drop
  16105. if (event && event.dataTransfer && event.dataTransfer.files) {
  16106. filesToLoad = event.dataTransfer.files;
  16107. }
  16108. // Handling files from input files
  16109. if (event && event.target && event.target.files) {
  16110. filesToLoad = event.target.files;
  16111. }
  16112. if (filesToLoad && filesToLoad.length > 0) {
  16113. for (var i = 0; i < filesToLoad.length; i++) {
  16114. switch (filesToLoad[i].type) {
  16115. case "image/jpeg":
  16116. case "image/png":
  16117. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16118. break;
  16119. case "image/targa":
  16120. case "image/vnd.ms-dds":
  16121. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16122. break;
  16123. default:
  16124. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  16125. sceneFileToLoad = filesToLoad[i];
  16126. }
  16127. break;
  16128. }
  16129. }
  16130. // If a ".babylon" file has been provided
  16131. if (sceneFileToLoad) {
  16132. if (this.currentScene) {
  16133. this.engine.stopRenderLoop();
  16134. this.currentScene.dispose();
  16135. }
  16136. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16137. that.currentScene = newScene;
  16138. // Wait for textures and shaders to be ready
  16139. that.currentScene.executeWhenReady(function () {
  16140. // Attach camera to canvas inputs
  16141. if (that.currentScene.activeCamera) {
  16142. that.currentScene.activeCamera.attachControl(that.canvas);
  16143. }
  16144. if (that.sceneLoadedCallback) {
  16145. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16146. }
  16147. that.engine.runRenderLoop(function () {
  16148. that.renderFunction();
  16149. });
  16150. });
  16151. }, function (progress) {
  16152. if (_this.progressCallback) {
  16153. _this.progressCallback(progress);
  16154. }
  16155. });
  16156. } else {
  16157. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16158. }
  16159. }
  16160. };
  16161. FilesInput.FilesTextures = new Array();
  16162. FilesInput.FilesToLoad = new Array();
  16163. return FilesInput;
  16164. })();
  16165. BABYLON.FilesInput = FilesInput;
  16166. })(BABYLON || (BABYLON = {}));
  16167. //# sourceMappingURL=babylon.filesInput.js.map
  16168. var BABYLON;
  16169. (function (BABYLON) {
  16170. var OimoJSPlugin = (function () {
  16171. function OimoJSPlugin() {
  16172. this._registeredMeshes = [];
  16173. /**
  16174. * Update the body position according to the mesh position
  16175. * @param mesh
  16176. */
  16177. this.updateBodyPosition = function (mesh) {
  16178. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16179. var registeredMesh = this._registeredMeshes[index];
  16180. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16181. var body = registeredMesh.body.body;
  16182. mesh.computeWorldMatrix(true);
  16183. var center = mesh.getBoundingInfo().boundingBox.center;
  16184. body.setPosition(center.x, center.y, center.z);
  16185. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16186. return;
  16187. }
  16188. // Case where the parent has been updated
  16189. if (registeredMesh.mesh.parent === mesh) {
  16190. mesh.computeWorldMatrix(true);
  16191. registeredMesh.mesh.computeWorldMatrix(true);
  16192. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16193. var absoluteRotation = mesh.rotation;
  16194. body = registeredMesh.body.body;
  16195. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16196. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16197. return;
  16198. }
  16199. }
  16200. };
  16201. }
  16202. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16203. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16204. };
  16205. OimoJSPlugin.prototype.initialize = function (iterations) {
  16206. this._world = new OIMO.World();
  16207. this._world.clear();
  16208. };
  16209. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16210. this._world.gravity = gravity;
  16211. };
  16212. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16213. var body = null;
  16214. this.unregisterMesh(mesh);
  16215. mesh.computeWorldMatrix(true);
  16216. switch (impostor) {
  16217. case BABYLON.PhysicsEngine.SphereImpostor:
  16218. var initialRotation = null;
  16219. if (mesh.rotationQuaternion) {
  16220. initialRotation = mesh.rotationQuaternion.clone();
  16221. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16222. mesh.computeWorldMatrix(true);
  16223. }
  16224. var bbox = mesh.getBoundingInfo().boundingBox;
  16225. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16226. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16227. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16228. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16229. // The delta between the mesh position and the mesh bounding box center
  16230. var deltaPosition = mesh.position.subtract(bbox.center);
  16231. // Transform delta position with the rotation
  16232. if (initialRotation) {
  16233. var m = new BABYLON.Matrix();
  16234. initialRotation.toRotationMatrix(m);
  16235. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16236. }
  16237. body = new OIMO.Body({
  16238. type: 'sphere',
  16239. size: [size],
  16240. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16241. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16242. move: options.mass != 0,
  16243. config: [options.mass, options.friction, options.restitution],
  16244. world: this._world
  16245. });
  16246. // Restore rotation
  16247. if (initialRotation) {
  16248. body.setQuaternion(initialRotation);
  16249. }
  16250. this._registeredMeshes.push({
  16251. mesh: mesh,
  16252. body: body,
  16253. delta: deltaPosition
  16254. });
  16255. break;
  16256. case BABYLON.PhysicsEngine.PlaneImpostor:
  16257. case BABYLON.PhysicsEngine.BoxImpostor:
  16258. initialRotation = null;
  16259. if (mesh.rotationQuaternion) {
  16260. initialRotation = mesh.rotationQuaternion.clone();
  16261. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16262. mesh.computeWorldMatrix(true);
  16263. }
  16264. bbox = mesh.getBoundingInfo().boundingBox;
  16265. var min = bbox.minimumWorld;
  16266. var max = bbox.maximumWorld;
  16267. var box = max.subtract(min);
  16268. var sizeX = this._checkWithEpsilon(box.x);
  16269. var sizeY = this._checkWithEpsilon(box.y);
  16270. var sizeZ = this._checkWithEpsilon(box.z);
  16271. // The delta between the mesh position and the mesh boudning box center
  16272. deltaPosition = mesh.position.subtract(bbox.center);
  16273. // Transform delta position with the rotation
  16274. if (initialRotation) {
  16275. m = new BABYLON.Matrix();
  16276. initialRotation.toRotationMatrix(m);
  16277. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16278. }
  16279. body = new OIMO.Body({
  16280. type: 'box',
  16281. size: [sizeX, sizeY, sizeZ],
  16282. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16283. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16284. move: options.mass != 0,
  16285. config: [options.mass, options.friction, options.restitution],
  16286. world: this._world
  16287. });
  16288. if (initialRotation) {
  16289. body.setQuaternion(initialRotation);
  16290. }
  16291. this._registeredMeshes.push({
  16292. mesh: mesh,
  16293. body: body,
  16294. delta: deltaPosition
  16295. });
  16296. break;
  16297. }
  16298. return body;
  16299. };
  16300. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16301. var types = [], sizes = [], positions = [], rotations = [];
  16302. var initialMesh = parts[0].mesh;
  16303. for (var index = 0; index < parts.length; index++) {
  16304. var part = parts[index];
  16305. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16306. types.push(bodyParameters.type);
  16307. sizes.push.apply(sizes, bodyParameters.size);
  16308. positions.push.apply(positions, bodyParameters.pos);
  16309. rotations.push.apply(rotations, bodyParameters.rot);
  16310. }
  16311. var body = new OIMO.Body({
  16312. type: types,
  16313. size: sizes,
  16314. pos: positions,
  16315. rot: rotations,
  16316. move: options.mass != 0,
  16317. config: [options.mass, options.friction, options.restitution],
  16318. world: this._world
  16319. });
  16320. this._registeredMeshes.push({
  16321. mesh: initialMesh,
  16322. body: body
  16323. });
  16324. return body;
  16325. };
  16326. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16327. var bodyParameters = null;
  16328. var mesh = part.mesh;
  16329. switch (part.impostor) {
  16330. case BABYLON.PhysicsEngine.SphereImpostor:
  16331. var bbox = mesh.getBoundingInfo().boundingBox;
  16332. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16333. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16334. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16335. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16336. bodyParameters = {
  16337. type: 'sphere',
  16338. /* bug with oimo : sphere needs 3 sizes in this case */
  16339. size: [size, -1, -1],
  16340. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16341. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16342. };
  16343. break;
  16344. case BABYLON.PhysicsEngine.PlaneImpostor:
  16345. case BABYLON.PhysicsEngine.BoxImpostor:
  16346. bbox = mesh.getBoundingInfo().boundingBox;
  16347. var min = bbox.minimumWorld;
  16348. var max = bbox.maximumWorld;
  16349. var box = max.subtract(min);
  16350. var sizeX = this._checkWithEpsilon(box.x);
  16351. var sizeY = this._checkWithEpsilon(box.y);
  16352. var sizeZ = this._checkWithEpsilon(box.z);
  16353. var relativePosition = mesh.position;
  16354. bodyParameters = {
  16355. type: 'box',
  16356. size: [sizeX, sizeY, sizeZ],
  16357. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16358. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16359. };
  16360. break;
  16361. }
  16362. return bodyParameters;
  16363. };
  16364. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16365. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16366. var registeredMesh = this._registeredMeshes[index];
  16367. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16368. if (registeredMesh.body) {
  16369. this._world.removeRigidBody(registeredMesh.body.body);
  16370. this._unbindBody(registeredMesh.body);
  16371. }
  16372. this._registeredMeshes.splice(index, 1);
  16373. return;
  16374. }
  16375. }
  16376. };
  16377. OimoJSPlugin.prototype._unbindBody = function (body) {
  16378. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16379. var registeredMesh = this._registeredMeshes[index];
  16380. if (registeredMesh.body === body) {
  16381. registeredMesh.body = null;
  16382. }
  16383. }
  16384. };
  16385. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16386. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16387. var registeredMesh = this._registeredMeshes[index];
  16388. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16389. // Get object mass to have a behaviour similar to cannon.js
  16390. var mass = registeredMesh.body.body.massInfo.mass;
  16391. // The force is scaled with the mass of object
  16392. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16393. return;
  16394. }
  16395. }
  16396. };
  16397. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16398. var body1 = null, body2 = null;
  16399. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16400. var registeredMesh = this._registeredMeshes[index];
  16401. if (registeredMesh.mesh === mesh1) {
  16402. body1 = registeredMesh.body.body;
  16403. } else if (registeredMesh.mesh === mesh2) {
  16404. body2 = registeredMesh.body.body;
  16405. }
  16406. }
  16407. if (!body1 || !body2) {
  16408. return false;
  16409. }
  16410. if (!options) {
  16411. options = {};
  16412. }
  16413. new OIMO.Link({
  16414. type: options.type,
  16415. body1: body1,
  16416. body2: body2,
  16417. min: options.min,
  16418. max: options.max,
  16419. axe1: options.axe1,
  16420. axe2: options.axe2,
  16421. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16422. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16423. collision: options.collision,
  16424. spring: options.spring,
  16425. world: this._world
  16426. });
  16427. return true;
  16428. };
  16429. OimoJSPlugin.prototype.dispose = function () {
  16430. this._world.clear();
  16431. while (this._registeredMeshes.length) {
  16432. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16433. }
  16434. };
  16435. OimoJSPlugin.prototype.isSupported = function () {
  16436. return OIMO !== undefined;
  16437. };
  16438. OimoJSPlugin.prototype._getLastShape = function (body) {
  16439. var lastShape = body.shapes;
  16440. while (lastShape.next) {
  16441. lastShape = lastShape.next;
  16442. }
  16443. return lastShape;
  16444. };
  16445. OimoJSPlugin.prototype.runOneStep = function (time) {
  16446. this._world.step();
  16447. // Update the position of all registered meshes
  16448. var i = this._registeredMeshes.length;
  16449. var m;
  16450. while (i--) {
  16451. var body = this._registeredMeshes[i].body.body;
  16452. var mesh = this._registeredMeshes[i].mesh;
  16453. var delta = this._registeredMeshes[i].delta;
  16454. if (!body.sleeping) {
  16455. if (body.shapes.next) {
  16456. var parentShape = this._getLastShape(body);
  16457. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16458. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16459. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16460. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16461. if (!mesh.rotationQuaternion) {
  16462. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16463. }
  16464. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16465. mesh.computeWorldMatrix();
  16466. } else {
  16467. m = body.getMatrix();
  16468. mtx = BABYLON.Matrix.FromArray(m);
  16469. // Body position
  16470. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16471. if (!delta) {
  16472. mesh.position.x = bodyX;
  16473. mesh.position.y = bodyY;
  16474. mesh.position.z = bodyZ;
  16475. } else {
  16476. mesh.position.x = bodyX + delta.x;
  16477. mesh.position.y = bodyY + delta.y;
  16478. mesh.position.z = bodyZ + delta.z;
  16479. }
  16480. if (!mesh.rotationQuaternion) {
  16481. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16482. }
  16483. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16484. mesh.computeWorldMatrix();
  16485. }
  16486. }
  16487. }
  16488. };
  16489. return OimoJSPlugin;
  16490. })();
  16491. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16492. })(BABYLON || (BABYLON = {}));
  16493. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16494. var BABYLON;
  16495. (function (BABYLON) {
  16496. var PhysicsEngine = (function () {
  16497. function PhysicsEngine(plugin) {
  16498. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16499. }
  16500. PhysicsEngine.prototype._initialize = function (gravity) {
  16501. this._currentPlugin.initialize();
  16502. this._setGravity(gravity);
  16503. };
  16504. PhysicsEngine.prototype._runOneStep = function (delta) {
  16505. if (delta > 0.1) {
  16506. delta = 0.1;
  16507. } else if (delta <= 0) {
  16508. delta = 1.0 / 60.0;
  16509. }
  16510. this._currentPlugin.runOneStep(delta);
  16511. };
  16512. PhysicsEngine.prototype._setGravity = function (gravity) {
  16513. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16514. this._currentPlugin.setGravity(this.gravity);
  16515. };
  16516. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16517. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16518. };
  16519. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16520. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16521. };
  16522. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16523. this._currentPlugin.unregisterMesh(mesh);
  16524. };
  16525. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16526. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16527. };
  16528. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16529. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16530. };
  16531. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16532. this._currentPlugin.updateBodyPosition(mesh);
  16533. };
  16534. PhysicsEngine.prototype.dispose = function () {
  16535. this._currentPlugin.dispose();
  16536. };
  16537. PhysicsEngine.prototype.isSupported = function () {
  16538. return this._currentPlugin.isSupported();
  16539. };
  16540. PhysicsEngine.NoImpostor = 0;
  16541. PhysicsEngine.SphereImpostor = 1;
  16542. PhysicsEngine.BoxImpostor = 2;
  16543. PhysicsEngine.PlaneImpostor = 3;
  16544. PhysicsEngine.MeshImpostor = 4;
  16545. PhysicsEngine.CapsuleImpostor = 5;
  16546. PhysicsEngine.ConeImpostor = 6;
  16547. PhysicsEngine.CylinderImpostor = 7;
  16548. PhysicsEngine.ConvexHullImpostor = 8;
  16549. PhysicsEngine.Epsilon = 0.001;
  16550. return PhysicsEngine;
  16551. })();
  16552. BABYLON.PhysicsEngine = PhysicsEngine;
  16553. })(BABYLON || (BABYLON = {}));
  16554. //# sourceMappingURL=babylon.physicsEngine.js.map
  16555. var BABYLON;
  16556. (function (BABYLON) {
  16557. var serializeLight = function (light) {
  16558. var serializationObject = {};
  16559. serializationObject.name = light.name;
  16560. serializationObject.id = light.id;
  16561. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16562. if (light instanceof BABYLON.PointLight) {
  16563. serializationObject.type = 0;
  16564. serializationObject.position = light.position.asArray();
  16565. } else if (light instanceof BABYLON.DirectionalLight) {
  16566. serializationObject.type = 1;
  16567. var directionalLight = light;
  16568. serializationObject.position = directionalLight.position.asArray();
  16569. serializationObject.direction = directionalLight.direction.asArray();
  16570. } else if (light instanceof BABYLON.SpotLight) {
  16571. serializationObject.type = 2;
  16572. var spotLight = light;
  16573. serializationObject.position = spotLight.position.asArray();
  16574. serializationObject.direction = spotLight.position.asArray();
  16575. serializationObject.angle = spotLight.angle;
  16576. serializationObject.exponent = spotLight.exponent;
  16577. } else if (light instanceof BABYLON.HemisphericLight) {
  16578. serializationObject.type = 3;
  16579. var hemisphericLight = light;
  16580. serializationObject.direction = hemisphericLight.direction.asArray();
  16581. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16582. }
  16583. if (light.intensity) {
  16584. serializationObject.intensity = light.intensity;
  16585. }
  16586. serializationObject.range = light.range;
  16587. serializationObject.diffuse = light.diffuse.asArray();
  16588. serializationObject.specular = light.specular.asArray();
  16589. return serializationObject;
  16590. };
  16591. var serializeFresnelParameter = function (fresnelParameter) {
  16592. var serializationObject = {};
  16593. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16594. serializationObject.leftColor = fresnelParameter.leftColor;
  16595. serializationObject.rightColor = fresnelParameter.rightColor;
  16596. serializationObject.bias = fresnelParameter.bias;
  16597. serializationObject.power = fresnelParameter.power;
  16598. return serializationObject;
  16599. };
  16600. var serializeCamera = function (camera) {
  16601. var serializationObject = {};
  16602. serializationObject.name = camera.name;
  16603. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16604. serializationObject.id = camera.id;
  16605. serializationObject.position = camera.position.asArray();
  16606. // Parent
  16607. if (camera.parent) {
  16608. serializationObject.parentId = camera.parent.id;
  16609. }
  16610. // Target
  16611. serializationObject.rotation = camera.rotation.asArray();
  16612. // Locked target
  16613. if (camera.lockedTarget && camera.lockedTarget.id) {
  16614. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16615. }
  16616. serializationObject.fov = camera.fov;
  16617. serializationObject.minZ = camera.minZ;
  16618. serializationObject.maxZ = camera.maxZ;
  16619. serializationObject.speed = camera.speed;
  16620. serializationObject.inertia = camera.inertia;
  16621. serializationObject.checkCollisions = camera.checkCollisions;
  16622. serializationObject.applyGravity = camera.applyGravity;
  16623. if (camera.ellipsoid) {
  16624. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16625. }
  16626. // Animations
  16627. appendAnimations(camera, serializationObject);
  16628. // Layer mask
  16629. serializationObject.layerMask = camera.layerMask;
  16630. return serializationObject;
  16631. };
  16632. var appendAnimations = function (source, destination) {
  16633. if (source.animations) {
  16634. destination.animations = [];
  16635. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16636. var animation = source.animations[animationIndex];
  16637. destination.animations.push(serializeAnimation(animation));
  16638. }
  16639. }
  16640. };
  16641. var serializeAnimation = function (animation) {
  16642. var serializationObject = {};
  16643. serializationObject.name = animation.name;
  16644. serializationObject.property = animation.targetProperty;
  16645. serializationObject.framePerSecond = animation.framePerSecond;
  16646. serializationObject.dataType = animation.dataType;
  16647. serializationObject.loopBehavior = animation.loopMode;
  16648. var dataType = animation.dataType;
  16649. serializationObject.keys = [];
  16650. var keys = animation.getKeys();
  16651. for (var index = 0; index < keys.length; index++) {
  16652. var animationKey = keys[index];
  16653. var key = {};
  16654. key.frame = animationKey.frame;
  16655. switch (dataType) {
  16656. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16657. key.values = [animationKey.value];
  16658. break;
  16659. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16660. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16661. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16662. key.values = animationKey.value.asArray();
  16663. break;
  16664. }
  16665. serializationObject.keys.push(key);
  16666. }
  16667. return serializationObject;
  16668. };
  16669. var serializeMultiMaterial = function (material) {
  16670. var serializationObject = {};
  16671. serializationObject.name = material.name;
  16672. serializationObject.id = material.id;
  16673. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16674. serializationObject.materials = [];
  16675. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16676. var subMat = material.subMaterials[matIndex];
  16677. if (subMat) {
  16678. serializationObject.materials.push(subMat.id);
  16679. } else {
  16680. serializationObject.materials.push(null);
  16681. }
  16682. }
  16683. return serializationObject;
  16684. };
  16685. var serializeMaterial = function (material) {
  16686. var serializationObject = {};
  16687. serializationObject.name = material.name;
  16688. serializationObject.ambient = material.ambientColor.asArray();
  16689. serializationObject.diffuse = material.diffuseColor.asArray();
  16690. serializationObject.specular = material.specularColor.asArray();
  16691. serializationObject.specularPower = material.specularPower;
  16692. serializationObject.emissive = material.emissiveColor.asArray();
  16693. serializationObject.alpha = material.alpha;
  16694. serializationObject.id = material.id;
  16695. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16696. serializationObject.backFaceCulling = material.backFaceCulling;
  16697. if (material.diffuseTexture) {
  16698. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16699. }
  16700. if (material.diffuseFresnelParameters) {
  16701. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16702. }
  16703. if (material.ambientTexture) {
  16704. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16705. }
  16706. if (material.opacityTexture) {
  16707. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16708. }
  16709. if (material.opacityFresnelParameters) {
  16710. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16711. }
  16712. if (material.reflectionTexture) {
  16713. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16714. }
  16715. if (material.reflectionFresnelParameters) {
  16716. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16717. }
  16718. if (material.emissiveTexture) {
  16719. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16720. }
  16721. if (material.emissiveFresnelParameters) {
  16722. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16723. }
  16724. if (material.specularTexture) {
  16725. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16726. }
  16727. if (material.bumpTexture) {
  16728. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16729. }
  16730. return serializationObject;
  16731. };
  16732. var serializeTexture = function (texture) {
  16733. var serializationObject = {};
  16734. if (!texture.name) {
  16735. return null;
  16736. }
  16737. if (texture instanceof BABYLON.CubeTexture) {
  16738. serializationObject.name = texture.name;
  16739. serializationObject.hasAlpha = texture.hasAlpha;
  16740. serializationObject.level = texture.level;
  16741. serializationObject.coordinatesMode = texture.coordinatesMode;
  16742. return serializationObject;
  16743. }
  16744. if (texture instanceof BABYLON.MirrorTexture) {
  16745. var mirrorTexture = texture;
  16746. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16747. serializationObject.renderList = [];
  16748. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16749. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16750. }
  16751. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16752. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16753. var renderTargetTexture = texture;
  16754. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16755. serializationObject.renderList = [];
  16756. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16757. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16758. }
  16759. }
  16760. var regularTexture = texture;
  16761. serializationObject.name = texture.name;
  16762. serializationObject.hasAlpha = texture.hasAlpha;
  16763. serializationObject.level = texture.level;
  16764. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16765. serializationObject.coordinatesMode = texture.coordinatesMode;
  16766. serializationObject.uOffset = regularTexture.uOffset;
  16767. serializationObject.vOffset = regularTexture.vOffset;
  16768. serializationObject.uScale = regularTexture.uScale;
  16769. serializationObject.vScale = regularTexture.vScale;
  16770. serializationObject.uAng = regularTexture.uAng;
  16771. serializationObject.vAng = regularTexture.vAng;
  16772. serializationObject.wAng = regularTexture.wAng;
  16773. serializationObject.wrapU = texture.wrapU;
  16774. serializationObject.wrapV = texture.wrapV;
  16775. // Animations
  16776. appendAnimations(texture, serializationObject);
  16777. return serializationObject;
  16778. };
  16779. var serializeSkeleton = function (skeleton) {
  16780. var serializationObject = {};
  16781. serializationObject.name = skeleton.name;
  16782. serializationObject.id = skeleton.id;
  16783. serializationObject.bones = [];
  16784. for (var index = 0; index < skeleton.bones.length; index++) {
  16785. var bone = skeleton.bones[index];
  16786. var serializedBone = {
  16787. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16788. name: bone.name,
  16789. matrix: bone.getLocalMatrix().toArray()
  16790. };
  16791. serializationObject.bones.push(serializedBone);
  16792. if (bone.animations && bone.animations.length > 0) {
  16793. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16794. }
  16795. }
  16796. return serializationObject;
  16797. };
  16798. var serializeParticleSystem = function (particleSystem) {
  16799. var serializationObject = {};
  16800. serializationObject.emitterId = particleSystem.emitter.id;
  16801. serializationObject.capacity = particleSystem.getCapacity();
  16802. if (particleSystem.particleTexture) {
  16803. serializationObject.textureName = particleSystem.particleTexture.name;
  16804. }
  16805. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16806. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16807. serializationObject.minSize = particleSystem.minSize;
  16808. serializationObject.maxSize = particleSystem.maxSize;
  16809. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16810. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16811. serializationObject.emitRate = particleSystem.emitRate;
  16812. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16813. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16814. serializationObject.gravity = particleSystem.gravity.asArray();
  16815. serializationObject.direction1 = particleSystem.direction1.asArray();
  16816. serializationObject.direction2 = particleSystem.direction2.asArray();
  16817. serializationObject.color1 = particleSystem.color1.asArray();
  16818. serializationObject.color2 = particleSystem.color2.asArray();
  16819. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16820. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16821. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16822. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16823. serializationObject.blendMode = particleSystem.blendMode;
  16824. return serializationObject;
  16825. };
  16826. var serializeLensFlareSystem = function (lensFlareSystem) {
  16827. var serializationObject = {};
  16828. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16829. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16830. serializationObject.flares = [];
  16831. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16832. var flare = lensFlareSystem.lensFlares[index];
  16833. serializationObject.flares.push({
  16834. size: flare.size,
  16835. position: flare.position,
  16836. color: flare.color.asArray(),
  16837. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16838. });
  16839. }
  16840. return serializationObject;
  16841. };
  16842. var serializeShadowGenerator = function (light) {
  16843. var serializationObject = {};
  16844. var shadowGenerator = light.getShadowGenerator();
  16845. serializationObject.lightId = light.id;
  16846. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16847. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16848. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16849. serializationObject.renderList = [];
  16850. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16851. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16852. serializationObject.renderList.push(mesh.id);
  16853. }
  16854. return serializationObject;
  16855. };
  16856. var serializedGeometries = [];
  16857. var serializeGeometry = function (geometry, serializationGeometries) {
  16858. if (serializedGeometries[geometry.id]) {
  16859. return;
  16860. }
  16861. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16862. serializationGeometries.boxes.push(serializeBox(geometry));
  16863. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16864. serializationGeometries.spheres.push(serializeSphere(geometry));
  16865. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16866. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16867. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16868. serializationGeometries.toruses.push(serializeTorus(geometry));
  16869. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16870. serializationGeometries.grounds.push(serializeGround(geometry));
  16871. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16872. serializationGeometries.planes.push(serializePlane(geometry));
  16873. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16874. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16875. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16876. throw new Error("Unknow primitive type");
  16877. } else {
  16878. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16879. }
  16880. serializedGeometries[geometry.id] = true;
  16881. };
  16882. var serializeGeometryBase = function (geometry) {
  16883. var serializationObject = {};
  16884. serializationObject.id = geometry.id;
  16885. if (BABYLON.Tags.HasTags(geometry)) {
  16886. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16887. }
  16888. return serializationObject;
  16889. };
  16890. var serializeVertexData = function (vertexData) {
  16891. var serializationObject = serializeGeometryBase(vertexData);
  16892. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16893. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16894. }
  16895. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16896. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16897. }
  16898. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16899. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16900. }
  16901. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16902. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16903. }
  16904. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16905. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16906. }
  16907. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16908. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16909. serializationObject.matricesIndices._isExpanded = true;
  16910. }
  16911. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16912. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16913. }
  16914. serializationObject.indices = vertexData.getIndices();
  16915. return serializationObject;
  16916. };
  16917. var serializePrimitive = function (primitive) {
  16918. var serializationObject = serializeGeometryBase(primitive);
  16919. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16920. return serializationObject;
  16921. };
  16922. var serializeBox = function (box) {
  16923. var serializationObject = serializePrimitive(box);
  16924. serializationObject.size = box.size;
  16925. return serializationObject;
  16926. };
  16927. var serializeSphere = function (sphere) {
  16928. var serializationObject = serializePrimitive(sphere);
  16929. serializationObject.segments = sphere.segments;
  16930. serializationObject.diameter = sphere.diameter;
  16931. return serializationObject;
  16932. };
  16933. var serializeCylinder = function (cylinder) {
  16934. var serializationObject = serializePrimitive(cylinder);
  16935. serializationObject.height = cylinder.height;
  16936. serializationObject.diameterTop = cylinder.diameterTop;
  16937. serializationObject.diameterBottom = cylinder.diameterBottom;
  16938. serializationObject.tessellation = cylinder.tessellation;
  16939. return serializationObject;
  16940. };
  16941. var serializeTorus = function (torus) {
  16942. var serializationObject = serializePrimitive(torus);
  16943. serializationObject.diameter = torus.diameter;
  16944. serializationObject.thickness = torus.thickness;
  16945. serializationObject.tessellation = torus.tessellation;
  16946. return serializationObject;
  16947. };
  16948. var serializeGround = function (ground) {
  16949. var serializationObject = serializePrimitive(ground);
  16950. serializationObject.width = ground.width;
  16951. serializationObject.height = ground.height;
  16952. serializationObject.subdivisions = ground.subdivisions;
  16953. return serializationObject;
  16954. };
  16955. var serializePlane = function (plane) {
  16956. var serializationObject = serializePrimitive(plane);
  16957. serializationObject.size = plane.size;
  16958. return serializationObject;
  16959. };
  16960. var serializeTorusKnot = function (torusKnot) {
  16961. var serializationObject = serializePrimitive(torusKnot);
  16962. serializationObject.radius = torusKnot.radius;
  16963. serializationObject.tube = torusKnot.tube;
  16964. serializationObject.radialSegments = torusKnot.radialSegments;
  16965. serializationObject.tubularSegments = torusKnot.tubularSegments;
  16966. serializationObject.p = torusKnot.p;
  16967. serializationObject.q = torusKnot.q;
  16968. return serializationObject;
  16969. };
  16970. var serializeMesh = function (mesh, serializationScene) {
  16971. var serializationObject = {};
  16972. serializationObject.name = mesh.name;
  16973. serializationObject.id = mesh.id;
  16974. if (BABYLON.Tags.HasTags(mesh)) {
  16975. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  16976. }
  16977. serializationObject.position = mesh.position.asArray();
  16978. if (mesh.rotationQuaternion) {
  16979. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  16980. } else if (mesh.rotation) {
  16981. serializationObject.rotation = mesh.rotation.asArray();
  16982. }
  16983. serializationObject.scaling = mesh.scaling.asArray();
  16984. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  16985. serializationObject.isEnabled = mesh.isEnabled();
  16986. serializationObject.isVisible = mesh.isVisible;
  16987. serializationObject.infiniteDistance = mesh.infiniteDistance;
  16988. serializationObject.pickable = mesh.isPickable;
  16989. serializationObject.receiveShadows = mesh.receiveShadows;
  16990. serializationObject.billboardMode = mesh.billboardMode;
  16991. serializationObject.visibility = mesh.visibility;
  16992. serializationObject.checkCollisions = mesh.checkCollisions;
  16993. // Parent
  16994. if (mesh.parent) {
  16995. serializationObject.parentId = mesh.parent.id;
  16996. }
  16997. // Geometry
  16998. var geometry = mesh._geometry;
  16999. if (geometry) {
  17000. var geometryId = geometry.id;
  17001. serializationObject.geometryId = geometryId;
  17002. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17003. // 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
  17004. serializeGeometry(geometry, serializationScene.geometries);
  17005. }
  17006. // SubMeshes
  17007. serializationObject.subMeshes = [];
  17008. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17009. var subMesh = mesh.subMeshes[subIndex];
  17010. serializationObject.subMeshes.push({
  17011. materialIndex: subMesh.materialIndex,
  17012. verticesStart: subMesh.verticesStart,
  17013. verticesCount: subMesh.verticesCount,
  17014. indexStart: subMesh.indexStart,
  17015. indexCount: subMesh.indexCount
  17016. });
  17017. }
  17018. }
  17019. // Material
  17020. if (mesh.material) {
  17021. serializationObject.materialId = mesh.material.id;
  17022. } else {
  17023. mesh.material = null;
  17024. }
  17025. // Skeleton
  17026. if (mesh.skeleton) {
  17027. serializationObject.skeletonId = mesh.skeleton.id;
  17028. }
  17029. // Physics
  17030. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17031. serializationObject.physicsMass = mesh.getPhysicsMass();
  17032. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17033. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17034. switch (mesh.getPhysicsImpostor()) {
  17035. case BABYLON.PhysicsEngine.BoxImpostor:
  17036. serializationObject.physicsImpostor = 1;
  17037. break;
  17038. case BABYLON.PhysicsEngine.SphereImpostor:
  17039. serializationObject.physicsImpostor = 2;
  17040. break;
  17041. }
  17042. }
  17043. // Instances
  17044. serializationObject.instances = [];
  17045. for (var index = 0; index < mesh.instances.length; index++) {
  17046. var instance = mesh.instances[index];
  17047. var serializationInstance = {
  17048. name: instance.name,
  17049. position: instance.position,
  17050. rotation: instance.rotation,
  17051. rotationQuaternion: instance.rotationQuaternion,
  17052. scaling: instance.scaling
  17053. };
  17054. serializationObject.instances.push(serializationInstance);
  17055. // Animations
  17056. appendAnimations(instance, serializationInstance);
  17057. }
  17058. // Animations
  17059. appendAnimations(mesh, serializationObject);
  17060. // Layer mask
  17061. serializationObject.layerMask = mesh.layerMask;
  17062. return serializationObject;
  17063. };
  17064. var SceneSerializer = (function () {
  17065. function SceneSerializer() {
  17066. }
  17067. SceneSerializer.Serialize = function (scene) {
  17068. var serializationObject = {};
  17069. // Scene
  17070. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17071. serializationObject.autoClear = scene.autoClear;
  17072. serializationObject.clearColor = scene.clearColor.asArray();
  17073. serializationObject.ambientColor = scene.ambientColor.asArray();
  17074. serializationObject.gravity = scene.gravity.asArray();
  17075. // Fog
  17076. if (scene.fogMode && scene.fogMode !== 0) {
  17077. serializationObject.fogMode = scene.fogMode;
  17078. serializationObject.fogColor = scene.fogColor.asArray();
  17079. serializationObject.fogStart = scene.fogStart;
  17080. serializationObject.fogEnd = scene.fogEnd;
  17081. serializationObject.fogDensity = scene.fogDensity;
  17082. }
  17083. // Lights
  17084. serializationObject.lights = [];
  17085. for (var index = 0; index < scene.lights.length; index++) {
  17086. var light = scene.lights[index];
  17087. serializationObject.lights.push(serializeLight(light));
  17088. }
  17089. // Cameras
  17090. serializationObject.cameras = [];
  17091. for (index = 0; index < scene.cameras.length; index++) {
  17092. var camera = scene.cameras[index];
  17093. if (camera instanceof BABYLON.FreeCamera) {
  17094. serializationObject.cameras.push(serializeCamera(camera));
  17095. }
  17096. }
  17097. if (scene.activeCamera) {
  17098. serializationObject.activeCameraID = scene.activeCamera.id;
  17099. }
  17100. // Materials
  17101. serializationObject.materials = [];
  17102. serializationObject.multiMaterials = [];
  17103. for (index = 0; index < scene.materials.length; index++) {
  17104. var material = scene.materials[index];
  17105. if (material instanceof BABYLON.StandardMaterial) {
  17106. serializationObject.materials.push(serializeMaterial(material));
  17107. } else if (material instanceof BABYLON.MultiMaterial) {
  17108. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17109. }
  17110. }
  17111. // Skeletons
  17112. serializationObject.skeletons = [];
  17113. for (index = 0; index < scene.skeletons.length; index++) {
  17114. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17115. }
  17116. // Geometries
  17117. serializationObject.geometries = {};
  17118. serializationObject.geometries.boxes = [];
  17119. serializationObject.geometries.spheres = [];
  17120. serializationObject.geometries.cylinders = [];
  17121. serializationObject.geometries.toruses = [];
  17122. serializationObject.geometries.grounds = [];
  17123. serializationObject.geometries.planes = [];
  17124. serializationObject.geometries.torusKnots = [];
  17125. serializationObject.geometries.vertexData = [];
  17126. serializedGeometries = [];
  17127. var geometries = scene.getGeometries();
  17128. for (var index = 0; index < geometries.length; index++) {
  17129. var geometry = geometries[index];
  17130. if (geometry.isReady()) {
  17131. serializeGeometry(geometry, serializationObject.geometries);
  17132. }
  17133. }
  17134. // Meshes
  17135. serializationObject.meshes = [];
  17136. for (index = 0; index < scene.meshes.length; index++) {
  17137. var abstractMesh = scene.meshes[index];
  17138. if (abstractMesh instanceof BABYLON.Mesh) {
  17139. var mesh = abstractMesh;
  17140. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17141. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17142. }
  17143. }
  17144. }
  17145. // Particles Systems
  17146. serializationObject.particleSystems = [];
  17147. for (index = 0; index < scene.particleSystems.length; index++) {
  17148. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17149. }
  17150. // Lens flares
  17151. serializationObject.lensFlareSystems = [];
  17152. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17153. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17154. }
  17155. // Shadows
  17156. serializationObject.shadowGenerators = [];
  17157. for (index = 0; index < scene.lights.length; index++) {
  17158. light = scene.lights[index];
  17159. if (light.getShadowGenerator()) {
  17160. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17161. }
  17162. }
  17163. return serializationObject;
  17164. };
  17165. return SceneSerializer;
  17166. })();
  17167. BABYLON.SceneSerializer = SceneSerializer;
  17168. })(BABYLON || (BABYLON = {}));
  17169. //# sourceMappingURL=babylon.sceneSerializer.js.map
  17170. var BABYLON;
  17171. (function (BABYLON) {
  17172. var SceneLoader = (function () {
  17173. function SceneLoader() {
  17174. }
  17175. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17176. get: function () {
  17177. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17178. },
  17179. set: function (value) {
  17180. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17181. },
  17182. enumerable: true,
  17183. configurable: true
  17184. });
  17185. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17186. get: function () {
  17187. return SceneLoader._ShowLoadingScreen;
  17188. },
  17189. set: function (value) {
  17190. SceneLoader._ShowLoadingScreen = value;
  17191. },
  17192. enumerable: true,
  17193. configurable: true
  17194. });
  17195. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17196. var dotPosition = sceneFilename.lastIndexOf(".");
  17197. var queryStringPosition = sceneFilename.indexOf("?");
  17198. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17199. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17200. var plugin = this._registeredPlugins[index];
  17201. if (plugin.extensions.indexOf(extension) !== -1) {
  17202. return plugin;
  17203. }
  17204. }
  17205. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17206. };
  17207. // Public functions
  17208. SceneLoader.RegisterPlugin = function (plugin) {
  17209. plugin.extensions = plugin.extensions.toLowerCase();
  17210. SceneLoader._registeredPlugins.push(plugin);
  17211. };
  17212. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17213. var manifestChecked = function (success) {
  17214. scene.database = database;
  17215. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17216. var importMeshFromData = function (data) {
  17217. var meshes = [];
  17218. var particleSystems = [];
  17219. var skeletons = [];
  17220. try {
  17221. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17222. if (onerror) {
  17223. onerror(scene, 'unable to load the scene');
  17224. }
  17225. return;
  17226. }
  17227. } catch (e) {
  17228. if (onerror) {
  17229. onerror(scene, e);
  17230. }
  17231. return;
  17232. }
  17233. if (onsuccess) {
  17234. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17235. onsuccess(meshes, particleSystems, skeletons);
  17236. }
  17237. };
  17238. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17239. // Direct load
  17240. importMeshFromData(sceneFilename.substr(5));
  17241. return;
  17242. }
  17243. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17244. importMeshFromData(data);
  17245. }, progressCallBack, database);
  17246. };
  17247. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17248. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17249. };
  17250. /**
  17251. * Load a scene
  17252. * @param rootUrl a string that defines the root url for scene and resources
  17253. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17254. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17255. */
  17256. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17257. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17258. };
  17259. /**
  17260. * Append a scene
  17261. * @param rootUrl a string that defines the root url for scene and resources
  17262. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17263. * @param scene is the instance of BABYLON.Scene to append to
  17264. */
  17265. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17266. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17267. var database;
  17268. if (SceneLoader.ShowLoadingScreen) {
  17269. scene.getEngine().displayLoadingUI();
  17270. }
  17271. var loadSceneFromData = function (data) {
  17272. scene.database = database;
  17273. if (!plugin.load(scene, data, rootUrl)) {
  17274. if (onerror) {
  17275. onerror(scene);
  17276. }
  17277. scene.getEngine().hideLoadingUI();
  17278. return;
  17279. }
  17280. if (onsuccess) {
  17281. onsuccess(scene);
  17282. }
  17283. if (SceneLoader.ShowLoadingScreen) {
  17284. scene.executeWhenReady(function () {
  17285. scene.getEngine().hideLoadingUI();
  17286. });
  17287. }
  17288. };
  17289. var manifestChecked = function (success) {
  17290. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17291. };
  17292. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17293. // Direct load
  17294. loadSceneFromData(sceneFilename.substr(5));
  17295. return;
  17296. }
  17297. if (rootUrl.indexOf("file:") === -1) {
  17298. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17299. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17300. } else {
  17301. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17302. }
  17303. };
  17304. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17305. SceneLoader._ShowLoadingScreen = true;
  17306. SceneLoader._registeredPlugins = new Array();
  17307. return SceneLoader;
  17308. })();
  17309. BABYLON.SceneLoader = SceneLoader;
  17310. ;
  17311. })(BABYLON || (BABYLON = {}));
  17312. //# sourceMappingURL=babylon.sceneLoader.js.map
  17313. var BABYLON;
  17314. (function (BABYLON) {
  17315. (function (Internals) {
  17316. var checkColors4 = function (colors, count) {
  17317. // Check if color3 was used
  17318. if (colors.length === count * 3) {
  17319. var colors4 = [];
  17320. for (var index = 0; index < colors.length; index += 3) {
  17321. var newIndex = (index / 3) * 4;
  17322. colors4[newIndex] = colors[index];
  17323. colors4[newIndex + 1] = colors[index + 1];
  17324. colors4[newIndex + 2] = colors[index + 2];
  17325. colors4[newIndex + 3] = 1.0;
  17326. }
  17327. return colors4;
  17328. }
  17329. return colors;
  17330. };
  17331. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17332. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17333. texture.name = parsedTexture.name;
  17334. texture.hasAlpha = parsedTexture.hasAlpha;
  17335. texture.level = parsedTexture.level;
  17336. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17337. return texture;
  17338. };
  17339. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17340. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17341. return null;
  17342. }
  17343. if (parsedTexture.isCube) {
  17344. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17345. }
  17346. var texture;
  17347. if (parsedTexture.mirrorPlane) {
  17348. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17349. texture._waitingRenderList = parsedTexture.renderList;
  17350. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17351. } else if (parsedTexture.isRenderTarget) {
  17352. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17353. texture._waitingRenderList = parsedTexture.renderList;
  17354. } else {
  17355. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17356. }
  17357. texture.name = parsedTexture.name;
  17358. texture.hasAlpha = parsedTexture.hasAlpha;
  17359. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17360. texture.level = parsedTexture.level;
  17361. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17362. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17363. texture.uOffset = parsedTexture.uOffset;
  17364. texture.vOffset = parsedTexture.vOffset;
  17365. texture.uScale = parsedTexture.uScale;
  17366. texture.vScale = parsedTexture.vScale;
  17367. texture.uAng = parsedTexture.uAng;
  17368. texture.vAng = parsedTexture.vAng;
  17369. texture.wAng = parsedTexture.wAng;
  17370. texture.wrapU = parsedTexture.wrapU;
  17371. texture.wrapV = parsedTexture.wrapV;
  17372. // Animations
  17373. if (parsedTexture.animations) {
  17374. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17375. var parsedAnimation = parsedTexture.animations[animationIndex];
  17376. texture.animations.push(parseAnimation(parsedAnimation));
  17377. }
  17378. }
  17379. return texture;
  17380. };
  17381. var parseSkeleton = function (parsedSkeleton, scene) {
  17382. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17383. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17384. var parsedBone = parsedSkeleton.bones[index];
  17385. var parentBone = null;
  17386. if (parsedBone.parentBoneIndex > -1) {
  17387. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17388. }
  17389. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17390. if (parsedBone.animation) {
  17391. bone.animations.push(parseAnimation(parsedBone.animation));
  17392. }
  17393. }
  17394. return skeleton;
  17395. };
  17396. var parseFresnelParameters = function (parsedFresnelParameters) {
  17397. var fresnelParameters = new BABYLON.FresnelParameters();
  17398. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17399. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17400. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17401. fresnelParameters.bias = parsedFresnelParameters.bias;
  17402. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17403. return fresnelParameters;
  17404. };
  17405. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17406. var material;
  17407. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17408. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17409. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17410. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17411. material.specularPower = parsedMaterial.specularPower;
  17412. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17413. material.alpha = parsedMaterial.alpha;
  17414. material.id = parsedMaterial.id;
  17415. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17416. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17417. material.wireframe = parsedMaterial.wireframe;
  17418. if (parsedMaterial.diffuseTexture) {
  17419. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17420. }
  17421. if (parsedMaterial.diffuseFresnelParameters) {
  17422. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17423. }
  17424. if (parsedMaterial.ambientTexture) {
  17425. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17426. }
  17427. if (parsedMaterial.opacityTexture) {
  17428. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17429. }
  17430. if (parsedMaterial.opacityFresnelParameters) {
  17431. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17432. }
  17433. if (parsedMaterial.reflectionTexture) {
  17434. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17435. }
  17436. if (parsedMaterial.reflectionFresnelParameters) {
  17437. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17438. }
  17439. if (parsedMaterial.emissiveTexture) {
  17440. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17441. }
  17442. if (parsedMaterial.emissiveFresnelParameters) {
  17443. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17444. }
  17445. if (parsedMaterial.specularTexture) {
  17446. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17447. }
  17448. if (parsedMaterial.bumpTexture) {
  17449. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17450. }
  17451. return material;
  17452. };
  17453. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17454. for (var index = 0; index < parsedData.materials.length; index++) {
  17455. var parsedMaterial = parsedData.materials[index];
  17456. if (parsedMaterial.id === id) {
  17457. return parseMaterial(parsedMaterial, scene, rootUrl);
  17458. }
  17459. }
  17460. return null;
  17461. };
  17462. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17463. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17464. multiMaterial.id = parsedMultiMaterial.id;
  17465. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17466. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17467. var subMatId = parsedMultiMaterial.materials[matIndex];
  17468. if (subMatId) {
  17469. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17470. } else {
  17471. multiMaterial.subMaterials.push(null);
  17472. }
  17473. }
  17474. return multiMaterial;
  17475. };
  17476. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17477. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17478. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17479. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17480. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17481. var parsedFlare = parsedLensFlareSystem.flares[index];
  17482. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17483. }
  17484. return lensFlareSystem;
  17485. };
  17486. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17487. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17488. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17489. if (parsedParticleSystem.textureName) {
  17490. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17491. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17492. }
  17493. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17494. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17495. particleSystem.minSize = parsedParticleSystem.minSize;
  17496. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17497. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17498. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17499. particleSystem.emitter = emitter;
  17500. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17501. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17502. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17503. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17504. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17505. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17506. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17507. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17508. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17509. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17510. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17511. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17512. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17513. particleSystem.start();
  17514. return particleSystem;
  17515. };
  17516. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17517. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17518. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17519. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17520. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17521. shadowGenerator.getShadowMap().renderList.push(mesh);
  17522. }
  17523. if (parsedShadowGenerator.usePoissonSampling) {
  17524. shadowGenerator.usePoissonSampling = true;
  17525. } else {
  17526. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17527. }
  17528. return shadowGenerator;
  17529. };
  17530. var parseAnimation = function (parsedAnimation) {
  17531. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17532. var dataType = parsedAnimation.dataType;
  17533. var keys = [];
  17534. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17535. var key = parsedAnimation.keys[index];
  17536. var data;
  17537. switch (dataType) {
  17538. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17539. data = key.values[0];
  17540. break;
  17541. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17542. data = BABYLON.Quaternion.FromArray(key.values);
  17543. break;
  17544. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17545. data = BABYLON.Matrix.FromArray(key.values);
  17546. break;
  17547. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17548. default:
  17549. data = BABYLON.Vector3.FromArray(key.values);
  17550. break;
  17551. }
  17552. keys.push({
  17553. frame: key.frame,
  17554. value: data
  17555. });
  17556. }
  17557. animation.setKeys(keys);
  17558. return animation;
  17559. };
  17560. var parseLight = function (parsedLight, scene) {
  17561. var light;
  17562. switch (parsedLight.type) {
  17563. case 0:
  17564. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17565. break;
  17566. case 1:
  17567. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17568. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17569. break;
  17570. case 2:
  17571. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17572. break;
  17573. case 3:
  17574. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17575. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17576. break;
  17577. }
  17578. light.id = parsedLight.id;
  17579. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17580. if (parsedLight.intensity !== undefined) {
  17581. light.intensity = parsedLight.intensity;
  17582. }
  17583. if (parsedLight.range) {
  17584. light.range = parsedLight.range;
  17585. }
  17586. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17587. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17588. if (parsedLight.excludedMeshesIds) {
  17589. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17590. }
  17591. // Parent
  17592. if (parsedLight.parentId) {
  17593. light._waitingParentId = parsedLight.parentId;
  17594. }
  17595. if (parsedLight.includedOnlyMeshesIds) {
  17596. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17597. }
  17598. // Animations
  17599. if (parsedLight.animations) {
  17600. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17601. var parsedAnimation = parsedLight.animations[animationIndex];
  17602. light.animations.push(parseAnimation(parsedAnimation));
  17603. }
  17604. }
  17605. if (parsedLight.autoAnimate) {
  17606. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17607. }
  17608. };
  17609. var parseCamera = function (parsedCamera, scene) {
  17610. var camera;
  17611. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17612. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17613. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17614. var alpha = parsedCamera.alpha;
  17615. var beta = parsedCamera.beta;
  17616. var radius = parsedCamera.radius;
  17617. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17618. var eye_space = parsedCamera.eye_space;
  17619. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17620. } else {
  17621. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17622. }
  17623. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17624. var eye_space = parsedCamera.eye_space;
  17625. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17626. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17627. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17628. } else if (parsedCamera.type === "FollowCamera") {
  17629. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17630. camera.heightOffset = parsedCamera.heightOffset;
  17631. camera.radius = parsedCamera.radius;
  17632. camera.rotationOffset = parsedCamera.rotationOffset;
  17633. if (lockedTargetMesh)
  17634. camera.target = lockedTargetMesh;
  17635. } else if (parsedCamera.type === "GamepadCamera") {
  17636. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17637. } else if (parsedCamera.type === "OculusCamera") {
  17638. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17639. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17640. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17641. } else if (parsedCamera.type === "TouchCamera") {
  17642. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17643. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17644. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17645. } else if (parsedCamera.type === "WebVRCamera") {
  17646. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17647. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17648. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17649. } else {
  17650. // Free Camera is the default value
  17651. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17652. }
  17653. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17654. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17655. camera.lockedTarget = lockedTargetMesh;
  17656. }
  17657. camera.id = parsedCamera.id;
  17658. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17659. // Parent
  17660. if (parsedCamera.parentId) {
  17661. camera._waitingParentId = parsedCamera.parentId;
  17662. }
  17663. // Target
  17664. if (parsedCamera.target) {
  17665. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17666. } else {
  17667. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17668. }
  17669. camera.fov = parsedCamera.fov;
  17670. camera.minZ = parsedCamera.minZ;
  17671. camera.maxZ = parsedCamera.maxZ;
  17672. camera.speed = parsedCamera.speed;
  17673. camera.inertia = parsedCamera.inertia;
  17674. camera.checkCollisions = parsedCamera.checkCollisions;
  17675. camera.applyGravity = parsedCamera.applyGravity;
  17676. if (parsedCamera.ellipsoid) {
  17677. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17678. }
  17679. // Animations
  17680. if (parsedCamera.animations) {
  17681. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17682. var parsedAnimation = parsedCamera.animations[animationIndex];
  17683. camera.animations.push(parseAnimation(parsedAnimation));
  17684. }
  17685. }
  17686. if (parsedCamera.autoAnimate) {
  17687. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17688. }
  17689. // Layer Mask
  17690. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17691. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17692. } else {
  17693. camera.layerMask = 0xFFFFFFFF;
  17694. }
  17695. return camera;
  17696. };
  17697. var parseGeometry = function (parsedGeometry, scene) {
  17698. var id = parsedGeometry.id;
  17699. return scene.getGeometryByID(id);
  17700. };
  17701. var parseBox = function (parsedBox, scene) {
  17702. if (parseGeometry(parsedBox, scene)) {
  17703. return null;
  17704. }
  17705. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17706. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17707. scene.pushGeometry(box, true);
  17708. return box;
  17709. };
  17710. var parseSphere = function (parsedSphere, scene) {
  17711. if (parseGeometry(parsedSphere, scene)) {
  17712. return null;
  17713. }
  17714. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17715. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17716. scene.pushGeometry(sphere, true);
  17717. return sphere;
  17718. };
  17719. var parseCylinder = function (parsedCylinder, scene) {
  17720. if (parseGeometry(parsedCylinder, scene)) {
  17721. return null;
  17722. }
  17723. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17724. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17725. scene.pushGeometry(cylinder, true);
  17726. return cylinder;
  17727. };
  17728. var parseTorus = function (parsedTorus, scene) {
  17729. if (parseGeometry(parsedTorus, scene)) {
  17730. return null;
  17731. }
  17732. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17733. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17734. scene.pushGeometry(torus, true);
  17735. return torus;
  17736. };
  17737. var parseGround = function (parsedGround, scene) {
  17738. if (parseGeometry(parsedGround, scene)) {
  17739. return null;
  17740. }
  17741. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17742. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17743. scene.pushGeometry(ground, true);
  17744. return ground;
  17745. };
  17746. var parsePlane = function (parsedPlane, scene) {
  17747. if (parseGeometry(parsedPlane, scene)) {
  17748. return null;
  17749. }
  17750. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17751. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17752. scene.pushGeometry(plane, true);
  17753. return plane;
  17754. };
  17755. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17756. if (parseGeometry(parsedTorusKnot, scene)) {
  17757. return null;
  17758. }
  17759. 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);
  17760. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17761. scene.pushGeometry(torusKnot, true);
  17762. return torusKnot;
  17763. };
  17764. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17765. if (parseGeometry(parsedVertexData, scene)) {
  17766. return null;
  17767. }
  17768. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17769. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17770. if (parsedVertexData.delayLoadingFile) {
  17771. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17772. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17773. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17774. geometry._delayInfo = [];
  17775. if (parsedVertexData.hasUVs) {
  17776. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17777. }
  17778. if (parsedVertexData.hasUVs2) {
  17779. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17780. }
  17781. if (parsedVertexData.hasColors) {
  17782. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17783. }
  17784. if (parsedVertexData.hasMatricesIndices) {
  17785. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17786. }
  17787. if (parsedVertexData.hasMatricesWeights) {
  17788. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17789. }
  17790. geometry._delayLoadingFunction = importVertexData;
  17791. } else {
  17792. importVertexData(parsedVertexData, geometry);
  17793. }
  17794. scene.pushGeometry(geometry, true);
  17795. return geometry;
  17796. };
  17797. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17798. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17799. mesh.id = parsedMesh.id;
  17800. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17801. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17802. if (parsedMesh.rotationQuaternion) {
  17803. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17804. } else if (parsedMesh.rotation) {
  17805. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17806. }
  17807. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17808. if (parsedMesh.localMatrix) {
  17809. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17810. } else if (parsedMesh.pivotMatrix) {
  17811. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17812. }
  17813. mesh.setEnabled(parsedMesh.isEnabled);
  17814. mesh.isVisible = parsedMesh.isVisible;
  17815. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17816. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17817. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17818. if (parsedMesh.applyFog !== undefined) {
  17819. mesh.applyFog = parsedMesh.applyFog;
  17820. }
  17821. if (parsedMesh.pickable !== undefined) {
  17822. mesh.isPickable = parsedMesh.pickable;
  17823. }
  17824. if (parsedMesh.alphaIndex !== undefined) {
  17825. mesh.alphaIndex = parsedMesh.alphaIndex;
  17826. }
  17827. mesh.receiveShadows = parsedMesh.receiveShadows;
  17828. mesh.billboardMode = parsedMesh.billboardMode;
  17829. if (parsedMesh.visibility !== undefined) {
  17830. mesh.visibility = parsedMesh.visibility;
  17831. }
  17832. mesh.checkCollisions = parsedMesh.checkCollisions;
  17833. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17834. // Parent
  17835. if (parsedMesh.parentId) {
  17836. mesh._waitingParentId = parsedMesh.parentId;
  17837. }
  17838. // Geometry
  17839. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17840. if (parsedMesh.delayLoadingFile) {
  17841. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17842. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17843. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17844. if (parsedMesh._binaryInfo) {
  17845. mesh._binaryInfo = parsedMesh._binaryInfo;
  17846. }
  17847. mesh._delayInfo = [];
  17848. if (parsedMesh.hasUVs) {
  17849. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17850. }
  17851. if (parsedMesh.hasUVs2) {
  17852. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17853. }
  17854. if (parsedMesh.hasColors) {
  17855. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17856. }
  17857. if (parsedMesh.hasMatricesIndices) {
  17858. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17859. }
  17860. if (parsedMesh.hasMatricesWeights) {
  17861. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17862. }
  17863. mesh._delayLoadingFunction = importGeometry;
  17864. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17865. mesh._checkDelayState();
  17866. }
  17867. } else {
  17868. importGeometry(parsedMesh, mesh);
  17869. }
  17870. // Material
  17871. if (parsedMesh.materialId) {
  17872. mesh.setMaterialByID(parsedMesh.materialId);
  17873. } else {
  17874. mesh.material = null;
  17875. }
  17876. // Skeleton
  17877. if (parsedMesh.skeletonId > -1) {
  17878. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17879. }
  17880. // Physics
  17881. if (parsedMesh.physicsImpostor) {
  17882. if (!scene.isPhysicsEnabled()) {
  17883. scene.enablePhysics();
  17884. }
  17885. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17886. }
  17887. // Animations
  17888. if (parsedMesh.animations) {
  17889. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17890. var parsedAnimation = parsedMesh.animations[animationIndex];
  17891. mesh.animations.push(parseAnimation(parsedAnimation));
  17892. }
  17893. }
  17894. if (parsedMesh.autoAnimate) {
  17895. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17896. }
  17897. // Layer Mask
  17898. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17899. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17900. } else {
  17901. mesh.layerMask = 0xFFFFFFFF;
  17902. }
  17903. // Instances
  17904. if (parsedMesh.instances) {
  17905. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17906. var parsedInstance = parsedMesh.instances[index];
  17907. var instance = mesh.createInstance(parsedInstance.name);
  17908. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17909. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17910. if (parsedInstance.rotationQuaternion) {
  17911. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17912. } else if (parsedInstance.rotation) {
  17913. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17914. }
  17915. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17916. instance.checkCollisions = mesh.checkCollisions;
  17917. if (parsedMesh.animations) {
  17918. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17919. parsedAnimation = parsedMesh.animations[animationIndex];
  17920. instance.animations.push(parseAnimation(parsedAnimation));
  17921. }
  17922. }
  17923. }
  17924. }
  17925. return mesh;
  17926. };
  17927. var isDescendantOf = function (mesh, names, hierarchyIds) {
  17928. names = (names instanceof Array) ? names : [names];
  17929. for (var i in names) {
  17930. if (mesh.name === names[i]) {
  17931. hierarchyIds.push(mesh.id);
  17932. return true;
  17933. }
  17934. }
  17935. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  17936. hierarchyIds.push(mesh.id);
  17937. return true;
  17938. }
  17939. return false;
  17940. };
  17941. var importVertexData = function (parsedVertexData, geometry) {
  17942. var vertexData = new BABYLON.VertexData();
  17943. // positions
  17944. var positions = parsedVertexData.positions;
  17945. if (positions) {
  17946. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  17947. }
  17948. // normals
  17949. var normals = parsedVertexData.normals;
  17950. if (normals) {
  17951. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  17952. }
  17953. // uvs
  17954. var uvs = parsedVertexData.uvs;
  17955. if (uvs) {
  17956. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  17957. }
  17958. // uv2s
  17959. var uv2s = parsedVertexData.uv2s;
  17960. if (uv2s) {
  17961. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  17962. }
  17963. // colors
  17964. var colors = parsedVertexData.colors;
  17965. if (colors) {
  17966. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  17967. }
  17968. // matricesIndices
  17969. var matricesIndices = parsedVertexData.matricesIndices;
  17970. if (matricesIndices) {
  17971. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  17972. }
  17973. // matricesWeights
  17974. var matricesWeights = parsedVertexData.matricesWeights;
  17975. if (matricesWeights) {
  17976. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  17977. }
  17978. // indices
  17979. var indices = parsedVertexData.indices;
  17980. if (indices) {
  17981. vertexData.indices = indices;
  17982. }
  17983. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  17984. };
  17985. var importGeometry = function (parsedGeometry, mesh) {
  17986. var scene = mesh.getScene();
  17987. // Geometry
  17988. var geometryId = parsedGeometry.geometryId;
  17989. if (geometryId) {
  17990. var geometry = scene.getGeometryByID(geometryId);
  17991. if (geometry) {
  17992. geometry.applyToMesh(mesh);
  17993. }
  17994. } else if (parsedGeometry instanceof ArrayBuffer) {
  17995. var binaryInfo = mesh._binaryInfo;
  17996. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  17997. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  17998. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  17999. }
  18000. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18001. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18002. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18003. }
  18004. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18005. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18006. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18007. }
  18008. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18009. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18010. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18011. }
  18012. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18013. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18014. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18015. }
  18016. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18017. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18018. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18019. }
  18020. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18021. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18022. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18023. }
  18024. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18025. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18026. mesh.setIndices(indicesData);
  18027. }
  18028. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18029. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18030. mesh.subMeshes = [];
  18031. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18032. var materialIndex = subMeshesData[(i * 5) + 0];
  18033. var verticesStart = subMeshesData[(i * 5) + 1];
  18034. var verticesCount = subMeshesData[(i * 5) + 2];
  18035. var indexStart = subMeshesData[(i * 5) + 3];
  18036. var indexCount = subMeshesData[(i * 5) + 4];
  18037. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18038. }
  18039. }
  18040. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18041. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18042. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18043. if (parsedGeometry.uvs) {
  18044. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18045. }
  18046. if (parsedGeometry.uvs2) {
  18047. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18048. }
  18049. if (parsedGeometry.colors) {
  18050. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18051. }
  18052. if (parsedGeometry.matricesIndices) {
  18053. if (!parsedGeometry.matricesIndices._isExpanded) {
  18054. var floatIndices = [];
  18055. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18056. var matricesIndex = parsedGeometry.matricesIndices[i];
  18057. floatIndices.push(matricesIndex & 0x000000FF);
  18058. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18059. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18060. floatIndices.push(matricesIndex >> 24);
  18061. }
  18062. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18063. } else {
  18064. delete parsedGeometry.matricesIndices._isExpanded;
  18065. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18066. }
  18067. }
  18068. if (parsedGeometry.matricesWeights) {
  18069. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18070. }
  18071. mesh.setIndices(parsedGeometry.indices);
  18072. // SubMeshes
  18073. if (parsedGeometry.subMeshes) {
  18074. mesh.subMeshes = [];
  18075. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18076. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18077. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18078. }
  18079. }
  18080. }
  18081. // Flat shading
  18082. if (mesh._shouldGenerateFlatShading) {
  18083. mesh.convertToFlatShadedMesh();
  18084. delete mesh._shouldGenerateFlatShading;
  18085. }
  18086. // Update
  18087. mesh.computeWorldMatrix(true);
  18088. // Octree
  18089. if (scene._selectionOctree) {
  18090. scene._selectionOctree.addMesh(mesh);
  18091. }
  18092. };
  18093. BABYLON.SceneLoader.RegisterPlugin({
  18094. extensions: ".babylon",
  18095. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18096. var parsedData = JSON.parse(data);
  18097. var loadedSkeletonsIds = [];
  18098. var loadedMaterialsIds = [];
  18099. var hierarchyIds = [];
  18100. for (var index = 0; index < parsedData.meshes.length; index++) {
  18101. var parsedMesh = parsedData.meshes[index];
  18102. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18103. if (meshesNames instanceof Array) {
  18104. // Remove found mesh name from list.
  18105. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18106. }
  18107. // Material ?
  18108. if (parsedMesh.materialId) {
  18109. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18110. if (!materialFound) {
  18111. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18112. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18113. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18114. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18115. var subMatId = parsedMultiMaterial.materials[matIndex];
  18116. loadedMaterialsIds.push(subMatId);
  18117. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18118. }
  18119. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18120. parseMultiMaterial(parsedMultiMaterial, scene);
  18121. materialFound = true;
  18122. break;
  18123. }
  18124. }
  18125. }
  18126. if (!materialFound) {
  18127. loadedMaterialsIds.push(parsedMesh.materialId);
  18128. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18129. }
  18130. }
  18131. // Skeleton ?
  18132. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18133. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18134. if (!skeletonAlreadyLoaded) {
  18135. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18136. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18137. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18138. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18139. loadedSkeletonsIds.push(parsedSkeleton.id);
  18140. }
  18141. }
  18142. }
  18143. }
  18144. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18145. meshes.push(mesh);
  18146. }
  18147. }
  18148. for (index = 0; index < scene.meshes.length; index++) {
  18149. var currentMesh = scene.meshes[index];
  18150. if (currentMesh._waitingParentId) {
  18151. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18152. currentMesh._waitingParentId = undefined;
  18153. }
  18154. }
  18155. // Particles
  18156. if (parsedData.particleSystems) {
  18157. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18158. var parsedParticleSystem = parsedData.particleSystems[index];
  18159. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18160. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18161. }
  18162. }
  18163. }
  18164. return true;
  18165. },
  18166. load: function (scene, data, rootUrl) {
  18167. var parsedData = JSON.parse(data);
  18168. // Scene
  18169. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18170. scene.autoClear = parsedData.autoClear;
  18171. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18172. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18173. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18174. // Fog
  18175. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18176. scene.fogMode = parsedData.fogMode;
  18177. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18178. scene.fogStart = parsedData.fogStart;
  18179. scene.fogEnd = parsedData.fogEnd;
  18180. scene.fogDensity = parsedData.fogDensity;
  18181. }
  18182. for (var index = 0; index < parsedData.lights.length; index++) {
  18183. var parsedLight = parsedData.lights[index];
  18184. parseLight(parsedLight, scene);
  18185. }
  18186. // Materials
  18187. if (parsedData.materials) {
  18188. for (index = 0; index < parsedData.materials.length; index++) {
  18189. var parsedMaterial = parsedData.materials[index];
  18190. parseMaterial(parsedMaterial, scene, rootUrl);
  18191. }
  18192. }
  18193. if (parsedData.multiMaterials) {
  18194. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18195. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18196. parseMultiMaterial(parsedMultiMaterial, scene);
  18197. }
  18198. }
  18199. // Skeletons
  18200. if (parsedData.skeletons) {
  18201. for (index = 0; index < parsedData.skeletons.length; index++) {
  18202. var parsedSkeleton = parsedData.skeletons[index];
  18203. parseSkeleton(parsedSkeleton, scene);
  18204. }
  18205. }
  18206. // Geometries
  18207. var geometries = parsedData.geometries;
  18208. if (geometries) {
  18209. // Boxes
  18210. var boxes = geometries.boxes;
  18211. if (boxes) {
  18212. for (index = 0; index < boxes.length; index++) {
  18213. var parsedBox = boxes[index];
  18214. parseBox(parsedBox, scene);
  18215. }
  18216. }
  18217. // Spheres
  18218. var spheres = geometries.spheres;
  18219. if (spheres) {
  18220. for (index = 0; index < spheres.length; index++) {
  18221. var parsedSphere = spheres[index];
  18222. parseSphere(parsedSphere, scene);
  18223. }
  18224. }
  18225. // Cylinders
  18226. var cylinders = geometries.cylinders;
  18227. if (cylinders) {
  18228. for (index = 0; index < cylinders.length; index++) {
  18229. var parsedCylinder = cylinders[index];
  18230. parseCylinder(parsedCylinder, scene);
  18231. }
  18232. }
  18233. // Toruses
  18234. var toruses = geometries.toruses;
  18235. if (toruses) {
  18236. for (index = 0; index < toruses.length; index++) {
  18237. var parsedTorus = toruses[index];
  18238. parseTorus(parsedTorus, scene);
  18239. }
  18240. }
  18241. // Grounds
  18242. var grounds = geometries.grounds;
  18243. if (grounds) {
  18244. for (index = 0; index < grounds.length; index++) {
  18245. var parsedGround = grounds[index];
  18246. parseGround(parsedGround, scene);
  18247. }
  18248. }
  18249. // Planes
  18250. var planes = geometries.planes;
  18251. if (planes) {
  18252. for (index = 0; index < planes.length; index++) {
  18253. var parsedPlane = planes[index];
  18254. parsePlane(parsedPlane, scene);
  18255. }
  18256. }
  18257. // TorusKnots
  18258. var torusKnots = geometries.torusKnots;
  18259. if (torusKnots) {
  18260. for (index = 0; index < torusKnots.length; index++) {
  18261. var parsedTorusKnot = torusKnots[index];
  18262. parseTorusKnot(parsedTorusKnot, scene);
  18263. }
  18264. }
  18265. // VertexData
  18266. var vertexData = geometries.vertexData;
  18267. if (vertexData) {
  18268. for (index = 0; index < vertexData.length; index++) {
  18269. var parsedVertexData = vertexData[index];
  18270. parseVertexData(parsedVertexData, scene, rootUrl);
  18271. }
  18272. }
  18273. }
  18274. for (index = 0; index < parsedData.meshes.length; index++) {
  18275. var parsedMesh = parsedData.meshes[index];
  18276. parseMesh(parsedMesh, scene, rootUrl);
  18277. }
  18278. for (index = 0; index < parsedData.cameras.length; index++) {
  18279. var parsedCamera = parsedData.cameras[index];
  18280. parseCamera(parsedCamera, scene);
  18281. }
  18282. if (parsedData.activeCameraID) {
  18283. scene.setActiveCameraByID(parsedData.activeCameraID);
  18284. }
  18285. for (index = 0; index < scene.cameras.length; index++) {
  18286. var camera = scene.cameras[index];
  18287. if (camera._waitingParentId) {
  18288. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18289. camera._waitingParentId = undefined;
  18290. }
  18291. }
  18292. for (index = 0; index < scene.lights.length; index++) {
  18293. var light = scene.lights[index];
  18294. if (light._waitingParentId) {
  18295. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18296. light._waitingParentId = undefined;
  18297. }
  18298. }
  18299. for (index = 0; index < scene.meshes.length; index++) {
  18300. var mesh = scene.meshes[index];
  18301. if (mesh._waitingParentId) {
  18302. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18303. mesh._waitingParentId = undefined;
  18304. }
  18305. }
  18306. // Particles Systems
  18307. if (parsedData.particleSystems) {
  18308. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18309. var parsedParticleSystem = parsedData.particleSystems[index];
  18310. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18311. }
  18312. }
  18313. // Lens flares
  18314. if (parsedData.lensFlareSystems) {
  18315. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18316. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18317. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18318. }
  18319. }
  18320. // Shadows
  18321. if (parsedData.shadowGenerators) {
  18322. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18323. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18324. parseShadowGenerator(parsedShadowGenerator, scene);
  18325. }
  18326. }
  18327. // Finish
  18328. return true;
  18329. }
  18330. });
  18331. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18332. var Internals = BABYLON.Internals;
  18333. })(BABYLON || (BABYLON = {}));
  18334. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18335. var BABYLON;
  18336. (function (BABYLON) {
  18337. // Unique ID when we import meshes from Babylon to CSG
  18338. var currentCSGMeshId = 0;
  18339. // # class Vertex
  18340. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18341. // one to provide additional features like texture coordinates and vertex
  18342. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18343. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18344. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18345. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18346. // is not used anywhere else.
  18347. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18348. var Vertex = (function () {
  18349. function Vertex(pos, normal, uv) {
  18350. this.pos = pos;
  18351. this.normal = normal;
  18352. this.uv = uv;
  18353. }
  18354. Vertex.prototype.clone = function () {
  18355. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18356. };
  18357. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18358. // orientation of a polygon is flipped.
  18359. Vertex.prototype.flip = function () {
  18360. this.normal = this.normal.scale(-1);
  18361. };
  18362. // Create a new vertex between this vertex and `other` by linearly
  18363. // interpolating all properties using a parameter of `t`. Subclasses should
  18364. // override this to interpolate additional properties.
  18365. Vertex.prototype.interpolate = function (other, t) {
  18366. 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));
  18367. };
  18368. return Vertex;
  18369. })();
  18370. // # class Plane
  18371. // Represents a plane in 3D space.
  18372. var Plane = (function () {
  18373. function Plane(normal, w) {
  18374. this.normal = normal;
  18375. this.w = w;
  18376. }
  18377. Plane.FromPoints = function (a, b, c) {
  18378. var v0 = c.subtract(a);
  18379. var v1 = b.subtract(a);
  18380. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18381. return null;
  18382. }
  18383. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18384. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18385. };
  18386. Plane.prototype.clone = function () {
  18387. return new Plane(this.normal.clone(), this.w);
  18388. };
  18389. Plane.prototype.flip = function () {
  18390. this.normal.scaleInPlace(-1);
  18391. this.w = -this.w;
  18392. };
  18393. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18394. // fragments in the appropriate lists. Coplanar polygons go into either
  18395. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18396. // respect to this plane. Polygons in front or in back of this plane go into
  18397. // either `front` or `back`.
  18398. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18399. var COPLANAR = 0;
  18400. var FRONT = 1;
  18401. var BACK = 2;
  18402. var SPANNING = 3;
  18403. // Classify each point as well as the entire polygon into one of the above
  18404. // four classes.
  18405. var polygonType = 0;
  18406. var types = [];
  18407. for (var i = 0; i < polygon.vertices.length; i++) {
  18408. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18409. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18410. polygonType |= type;
  18411. types.push(type);
  18412. }
  18413. switch (polygonType) {
  18414. case COPLANAR:
  18415. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18416. break;
  18417. case FRONT:
  18418. front.push(polygon);
  18419. break;
  18420. case BACK:
  18421. back.push(polygon);
  18422. break;
  18423. case SPANNING:
  18424. var f = [], b = [];
  18425. for (i = 0; i < polygon.vertices.length; i++) {
  18426. var j = (i + 1) % polygon.vertices.length;
  18427. var ti = types[i], tj = types[j];
  18428. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18429. if (ti != BACK)
  18430. f.push(vi);
  18431. if (ti != FRONT)
  18432. b.push(ti != BACK ? vi.clone() : vi);
  18433. if ((ti | tj) == SPANNING) {
  18434. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18435. var v = vi.interpolate(vj, t);
  18436. f.push(v);
  18437. b.push(v.clone());
  18438. }
  18439. }
  18440. if (f.length >= 3) {
  18441. var poly = new Polygon(f, polygon.shared);
  18442. if (poly.plane)
  18443. front.push(poly);
  18444. }
  18445. if (b.length >= 3) {
  18446. poly = new Polygon(b, polygon.shared);
  18447. if (poly.plane)
  18448. back.push(poly);
  18449. }
  18450. break;
  18451. }
  18452. };
  18453. Plane.EPSILON = 1e-5;
  18454. return Plane;
  18455. })();
  18456. // # class Polygon
  18457. // Represents a convex polygon. The vertices used to initialize a polygon must
  18458. // be coplanar and form a convex loop.
  18459. //
  18460. // Each convex polygon has a `shared` property, which is shared between all
  18461. // polygons that are clones of each other or were split from the same polygon.
  18462. // This can be used to define per-polygon properties (such as surface color).
  18463. var Polygon = (function () {
  18464. function Polygon(vertices, shared) {
  18465. this.vertices = vertices;
  18466. this.shared = shared;
  18467. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18468. }
  18469. Polygon.prototype.clone = function () {
  18470. var vertices = this.vertices.map(function (v) {
  18471. return v.clone();
  18472. });
  18473. return new Polygon(vertices, this.shared);
  18474. };
  18475. Polygon.prototype.flip = function () {
  18476. this.vertices.reverse().map(function (v) {
  18477. v.flip();
  18478. });
  18479. this.plane.flip();
  18480. };
  18481. return Polygon;
  18482. })();
  18483. // # class Node
  18484. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18485. // by picking a polygon to split along. That polygon (and all other coplanar
  18486. // polygons) are added directly to that node and the other polygons are added to
  18487. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18488. // no distinction between internal and leaf nodes.
  18489. var Node = (function () {
  18490. function Node(polygons) {
  18491. this.plane = null;
  18492. this.front = null;
  18493. this.back = null;
  18494. this.polygons = [];
  18495. if (polygons) {
  18496. this.build(polygons);
  18497. }
  18498. }
  18499. Node.prototype.clone = function () {
  18500. var node = new Node();
  18501. node.plane = this.plane && this.plane.clone();
  18502. node.front = this.front && this.front.clone();
  18503. node.back = this.back && this.back.clone();
  18504. node.polygons = this.polygons.map(function (p) {
  18505. return p.clone();
  18506. });
  18507. return node;
  18508. };
  18509. // Convert solid space to empty space and empty space to solid space.
  18510. Node.prototype.invert = function () {
  18511. for (var i = 0; i < this.polygons.length; i++) {
  18512. this.polygons[i].flip();
  18513. }
  18514. if (this.plane) {
  18515. this.plane.flip();
  18516. }
  18517. if (this.front) {
  18518. this.front.invert();
  18519. }
  18520. if (this.back) {
  18521. this.back.invert();
  18522. }
  18523. var temp = this.front;
  18524. this.front = this.back;
  18525. this.back = temp;
  18526. };
  18527. // Recursively remove all polygons in `polygons` that are inside this BSP
  18528. // tree.
  18529. Node.prototype.clipPolygons = function (polygons) {
  18530. if (!this.plane)
  18531. return polygons.slice();
  18532. var front = [], back = [];
  18533. for (var i = 0; i < polygons.length; i++) {
  18534. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18535. }
  18536. if (this.front) {
  18537. front = this.front.clipPolygons(front);
  18538. }
  18539. if (this.back) {
  18540. back = this.back.clipPolygons(back);
  18541. } else {
  18542. back = [];
  18543. }
  18544. return front.concat(back);
  18545. };
  18546. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18547. // `bsp`.
  18548. Node.prototype.clipTo = function (bsp) {
  18549. this.polygons = bsp.clipPolygons(this.polygons);
  18550. if (this.front)
  18551. this.front.clipTo(bsp);
  18552. if (this.back)
  18553. this.back.clipTo(bsp);
  18554. };
  18555. // Return a list of all polygons in this BSP tree.
  18556. Node.prototype.allPolygons = function () {
  18557. var polygons = this.polygons.slice();
  18558. if (this.front)
  18559. polygons = polygons.concat(this.front.allPolygons());
  18560. if (this.back)
  18561. polygons = polygons.concat(this.back.allPolygons());
  18562. return polygons;
  18563. };
  18564. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18565. // new polygons are filtered down to the bottom of the tree and become new
  18566. // nodes there. Each set of polygons is partitioned using the first polygon
  18567. // (no heuristic is used to pick a good split).
  18568. Node.prototype.build = function (polygons) {
  18569. if (!polygons.length)
  18570. return;
  18571. if (!this.plane)
  18572. this.plane = polygons[0].plane.clone();
  18573. var front = [], back = [];
  18574. for (var i = 0; i < polygons.length; i++) {
  18575. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18576. }
  18577. if (front.length) {
  18578. if (!this.front)
  18579. this.front = new Node();
  18580. this.front.build(front);
  18581. }
  18582. if (back.length) {
  18583. if (!this.back)
  18584. this.back = new Node();
  18585. this.back.build(back);
  18586. }
  18587. };
  18588. return Node;
  18589. })();
  18590. var CSG = (function () {
  18591. function CSG() {
  18592. this.polygons = new Array();
  18593. }
  18594. // Convert BABYLON.Mesh to BABYLON.CSG
  18595. CSG.FromMesh = function (mesh) {
  18596. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18597. if (mesh instanceof BABYLON.Mesh) {
  18598. mesh.computeWorldMatrix(true);
  18599. var matrix = mesh.getWorldMatrix();
  18600. var meshPosition = mesh.position.clone();
  18601. var meshRotation = mesh.rotation.clone();
  18602. var meshScaling = mesh.scaling.clone();
  18603. } else {
  18604. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18605. }
  18606. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18607. var subMeshes = mesh.subMeshes;
  18608. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18609. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18610. vertices = [];
  18611. for (var j = 0; j < 3; j++) {
  18612. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18613. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18614. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18615. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18616. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18617. vertex = new Vertex(position, normal, uv);
  18618. vertices.push(vertex);
  18619. }
  18620. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18621. // To handle the case of degenerated triangle
  18622. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18623. if (polygon.plane)
  18624. polygons.push(polygon);
  18625. }
  18626. }
  18627. var csg = CSG.FromPolygons(polygons);
  18628. csg.matrix = matrix;
  18629. csg.position = meshPosition;
  18630. csg.rotation = meshRotation;
  18631. csg.scaling = meshScaling;
  18632. currentCSGMeshId++;
  18633. return csg;
  18634. };
  18635. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18636. CSG.FromPolygons = function (polygons) {
  18637. var csg = new BABYLON.CSG();
  18638. csg.polygons = polygons;
  18639. return csg;
  18640. };
  18641. CSG.prototype.clone = function () {
  18642. var csg = new BABYLON.CSG();
  18643. csg.polygons = this.polygons.map(function (p) {
  18644. return p.clone();
  18645. });
  18646. csg.copyTransformAttributes(this);
  18647. return csg;
  18648. };
  18649. CSG.prototype.toPolygons = function () {
  18650. return this.polygons;
  18651. };
  18652. CSG.prototype.union = function (csg) {
  18653. var a = new Node(this.clone().polygons);
  18654. var b = new Node(csg.clone().polygons);
  18655. a.clipTo(b);
  18656. b.clipTo(a);
  18657. b.invert();
  18658. b.clipTo(a);
  18659. b.invert();
  18660. a.build(b.allPolygons());
  18661. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18662. };
  18663. CSG.prototype.unionInPlace = function (csg) {
  18664. var a = new Node(this.polygons);
  18665. var b = new Node(csg.polygons);
  18666. a.clipTo(b);
  18667. b.clipTo(a);
  18668. b.invert();
  18669. b.clipTo(a);
  18670. b.invert();
  18671. a.build(b.allPolygons());
  18672. this.polygons = a.allPolygons();
  18673. };
  18674. CSG.prototype.subtract = function (csg) {
  18675. var a = new Node(this.clone().polygons);
  18676. var b = new Node(csg.clone().polygons);
  18677. a.invert();
  18678. a.clipTo(b);
  18679. b.clipTo(a);
  18680. b.invert();
  18681. b.clipTo(a);
  18682. b.invert();
  18683. a.build(b.allPolygons());
  18684. a.invert();
  18685. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18686. };
  18687. CSG.prototype.subtractInPlace = function (csg) {
  18688. var a = new Node(this.polygons);
  18689. var b = new Node(csg.polygons);
  18690. a.invert();
  18691. a.clipTo(b);
  18692. b.clipTo(a);
  18693. b.invert();
  18694. b.clipTo(a);
  18695. b.invert();
  18696. a.build(b.allPolygons());
  18697. a.invert();
  18698. this.polygons = a.allPolygons();
  18699. };
  18700. CSG.prototype.intersect = function (csg) {
  18701. var a = new Node(this.clone().polygons);
  18702. var b = new Node(csg.clone().polygons);
  18703. a.invert();
  18704. b.clipTo(a);
  18705. b.invert();
  18706. a.clipTo(b);
  18707. b.clipTo(a);
  18708. a.build(b.allPolygons());
  18709. a.invert();
  18710. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18711. };
  18712. CSG.prototype.intersectInPlace = function (csg) {
  18713. var a = new Node(this.polygons);
  18714. var b = new Node(csg.polygons);
  18715. a.invert();
  18716. b.clipTo(a);
  18717. b.invert();
  18718. a.clipTo(b);
  18719. b.clipTo(a);
  18720. a.build(b.allPolygons());
  18721. a.invert();
  18722. this.polygons = a.allPolygons();
  18723. };
  18724. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18725. // not modified.
  18726. CSG.prototype.inverse = function () {
  18727. var csg = this.clone();
  18728. csg.inverseInPlace();
  18729. return csg;
  18730. };
  18731. CSG.prototype.inverseInPlace = function () {
  18732. this.polygons.map(function (p) {
  18733. p.flip();
  18734. });
  18735. };
  18736. // This is used to keep meshes transformations so they can be restored
  18737. // when we build back a Babylon Mesh
  18738. // NB : All CSG operations are performed in world coordinates
  18739. CSG.prototype.copyTransformAttributes = function (csg) {
  18740. this.matrix = csg.matrix;
  18741. this.position = csg.position;
  18742. this.rotation = csg.rotation;
  18743. this.scaling = csg.scaling;
  18744. return this;
  18745. };
  18746. // Build Raw mesh from CSG
  18747. // Coordinates here are in world space
  18748. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18749. var matrix = this.matrix.clone();
  18750. matrix.invert();
  18751. 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;
  18752. if (keepSubMeshes) {
  18753. // Sort Polygons, since subMeshes are indices range
  18754. polygons.sort(function (a, b) {
  18755. if (a.shared.meshId === b.shared.meshId) {
  18756. return a.shared.subMeshId - b.shared.subMeshId;
  18757. } else {
  18758. return a.shared.meshId - b.shared.meshId;
  18759. }
  18760. });
  18761. }
  18762. for (var i = 0, il = polygons.length; i < il; i++) {
  18763. polygon = polygons[i];
  18764. // Building SubMeshes
  18765. if (!subMesh_dict[polygon.shared.meshId]) {
  18766. subMesh_dict[polygon.shared.meshId] = {};
  18767. }
  18768. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18769. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18770. indexStart: +Infinity,
  18771. indexEnd: -Infinity,
  18772. materialIndex: polygon.shared.materialIndex
  18773. };
  18774. }
  18775. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18776. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18777. polygonIndices[0] = 0;
  18778. polygonIndices[1] = j - 1;
  18779. polygonIndices[2] = j;
  18780. for (var k = 0; k < 3; k++) {
  18781. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18782. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18783. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18784. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18785. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18786. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18787. // Check if 2 points can be merged
  18788. 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)) {
  18789. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18790. uvs.push(uv.x, uv.y);
  18791. normals.push(normal.x, normal.y, normal.z);
  18792. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18793. }
  18794. indices.push(vertex_idx);
  18795. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18796. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18797. currentIndex++;
  18798. }
  18799. }
  18800. }
  18801. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18802. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18803. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18804. mesh.setIndices(indices);
  18805. if (keepSubMeshes) {
  18806. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18807. var materialIndexOffset = 0, materialMaxIndex;
  18808. mesh.subMeshes.length = 0;
  18809. for (var m in subMesh_dict) {
  18810. materialMaxIndex = -1;
  18811. for (var sm in subMesh_dict[m]) {
  18812. subMesh_obj = subMesh_dict[m][sm];
  18813. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18814. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18815. }
  18816. materialIndexOffset += ++materialMaxIndex;
  18817. }
  18818. }
  18819. return mesh;
  18820. };
  18821. // Build Mesh from CSG taking material and transforms into account
  18822. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  18823. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  18824. mesh.material = material;
  18825. mesh.position.copyFrom(this.position);
  18826. mesh.rotation.copyFrom(this.rotation);
  18827. mesh.scaling.copyFrom(this.scaling);
  18828. mesh.computeWorldMatrix(true);
  18829. return mesh;
  18830. };
  18831. return CSG;
  18832. })();
  18833. BABYLON.CSG = CSG;
  18834. })(BABYLON || (BABYLON = {}));
  18835. //# sourceMappingURL=babylon.csg.js.map
  18836. var BABYLON;
  18837. (function (BABYLON) {
  18838. var OculusDistortionCorrectionPostProcess = (function (_super) {
  18839. __extends(OculusDistortionCorrectionPostProcess, _super);
  18840. //ANY
  18841. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  18842. var _this = this;
  18843. _super.call(this, name, "oculusDistortionCorrection", [
  18844. 'LensCenter',
  18845. 'Scale',
  18846. 'ScaleIn',
  18847. 'HmdWarpParam'
  18848. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  18849. this._isRightEye = isRightEye;
  18850. this._distortionFactors = cameraSettings.DistortionK;
  18851. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  18852. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  18853. this.onSizeChanged = function () {
  18854. _this.aspectRatio = _this.width * .5 / _this.height;
  18855. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  18856. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  18857. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  18858. };
  18859. this.onApply = function (effect) {
  18860. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  18861. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  18862. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  18863. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  18864. };
  18865. }
  18866. return OculusDistortionCorrectionPostProcess;
  18867. })(BABYLON.PostProcess);
  18868. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  18869. })(BABYLON || (BABYLON = {}));
  18870. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  18871. // Mainly based on these 2 articles :
  18872. // 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
  18873. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  18874. var BABYLON;
  18875. (function (BABYLON) {
  18876. (function (JoystickAxis) {
  18877. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  18878. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  18879. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  18880. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  18881. var JoystickAxis = BABYLON.JoystickAxis;
  18882. var VirtualJoystick = (function () {
  18883. function VirtualJoystick(leftJoystick) {
  18884. var _this = this;
  18885. if (leftJoystick) {
  18886. this._leftJoystick = true;
  18887. } else {
  18888. this._leftJoystick = false;
  18889. }
  18890. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  18891. VirtualJoystick._globalJoystickIndex++;
  18892. // By default left & right arrow keys are moving the X
  18893. // and up & down keys are moving the Y
  18894. this._axisTargetedByLeftAndRight = 0 /* X */;
  18895. this._axisTargetedByUpAndDown = 1 /* Y */;
  18896. this.reverseLeftRight = false;
  18897. this.reverseUpDown = false;
  18898. // collections of pointers
  18899. this._touches = new BABYLON.VirtualJoystick.Collection();
  18900. this.deltaPosition = BABYLON.Vector3.Zero();
  18901. this._joystickSensibility = 25;
  18902. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18903. this._rotationSpeed = 25;
  18904. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  18905. this._rotateOnAxisRelativeToMesh = false;
  18906. // injecting a canvas element on top of the canvas 3D game
  18907. if (!VirtualJoystick.vjCanvas) {
  18908. window.addEventListener("resize", function () {
  18909. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18910. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18911. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  18912. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  18913. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  18914. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  18915. }, false);
  18916. VirtualJoystick.vjCanvas = document.createElement("canvas");
  18917. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18918. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18919. VirtualJoystick.vjCanvas.width = window.innerWidth;
  18920. VirtualJoystick.vjCanvas.height = window.innerHeight;
  18921. VirtualJoystick.vjCanvas.style.width = "100%";
  18922. VirtualJoystick.vjCanvas.style.height = "100%";
  18923. VirtualJoystick.vjCanvas.style.position = "absolute";
  18924. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  18925. VirtualJoystick.vjCanvas.style.top = "0px";
  18926. VirtualJoystick.vjCanvas.style.left = "0px";
  18927. VirtualJoystick.vjCanvas.style.zIndex = "5";
  18928. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  18929. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  18930. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  18931. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18932. document.body.appendChild(VirtualJoystick.vjCanvas);
  18933. }
  18934. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  18935. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  18936. this.pressed = false;
  18937. // default joystick color
  18938. this._joystickColor = "cyan";
  18939. this._joystickPointerID = -1;
  18940. // current joystick position
  18941. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  18942. // origin joystick position
  18943. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  18944. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  18945. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  18946. _this._onPointerDown(evt);
  18947. }, false);
  18948. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  18949. _this._onPointerMove(evt);
  18950. }, false);
  18951. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  18952. _this._onPointerUp(evt);
  18953. }, false);
  18954. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  18955. _this._onPointerUp(evt);
  18956. }, false);
  18957. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  18958. evt.preventDefault(); // Disables system menu
  18959. }, false);
  18960. requestAnimationFrame(function () {
  18961. _this._drawVirtualJoystick();
  18962. });
  18963. }
  18964. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  18965. this._joystickSensibility = newJoystickSensibility;
  18966. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18967. };
  18968. VirtualJoystick.prototype._onPointerDown = function (e) {
  18969. var positionOnScreenCondition;
  18970. e.preventDefault();
  18971. if (this._leftJoystick === true) {
  18972. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  18973. } else {
  18974. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  18975. }
  18976. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  18977. // First contact will be dedicated to the virtual joystick
  18978. this._joystickPointerID = e.pointerId;
  18979. this._joystickPointerStartPos.x = e.clientX;
  18980. this._joystickPointerStartPos.y = e.clientY;
  18981. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  18982. this._deltaJoystickVector.x = 0;
  18983. this._deltaJoystickVector.y = 0;
  18984. this.pressed = true;
  18985. this._touches.add(e.pointerId.toString(), e);
  18986. } else {
  18987. // You can only trigger the action buttons with a joystick declared
  18988. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  18989. this._action();
  18990. this._touches.add(e.pointerId.toString(), e);
  18991. }
  18992. }
  18993. };
  18994. VirtualJoystick.prototype._onPointerMove = function (e) {
  18995. // If the current pointer is the one associated to the joystick (first touch contact)
  18996. if (this._joystickPointerID == e.pointerId) {
  18997. this._joystickPointerPos.x = e.clientX;
  18998. this._joystickPointerPos.y = e.clientY;
  18999. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19000. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19001. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19002. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19003. switch (this._axisTargetedByLeftAndRight) {
  19004. case 0 /* X */:
  19005. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19006. break;
  19007. case 1 /* Y */:
  19008. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19009. break;
  19010. case 2 /* Z */:
  19011. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19012. break;
  19013. }
  19014. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19015. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19016. switch (this._axisTargetedByUpAndDown) {
  19017. case 0 /* X */:
  19018. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19019. break;
  19020. case 1 /* Y */:
  19021. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19022. break;
  19023. case 2 /* Z */:
  19024. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19025. break;
  19026. }
  19027. } else {
  19028. if (this._touches.item(e.pointerId.toString())) {
  19029. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19030. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19031. }
  19032. }
  19033. };
  19034. VirtualJoystick.prototype._onPointerUp = function (e) {
  19035. this._clearCanvas();
  19036. if (this._joystickPointerID == e.pointerId) {
  19037. this._joystickPointerID = -1;
  19038. this.pressed = false;
  19039. }
  19040. this._deltaJoystickVector.x = 0;
  19041. this._deltaJoystickVector.y = 0;
  19042. this._touches.remove(e.pointerId.toString());
  19043. };
  19044. /**
  19045. * Change the color of the virtual joystick
  19046. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19047. */
  19048. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19049. this._joystickColor = newColor;
  19050. };
  19051. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19052. this._action = action;
  19053. };
  19054. // Define which axis you'd like to control for left & right
  19055. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19056. switch (axis) {
  19057. case 0 /* X */:
  19058. case 1 /* Y */:
  19059. case 2 /* Z */:
  19060. this._axisTargetedByLeftAndRight = axis;
  19061. break;
  19062. default:
  19063. this._axisTargetedByLeftAndRight = 0 /* X */;
  19064. break;
  19065. }
  19066. };
  19067. // Define which axis you'd like to control for up & down
  19068. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19069. switch (axis) {
  19070. case 0 /* X */:
  19071. case 1 /* Y */:
  19072. case 2 /* Z */:
  19073. this._axisTargetedByUpAndDown = axis;
  19074. break;
  19075. default:
  19076. this._axisTargetedByUpAndDown = 1 /* Y */;
  19077. break;
  19078. }
  19079. };
  19080. VirtualJoystick.prototype._clearCanvas = function () {
  19081. if (this._leftJoystick) {
  19082. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19083. } else {
  19084. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19085. }
  19086. };
  19087. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19088. var _this = this;
  19089. if (this.pressed) {
  19090. this._clearCanvas();
  19091. this._touches.forEach(function (touch) {
  19092. if (touch.pointerId === _this._joystickPointerID) {
  19093. VirtualJoystick.vjCanvasContext.beginPath();
  19094. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19095. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19096. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19097. VirtualJoystick.vjCanvasContext.stroke();
  19098. VirtualJoystick.vjCanvasContext.beginPath();
  19099. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19100. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19101. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19102. VirtualJoystick.vjCanvasContext.stroke();
  19103. VirtualJoystick.vjCanvasContext.beginPath();
  19104. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19105. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19106. VirtualJoystick.vjCanvasContext.stroke();
  19107. } else {
  19108. VirtualJoystick.vjCanvasContext.beginPath();
  19109. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19110. VirtualJoystick.vjCanvasContext.beginPath();
  19111. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19112. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19113. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19114. VirtualJoystick.vjCanvasContext.stroke();
  19115. }
  19116. ;
  19117. });
  19118. }
  19119. requestAnimationFrame(function () {
  19120. _this._drawVirtualJoystick();
  19121. });
  19122. };
  19123. VirtualJoystick.prototype.releaseCanvas = function () {
  19124. if (VirtualJoystick.vjCanvas) {
  19125. document.body.removeChild(VirtualJoystick.vjCanvas);
  19126. VirtualJoystick.vjCanvas = null;
  19127. }
  19128. };
  19129. VirtualJoystick._globalJoystickIndex = 0;
  19130. return VirtualJoystick;
  19131. })();
  19132. BABYLON.VirtualJoystick = VirtualJoystick;
  19133. })(BABYLON || (BABYLON = {}));
  19134. var BABYLON;
  19135. (function (BABYLON) {
  19136. (function (VirtualJoystick) {
  19137. var Collection = (function () {
  19138. function Collection() {
  19139. this._count = 0;
  19140. this._collection = new Array();
  19141. }
  19142. Collection.prototype.Count = function () {
  19143. return this._count;
  19144. };
  19145. Collection.prototype.add = function (key, item) {
  19146. if (this._collection[key] != undefined) {
  19147. return undefined;
  19148. }
  19149. this._collection[key] = item;
  19150. return ++this._count;
  19151. };
  19152. Collection.prototype.remove = function (key) {
  19153. if (this._collection[key] == undefined) {
  19154. return undefined;
  19155. }
  19156. delete this._collection[key];
  19157. return --this._count;
  19158. };
  19159. Collection.prototype.item = function (key) {
  19160. return this._collection[key];
  19161. };
  19162. Collection.prototype.forEach = function (block) {
  19163. var key;
  19164. for (key in this._collection) {
  19165. if (this._collection.hasOwnProperty(key)) {
  19166. block(this._collection[key]);
  19167. }
  19168. }
  19169. };
  19170. return Collection;
  19171. })();
  19172. VirtualJoystick.Collection = Collection;
  19173. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  19174. var VirtualJoystick = BABYLON.VirtualJoystick;
  19175. })(BABYLON || (BABYLON = {}));
  19176. //# sourceMappingURL=babylon.virtualJoystick.js.map
  19177. var BABYLON;
  19178. (function (BABYLON) {
  19179. var OculusRiftDevKit2013_Metric = {
  19180. HResolution: 1280,
  19181. VResolution: 800,
  19182. HScreenSize: 0.149759993,
  19183. VScreenSize: 0.0935999975,
  19184. VScreenCenter: 0.0467999987,
  19185. EyeToScreenDistance: 0.0410000011,
  19186. LensSeparationDistance: 0.0635000020,
  19187. InterpupillaryDistance: 0.0640000030,
  19188. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19189. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19190. PostProcessScaleFactor: 1.714605507808412,
  19191. LensCenterOffset: 0.151976421
  19192. };
  19193. var _OculusInnerCamera = (function (_super) {
  19194. __extends(_OculusInnerCamera, _super);
  19195. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  19196. _super.call(this, name, position, scene);
  19197. this._workMatrix = new BABYLON.Matrix();
  19198. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19199. // Constants
  19200. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19201. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19202. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19203. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19204. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19205. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19206. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19207. // Postprocess
  19208. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19209. }
  19210. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  19211. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19212. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19213. return this._projectionMatrix;
  19214. };
  19215. _OculusInnerCamera.prototype._getViewMatrix = function () {
  19216. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19217. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19218. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19219. // Computing target and final matrix
  19220. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19221. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19222. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19223. return this._viewMatrix;
  19224. };
  19225. return _OculusInnerCamera;
  19226. })(BABYLON.FreeCamera);
  19227. var OculusCamera = (function (_super) {
  19228. __extends(OculusCamera, _super);
  19229. function OculusCamera(name, position, scene) {
  19230. _super.call(this, name, position, scene);
  19231. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  19232. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  19233. this.subCameras.push(this._leftCamera);
  19234. this.subCameras.push(this._rightCamera);
  19235. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19236. }
  19237. OculusCamera.prototype._update = function () {
  19238. this._leftCamera.position.copyFrom(this.position);
  19239. this._rightCamera.position.copyFrom(this.position);
  19240. this._updateCamera(this._leftCamera);
  19241. this._updateCamera(this._rightCamera);
  19242. _super.prototype._update.call(this);
  19243. };
  19244. OculusCamera.prototype._updateCamera = function (camera) {
  19245. camera.minZ = this.minZ;
  19246. camera.maxZ = this.maxZ;
  19247. camera.rotation.x = this.rotation.x;
  19248. camera.rotation.y = this.rotation.y;
  19249. camera.rotation.z = this.rotation.z;
  19250. };
  19251. // Oculus events
  19252. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19253. var yaw = evt.alpha / 180 * Math.PI;
  19254. var pitch = evt.beta / 180 * Math.PI;
  19255. var roll = evt.gamma / 180 * Math.PI;
  19256. if (!this._offsetOrientation) {
  19257. this._offsetOrientation = {
  19258. yaw: yaw,
  19259. pitch: pitch,
  19260. roll: roll
  19261. };
  19262. return;
  19263. } else {
  19264. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19265. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19266. this.rotation.z += this._offsetOrientation.roll - roll;
  19267. this._offsetOrientation.yaw = yaw;
  19268. this._offsetOrientation.pitch = pitch;
  19269. this._offsetOrientation.roll = roll;
  19270. }
  19271. };
  19272. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19273. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19274. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19275. };
  19276. OculusCamera.prototype.detachControl = function (element) {
  19277. _super.prototype.detachControl.call(this, element);
  19278. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19279. };
  19280. return OculusCamera;
  19281. })(BABYLON.FreeCamera);
  19282. BABYLON.OculusCamera = OculusCamera;
  19283. })(BABYLON || (BABYLON = {}));
  19284. //# sourceMappingURL=babylon.oculusCamera.js.map
  19285. var BABYLON;
  19286. (function (BABYLON) {
  19287. var OculusRiftDevKit2013_Metric = {
  19288. HResolution: 1280,
  19289. VResolution: 800,
  19290. HScreenSize: 0.149759993,
  19291. VScreenSize: 0.0935999975,
  19292. VScreenCenter: 0.0467999987,
  19293. EyeToScreenDistance: 0.0410000011,
  19294. LensSeparationDistance: 0.0635000020,
  19295. InterpupillaryDistance: 0.0640000030,
  19296. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19297. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19298. PostProcessScaleFactor: 1.714605507808412,
  19299. LensCenterOffset: 0.151976421
  19300. };
  19301. var _OculusInnerGamepadCamera = (function (_super) {
  19302. __extends(_OculusInnerGamepadCamera, _super);
  19303. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19304. _super.call(this, name, position, scene);
  19305. this._workMatrix = new BABYLON.Matrix();
  19306. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19307. // Constants
  19308. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19309. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19310. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19311. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19312. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19313. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19314. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19315. // Postprocess
  19316. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19317. }
  19318. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19319. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19320. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19321. return this._projectionMatrix;
  19322. };
  19323. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19324. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19325. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19326. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19327. // Computing target and final matrix
  19328. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19329. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19330. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19331. return this._viewMatrix;
  19332. };
  19333. return _OculusInnerGamepadCamera;
  19334. })(BABYLON.FreeCamera);
  19335. var OculusGamepadCamera = (function (_super) {
  19336. __extends(OculusGamepadCamera, _super);
  19337. function OculusGamepadCamera(name, position, scene) {
  19338. var _this = this;
  19339. _super.call(this, name, position, scene);
  19340. this.angularSensibility = 200;
  19341. this.moveSensibility = 75;
  19342. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19343. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19344. this.subCameras.push(this._leftCamera);
  19345. this.subCameras.push(this._rightCamera);
  19346. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19347. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19348. _this._onNewGameConnected(gamepad);
  19349. });
  19350. }
  19351. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19352. // Only the first gamepad can control the camera
  19353. if (gamepad.index === 0) {
  19354. this._gamepad = gamepad;
  19355. }
  19356. };
  19357. OculusGamepadCamera.prototype._update = function () {
  19358. this._leftCamera.position.copyFrom(this.position);
  19359. this._rightCamera.position.copyFrom(this.position);
  19360. this._updateCamera(this._leftCamera);
  19361. this._updateCamera(this._rightCamera);
  19362. _super.prototype._update.call(this);
  19363. };
  19364. OculusGamepadCamera.prototype._checkInputs = function () {
  19365. if (!this._gamepad) {
  19366. return;
  19367. }
  19368. var LSValues = this._gamepad.leftStick;
  19369. var normalizedLX = LSValues.x / this.moveSensibility;
  19370. var normalizedLY = LSValues.y / this.moveSensibility;
  19371. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19372. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19373. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19374. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19375. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19376. };
  19377. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19378. camera.minZ = this.minZ;
  19379. camera.maxZ = this.maxZ;
  19380. camera.rotation.x = this.rotation.x;
  19381. camera.rotation.y = this.rotation.y;
  19382. camera.rotation.z = this.rotation.z;
  19383. };
  19384. // Oculus events
  19385. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19386. var yaw = evt.alpha / 180 * Math.PI;
  19387. var pitch = evt.beta / 180 * Math.PI;
  19388. var roll = evt.gamma / 180 * Math.PI;
  19389. if (!this._offsetOrientation) {
  19390. this._offsetOrientation = {
  19391. yaw: yaw,
  19392. pitch: pitch,
  19393. roll: roll
  19394. };
  19395. return;
  19396. } else {
  19397. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19398. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19399. this.rotation.z += this._offsetOrientation.roll - roll;
  19400. this._offsetOrientation.yaw = yaw;
  19401. this._offsetOrientation.pitch = pitch;
  19402. this._offsetOrientation.roll = roll;
  19403. }
  19404. };
  19405. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19406. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19407. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19408. };
  19409. OculusGamepadCamera.prototype.detachControl = function (element) {
  19410. _super.prototype.detachControl.call(this, element);
  19411. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19412. };
  19413. OculusGamepadCamera.prototype.dispose = function () {
  19414. this._gamepads.dispose();
  19415. _super.prototype.dispose.call(this);
  19416. };
  19417. return OculusGamepadCamera;
  19418. })(BABYLON.FreeCamera);
  19419. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19420. })(BABYLON || (BABYLON = {}));
  19421. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19422. var BABYLON;
  19423. (function (BABYLON) {
  19424. // We're mainly based on the logic defined into the FreeCamera code
  19425. var VirtualJoysticksCamera = (function (_super) {
  19426. __extends(VirtualJoysticksCamera, _super);
  19427. function VirtualJoysticksCamera(name, position, scene) {
  19428. _super.call(this, name, position, scene);
  19429. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19430. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19431. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19432. this._leftjoystick.setJoystickSensibility(0.15);
  19433. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19434. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19435. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19436. this._rightjoystick.reverseUpDown = true;
  19437. this._rightjoystick.setJoystickSensibility(0.05);
  19438. this._rightjoystick.setJoystickColor("yellow");
  19439. }
  19440. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19441. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19442. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19443. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19444. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19445. if (!this._leftjoystick.pressed) {
  19446. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19447. }
  19448. if (!this._rightjoystick.pressed) {
  19449. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19450. }
  19451. };
  19452. VirtualJoysticksCamera.prototype.dispose = function () {
  19453. this._leftjoystick.releaseCanvas();
  19454. _super.prototype.dispose.call(this);
  19455. };
  19456. return VirtualJoysticksCamera;
  19457. })(BABYLON.FreeCamera);
  19458. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19459. })(BABYLON || (BABYLON = {}));
  19460. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19461. var BABYLON;
  19462. (function (BABYLON) {
  19463. var ShaderMaterial = (function (_super) {
  19464. __extends(ShaderMaterial, _super);
  19465. function ShaderMaterial(name, scene, shaderPath, options) {
  19466. _super.call(this, name, scene);
  19467. this._textures = new Array();
  19468. this._floats = new Array();
  19469. this._floatsArrays = {};
  19470. this._colors3 = new Array();
  19471. this._colors4 = new Array();
  19472. this._vectors2 = new Array();
  19473. this._vectors3 = new Array();
  19474. this._matrices = new Array();
  19475. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19476. this._shaderPath = shaderPath;
  19477. options.needAlphaBlending = options.needAlphaBlending || false;
  19478. options.needAlphaTesting = options.needAlphaTesting || false;
  19479. options.attributes = options.attributes || ["position", "normal", "uv"];
  19480. options.uniforms = options.uniforms || ["worldViewProjection"];
  19481. options.samplers = options.samplers || [];
  19482. this._options = options;
  19483. }
  19484. ShaderMaterial.prototype.needAlphaBlending = function () {
  19485. return this._options.needAlphaBlending;
  19486. };
  19487. ShaderMaterial.prototype.needAlphaTesting = function () {
  19488. return this._options.needAlphaTesting;
  19489. };
  19490. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19491. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19492. this._options.uniforms.push(uniformName);
  19493. }
  19494. };
  19495. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19496. if (this._options.samplers.indexOf(name) === -1) {
  19497. this._options.samplers.push(name);
  19498. }
  19499. this._textures[name] = texture;
  19500. return this;
  19501. };
  19502. ShaderMaterial.prototype.setFloat = function (name, value) {
  19503. this._checkUniform(name);
  19504. this._floats[name] = value;
  19505. return this;
  19506. };
  19507. ShaderMaterial.prototype.setFloats = function (name, value) {
  19508. this._checkUniform(name);
  19509. this._floatsArrays[name] = value;
  19510. return this;
  19511. };
  19512. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19513. this._checkUniform(name);
  19514. this._colors3[name] = value;
  19515. return this;
  19516. };
  19517. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19518. this._checkUniform(name);
  19519. this._colors4[name] = value;
  19520. return this;
  19521. };
  19522. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19523. this._checkUniform(name);
  19524. this._vectors2[name] = value;
  19525. return this;
  19526. };
  19527. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19528. this._checkUniform(name);
  19529. this._vectors3[name] = value;
  19530. return this;
  19531. };
  19532. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19533. this._checkUniform(name);
  19534. this._matrices[name] = value;
  19535. return this;
  19536. };
  19537. ShaderMaterial.prototype.isReady = function () {
  19538. var scene = this.getScene();
  19539. var engine = scene.getEngine();
  19540. if (!this.checkReadyOnEveryCall) {
  19541. if (this._renderId === scene.getRenderId()) {
  19542. return true;
  19543. }
  19544. }
  19545. var previousEffect = this._effect;
  19546. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19547. if (!this._effect.isReady()) {
  19548. return false;
  19549. }
  19550. if (previousEffect !== this._effect) {
  19551. scene.resetCachedMaterial();
  19552. }
  19553. this._renderId = scene.getRenderId();
  19554. return true;
  19555. };
  19556. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19557. var scene = this.getScene();
  19558. if (this._options.uniforms.indexOf("world") !== -1) {
  19559. this._effect.setMatrix("world", world);
  19560. }
  19561. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19562. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19563. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19564. }
  19565. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19566. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19567. }
  19568. };
  19569. ShaderMaterial.prototype.bind = function (world) {
  19570. // Std values
  19571. this.bindOnlyWorldMatrix(world);
  19572. if (this.getScene().getCachedMaterial() !== this) {
  19573. if (this._options.uniforms.indexOf("view") !== -1) {
  19574. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19575. }
  19576. if (this._options.uniforms.indexOf("projection") !== -1) {
  19577. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19578. }
  19579. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19580. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19581. }
  19582. for (var name in this._textures) {
  19583. this._effect.setTexture(name, this._textures[name]);
  19584. }
  19585. for (name in this._floats) {
  19586. this._effect.setFloat(name, this._floats[name]);
  19587. }
  19588. for (name in this._floatsArrays) {
  19589. this._effect.setArray(name, this._floatsArrays[name]);
  19590. }
  19591. for (name in this._colors3) {
  19592. this._effect.setColor3(name, this._colors3[name]);
  19593. }
  19594. for (name in this._colors4) {
  19595. var color = this._colors4[name];
  19596. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19597. }
  19598. for (name in this._vectors2) {
  19599. this._effect.setVector2(name, this._vectors2[name]);
  19600. }
  19601. for (name in this._vectors3) {
  19602. this._effect.setVector3(name, this._vectors3[name]);
  19603. }
  19604. for (name in this._matrices) {
  19605. this._effect.setMatrix(name, this._matrices[name]);
  19606. }
  19607. }
  19608. _super.prototype.bind.call(this, world, null);
  19609. };
  19610. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19611. for (var name in this._textures) {
  19612. this._textures[name].dispose();
  19613. }
  19614. this._textures = [];
  19615. _super.prototype.dispose.call(this, forceDisposeEffect);
  19616. };
  19617. return ShaderMaterial;
  19618. })(BABYLON.Material);
  19619. BABYLON.ShaderMaterial = ShaderMaterial;
  19620. })(BABYLON || (BABYLON = {}));
  19621. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19622. var BABYLON;
  19623. (function (BABYLON) {
  19624. var VertexData = (function () {
  19625. function VertexData() {
  19626. }
  19627. VertexData.prototype.set = function (data, kind) {
  19628. switch (kind) {
  19629. case BABYLON.VertexBuffer.PositionKind:
  19630. this.positions = data;
  19631. break;
  19632. case BABYLON.VertexBuffer.NormalKind:
  19633. this.normals = data;
  19634. break;
  19635. case BABYLON.VertexBuffer.UVKind:
  19636. this.uvs = data;
  19637. break;
  19638. case BABYLON.VertexBuffer.UV2Kind:
  19639. this.uv2s = data;
  19640. break;
  19641. case BABYLON.VertexBuffer.ColorKind:
  19642. this.colors = data;
  19643. break;
  19644. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19645. this.matricesIndices = data;
  19646. break;
  19647. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19648. this.matricesWeights = data;
  19649. break;
  19650. }
  19651. };
  19652. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19653. this._applyTo(mesh, updatable);
  19654. };
  19655. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19656. this._applyTo(geometry, updatable);
  19657. };
  19658. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19659. this._update(mesh);
  19660. };
  19661. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19662. this._update(geometry);
  19663. };
  19664. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19665. if (this.positions) {
  19666. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19667. }
  19668. if (this.normals) {
  19669. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19670. }
  19671. if (this.uvs) {
  19672. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19673. }
  19674. if (this.uv2s) {
  19675. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19676. }
  19677. if (this.colors) {
  19678. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19679. }
  19680. if (this.matricesIndices) {
  19681. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19682. }
  19683. if (this.matricesWeights) {
  19684. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19685. }
  19686. if (this.indices) {
  19687. meshOrGeometry.setIndices(this.indices);
  19688. }
  19689. };
  19690. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19691. if (this.positions) {
  19692. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19693. }
  19694. if (this.normals) {
  19695. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19696. }
  19697. if (this.uvs) {
  19698. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19699. }
  19700. if (this.uv2s) {
  19701. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19702. }
  19703. if (this.colors) {
  19704. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19705. }
  19706. if (this.matricesIndices) {
  19707. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19708. }
  19709. if (this.matricesWeights) {
  19710. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19711. }
  19712. if (this.indices) {
  19713. meshOrGeometry.setIndices(this.indices);
  19714. }
  19715. };
  19716. VertexData.prototype.transform = function (matrix) {
  19717. var transformed = BABYLON.Vector3.Zero();
  19718. if (this.positions) {
  19719. var position = BABYLON.Vector3.Zero();
  19720. for (var index = 0; index < this.positions.length; index += 3) {
  19721. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19722. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19723. this.positions[index] = transformed.x;
  19724. this.positions[index + 1] = transformed.y;
  19725. this.positions[index + 2] = transformed.z;
  19726. }
  19727. }
  19728. if (this.normals) {
  19729. var normal = BABYLON.Vector3.Zero();
  19730. for (index = 0; index < this.normals.length; index += 3) {
  19731. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19732. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19733. this.normals[index] = transformed.x;
  19734. this.normals[index + 1] = transformed.y;
  19735. this.normals[index + 2] = transformed.z;
  19736. }
  19737. }
  19738. };
  19739. VertexData.prototype.merge = function (other) {
  19740. if (other.indices) {
  19741. if (!this.indices) {
  19742. this.indices = [];
  19743. }
  19744. var offset = this.positions ? this.positions.length / 3 : 0;
  19745. for (var index = 0; index < other.indices.length; index++) {
  19746. this.indices.push(other.indices[index] + offset);
  19747. }
  19748. }
  19749. if (other.positions) {
  19750. if (!this.positions) {
  19751. this.positions = [];
  19752. }
  19753. for (index = 0; index < other.positions.length; index++) {
  19754. this.positions.push(other.positions[index]);
  19755. }
  19756. }
  19757. if (other.normals) {
  19758. if (!this.normals) {
  19759. this.normals = [];
  19760. }
  19761. for (index = 0; index < other.normals.length; index++) {
  19762. this.normals.push(other.normals[index]);
  19763. }
  19764. }
  19765. if (other.uvs) {
  19766. if (!this.uvs) {
  19767. this.uvs = [];
  19768. }
  19769. for (index = 0; index < other.uvs.length; index++) {
  19770. this.uvs.push(other.uvs[index]);
  19771. }
  19772. }
  19773. if (other.uv2s) {
  19774. if (!this.uv2s) {
  19775. this.uv2s = [];
  19776. }
  19777. for (index = 0; index < other.uv2s.length; index++) {
  19778. this.uv2s.push(other.uv2s[index]);
  19779. }
  19780. }
  19781. if (other.matricesIndices) {
  19782. if (!this.matricesIndices) {
  19783. this.matricesIndices = [];
  19784. }
  19785. for (index = 0; index < other.matricesIndices.length; index++) {
  19786. this.matricesIndices.push(other.matricesIndices[index]);
  19787. }
  19788. }
  19789. if (other.matricesWeights) {
  19790. if (!this.matricesWeights) {
  19791. this.matricesWeights = [];
  19792. }
  19793. for (index = 0; index < other.matricesWeights.length; index++) {
  19794. this.matricesWeights.push(other.matricesWeights[index]);
  19795. }
  19796. }
  19797. if (other.colors) {
  19798. if (!this.colors) {
  19799. this.colors = [];
  19800. }
  19801. for (index = 0; index < other.colors.length; index++) {
  19802. this.colors.push(other.colors[index]);
  19803. }
  19804. }
  19805. };
  19806. // Statics
  19807. VertexData.ExtractFromMesh = function (mesh) {
  19808. return VertexData._ExtractFrom(mesh);
  19809. };
  19810. VertexData.ExtractFromGeometry = function (geometry) {
  19811. return VertexData._ExtractFrom(geometry);
  19812. };
  19813. VertexData._ExtractFrom = function (meshOrGeometry) {
  19814. var result = new BABYLON.VertexData();
  19815. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19816. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19817. }
  19818. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19819. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19820. }
  19821. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19822. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19823. }
  19824. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19825. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19826. }
  19827. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19828. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19829. }
  19830. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19831. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19832. }
  19833. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19834. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19835. }
  19836. result.indices = meshOrGeometry.getIndices();
  19837. return result;
  19838. };
  19839. VertexData.CreateBox = function (size) {
  19840. var normalsSource = [
  19841. new BABYLON.Vector3(0, 0, 1),
  19842. new BABYLON.Vector3(0, 0, -1),
  19843. new BABYLON.Vector3(1, 0, 0),
  19844. new BABYLON.Vector3(-1, 0, 0),
  19845. new BABYLON.Vector3(0, 1, 0),
  19846. new BABYLON.Vector3(0, -1, 0)
  19847. ];
  19848. var indices = [];
  19849. var positions = [];
  19850. var normals = [];
  19851. var uvs = [];
  19852. size = size || 1;
  19853. for (var index = 0; index < normalsSource.length; index++) {
  19854. var normal = normalsSource[index];
  19855. // Get two vectors perpendicular to the face normal and to each other.
  19856. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  19857. var side2 = BABYLON.Vector3.Cross(normal, side1);
  19858. // Six indices (two triangles) per face.
  19859. var verticesLength = positions.length / 3;
  19860. indices.push(verticesLength);
  19861. indices.push(verticesLength + 1);
  19862. indices.push(verticesLength + 2);
  19863. indices.push(verticesLength);
  19864. indices.push(verticesLength + 2);
  19865. indices.push(verticesLength + 3);
  19866. // Four vertices per face.
  19867. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  19868. positions.push(vertex.x, vertex.y, vertex.z);
  19869. normals.push(normal.x, normal.y, normal.z);
  19870. uvs.push(1.0, 1.0);
  19871. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  19872. positions.push(vertex.x, vertex.y, vertex.z);
  19873. normals.push(normal.x, normal.y, normal.z);
  19874. uvs.push(0.0, 1.0);
  19875. vertex = normal.add(side1).add(side2).scale(size / 2);
  19876. positions.push(vertex.x, vertex.y, vertex.z);
  19877. normals.push(normal.x, normal.y, normal.z);
  19878. uvs.push(0.0, 0.0);
  19879. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  19880. positions.push(vertex.x, vertex.y, vertex.z);
  19881. normals.push(normal.x, normal.y, normal.z);
  19882. uvs.push(1.0, 0.0);
  19883. }
  19884. // Result
  19885. var vertexData = new BABYLON.VertexData();
  19886. vertexData.indices = indices;
  19887. vertexData.positions = positions;
  19888. vertexData.normals = normals;
  19889. vertexData.uvs = uvs;
  19890. return vertexData;
  19891. };
  19892. VertexData.CreateSphere = function (segments, diameter) {
  19893. segments = segments || 32;
  19894. diameter = diameter || 1;
  19895. var radius = diameter / 2;
  19896. var totalZRotationSteps = 2 + segments;
  19897. var totalYRotationSteps = 2 * totalZRotationSteps;
  19898. var indices = [];
  19899. var positions = [];
  19900. var normals = [];
  19901. var uvs = [];
  19902. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  19903. var normalizedZ = zRotationStep / totalZRotationSteps;
  19904. var angleZ = (normalizedZ * Math.PI);
  19905. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  19906. var normalizedY = yRotationStep / totalYRotationSteps;
  19907. var angleY = normalizedY * Math.PI * 2;
  19908. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  19909. var rotationY = BABYLON.Matrix.RotationY(angleY);
  19910. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  19911. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  19912. var vertex = complete.scale(radius);
  19913. var normal = BABYLON.Vector3.Normalize(vertex);
  19914. positions.push(vertex.x, vertex.y, vertex.z);
  19915. normals.push(normal.x, normal.y, normal.z);
  19916. uvs.push(normalizedZ, normalizedY);
  19917. }
  19918. if (zRotationStep > 0) {
  19919. var verticesCount = positions.length / 3;
  19920. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  19921. indices.push((firstIndex));
  19922. indices.push((firstIndex + 1));
  19923. indices.push(firstIndex + totalYRotationSteps + 1);
  19924. indices.push((firstIndex + totalYRotationSteps + 1));
  19925. indices.push((firstIndex + 1));
  19926. indices.push((firstIndex + totalYRotationSteps + 2));
  19927. }
  19928. }
  19929. }
  19930. // Result
  19931. var vertexData = new BABYLON.VertexData();
  19932. vertexData.indices = indices;
  19933. vertexData.positions = positions;
  19934. vertexData.normals = normals;
  19935. vertexData.uvs = uvs;
  19936. return vertexData;
  19937. };
  19938. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  19939. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19940. var radiusTop = diameterTop / 2;
  19941. var radiusBottom = diameterBottom / 2;
  19942. var indices = [];
  19943. var positions = [];
  19944. var normals = [];
  19945. var uvs = [];
  19946. height = height || 1;
  19947. diameterTop = diameterTop || 0.5;
  19948. diameterBottom = diameterBottom || 1;
  19949. tessellation = tessellation || 16;
  19950. subdivisions = subdivisions || 1;
  19951. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  19952. var getCircleVector = function (i) {
  19953. var angle = (i * 2.0 * Math.PI / tessellation);
  19954. var dx = Math.cos(angle);
  19955. var dz = Math.sin(angle);
  19956. return new BABYLON.Vector3(dx, 0, dz);
  19957. };
  19958. var createCylinderCap = function (isTop) {
  19959. var radius = isTop ? radiusTop : radiusBottom;
  19960. if (radius == 0) {
  19961. return;
  19962. }
  19963. var vbase = positions.length / 3;
  19964. var offset = new BABYLON.Vector3(0, height / 2, 0);
  19965. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  19966. if (!isTop) {
  19967. offset.scaleInPlace(-1);
  19968. textureScale.x = -textureScale.x;
  19969. }
  19970. for (i = 0; i < tessellation; i++) {
  19971. var circleVector = getCircleVector(i);
  19972. var position = circleVector.scale(radius).add(offset);
  19973. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  19974. positions.push(position.x, position.y, position.z);
  19975. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19976. }
  19977. for (var i = 0; i < tessellation - 2; i++) {
  19978. if (!isTop) {
  19979. indices.push(vbase);
  19980. indices.push(vbase + (i + 2) % tessellation);
  19981. indices.push(vbase + (i + 1) % tessellation);
  19982. } else {
  19983. indices.push(vbase);
  19984. indices.push(vbase + (i + 1) % tessellation);
  19985. indices.push(vbase + (i + 2) % tessellation);
  19986. }
  19987. }
  19988. };
  19989. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  19990. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  19991. var stride = tessellation + 1;
  19992. for (var i = 0; i <= tessellation; i++) {
  19993. var circleVector = getCircleVector(i);
  19994. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  19995. var position, radius = radiusBottom;
  19996. for (var s = 0; s <= subdivisions; s++) {
  19997. // Update variables
  19998. position = circleVector.scale(radius);
  19999. position.addInPlace(base.add(offset.scale(s)));
  20000. textureCoordinate.y += 1 / subdivisions;
  20001. radius += (radiusTop - radiusBottom) / subdivisions;
  20002. // Push in arrays
  20003. positions.push(position.x, position.y, position.z);
  20004. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20005. }
  20006. }
  20007. subdivisions += 1;
  20008. for (var s = 0; s < subdivisions - 1; s++) {
  20009. for (var i = 0; i <= tessellation; i++) {
  20010. indices.push(i * subdivisions + s);
  20011. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20012. indices.push(i * subdivisions + (s + 1));
  20013. indices.push(i * subdivisions + (s + 1));
  20014. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20015. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20016. }
  20017. }
  20018. // Create flat triangle fan caps to seal the top and bottom.
  20019. createCylinderCap(true);
  20020. createCylinderCap(false);
  20021. // Normals
  20022. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20023. // Result
  20024. var vertexData = new BABYLON.VertexData();
  20025. vertexData.indices = indices;
  20026. vertexData.positions = positions;
  20027. vertexData.normals = normals;
  20028. vertexData.uvs = uvs;
  20029. return vertexData;
  20030. };
  20031. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20032. var indices = [];
  20033. var positions = [];
  20034. var normals = [];
  20035. var uvs = [];
  20036. diameter = diameter || 1;
  20037. thickness = thickness || 0.5;
  20038. tessellation = tessellation || 16;
  20039. var stride = tessellation + 1;
  20040. for (var i = 0; i <= tessellation; i++) {
  20041. var u = i / tessellation;
  20042. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20043. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20044. for (var j = 0; j <= tessellation; j++) {
  20045. var v = 1 - j / tessellation;
  20046. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20047. var dx = Math.cos(innerAngle);
  20048. var dy = Math.sin(innerAngle);
  20049. // Create a vertex.
  20050. var normal = new BABYLON.Vector3(dx, dy, 0);
  20051. var position = normal.scale(thickness / 2);
  20052. var textureCoordinate = new BABYLON.Vector2(u, v);
  20053. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20054. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20055. positions.push(position.x, position.y, position.z);
  20056. normals.push(normal.x, normal.y, normal.z);
  20057. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20058. // And create indices for two triangles.
  20059. var nextI = (i + 1) % stride;
  20060. var nextJ = (j + 1) % stride;
  20061. indices.push(i * stride + j);
  20062. indices.push(i * stride + nextJ);
  20063. indices.push(nextI * stride + j);
  20064. indices.push(i * stride + nextJ);
  20065. indices.push(nextI * stride + nextJ);
  20066. indices.push(nextI * stride + j);
  20067. }
  20068. }
  20069. // Result
  20070. var vertexData = new BABYLON.VertexData();
  20071. vertexData.indices = indices;
  20072. vertexData.positions = positions;
  20073. vertexData.normals = normals;
  20074. vertexData.uvs = uvs;
  20075. return vertexData;
  20076. };
  20077. VertexData.CreateLines = function (points) {
  20078. var indices = [];
  20079. var positions = [];
  20080. for (var index = 0; index < points.length; index++) {
  20081. positions.push(points[index].x, points[index].y, points[index].z);
  20082. if (index > 0) {
  20083. indices.push(index - 1);
  20084. indices.push(index);
  20085. }
  20086. }
  20087. // Result
  20088. var vertexData = new BABYLON.VertexData();
  20089. vertexData.indices = indices;
  20090. vertexData.positions = positions;
  20091. return vertexData;
  20092. };
  20093. VertexData.CreateGround = function (width, height, subdivisions) {
  20094. var indices = [];
  20095. var positions = [];
  20096. var normals = [];
  20097. var uvs = [];
  20098. var row, col;
  20099. width = width || 1;
  20100. height = height || 1;
  20101. subdivisions = subdivisions || 1;
  20102. for (row = 0; row <= subdivisions; row++) {
  20103. for (col = 0; col <= subdivisions; col++) {
  20104. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20105. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20106. positions.push(position.x, position.y, position.z);
  20107. normals.push(normal.x, normal.y, normal.z);
  20108. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20109. }
  20110. }
  20111. for (row = 0; row < subdivisions; row++) {
  20112. for (col = 0; col < subdivisions; col++) {
  20113. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20114. indices.push(col + 1 + row * (subdivisions + 1));
  20115. indices.push(col + row * (subdivisions + 1));
  20116. indices.push(col + (row + 1) * (subdivisions + 1));
  20117. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20118. indices.push(col + row * (subdivisions + 1));
  20119. }
  20120. }
  20121. // Result
  20122. var vertexData = new BABYLON.VertexData();
  20123. vertexData.indices = indices;
  20124. vertexData.positions = positions;
  20125. vertexData.normals = normals;
  20126. vertexData.uvs = uvs;
  20127. return vertexData;
  20128. };
  20129. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  20130. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  20131. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  20132. var indices = [];
  20133. var positions = [];
  20134. var normals = [];
  20135. var uvs = [];
  20136. var row, col, tileRow, tileCol;
  20137. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  20138. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  20139. precision.w = (precision.w < 1) ? 1 : precision.w;
  20140. precision.h = (precision.h < 1) ? 1 : precision.h;
  20141. var tileSize = {
  20142. 'w': (xmax - xmin) / subdivisions.w,
  20143. 'h': (zmax - zmin) / subdivisions.h
  20144. };
  20145. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  20146. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  20147. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  20148. }
  20149. }
  20150. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  20151. // Indices
  20152. var base = positions.length / 3;
  20153. var rowLength = precision.w + 1;
  20154. for (row = 0; row < precision.h; row++) {
  20155. for (col = 0; col < precision.w; col++) {
  20156. var square = [
  20157. base + col + row * rowLength,
  20158. base + (col + 1) + row * rowLength,
  20159. base + (col + 1) + (row + 1) * rowLength,
  20160. base + col + (row + 1) * rowLength
  20161. ];
  20162. indices.push(square[1]);
  20163. indices.push(square[2]);
  20164. indices.push(square[3]);
  20165. indices.push(square[0]);
  20166. indices.push(square[1]);
  20167. indices.push(square[3]);
  20168. }
  20169. }
  20170. // Position, normals and uvs
  20171. var position = BABYLON.Vector3.Zero();
  20172. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20173. for (row = 0; row <= precision.h; row++) {
  20174. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  20175. for (col = 0; col <= precision.w; col++) {
  20176. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  20177. position.y = 0;
  20178. positions.push(position.x, position.y, position.z);
  20179. normals.push(normal.x, normal.y, normal.z);
  20180. uvs.push(col / precision.w, row / precision.h);
  20181. }
  20182. }
  20183. }
  20184. // Result
  20185. var vertexData = new BABYLON.VertexData();
  20186. vertexData.indices = indices;
  20187. vertexData.positions = positions;
  20188. vertexData.normals = normals;
  20189. vertexData.uvs = uvs;
  20190. return vertexData;
  20191. };
  20192. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  20193. var indices = [];
  20194. var positions = [];
  20195. var normals = [];
  20196. var uvs = [];
  20197. var row, col;
  20198. for (row = 0; row <= subdivisions; row++) {
  20199. for (col = 0; col <= subdivisions; col++) {
  20200. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20201. // Compute height
  20202. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  20203. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  20204. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  20205. var r = buffer[pos] / 255.0;
  20206. var g = buffer[pos + 1] / 255.0;
  20207. var b = buffer[pos + 2] / 255.0;
  20208. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20209. position.y = minHeight + (maxHeight - minHeight) * gradient;
  20210. // Add vertex
  20211. positions.push(position.x, position.y, position.z);
  20212. normals.push(0, 0, 0);
  20213. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20214. }
  20215. }
  20216. for (row = 0; row < subdivisions; row++) {
  20217. for (col = 0; col < subdivisions; col++) {
  20218. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20219. indices.push(col + 1 + row * (subdivisions + 1));
  20220. indices.push(col + row * (subdivisions + 1));
  20221. indices.push(col + (row + 1) * (subdivisions + 1));
  20222. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20223. indices.push(col + row * (subdivisions + 1));
  20224. }
  20225. }
  20226. // Normals
  20227. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20228. // Result
  20229. var vertexData = new BABYLON.VertexData();
  20230. vertexData.indices = indices;
  20231. vertexData.positions = positions;
  20232. vertexData.normals = normals;
  20233. vertexData.uvs = uvs;
  20234. return vertexData;
  20235. };
  20236. VertexData.CreatePlane = function (size) {
  20237. var indices = [];
  20238. var positions = [];
  20239. var normals = [];
  20240. var uvs = [];
  20241. size = size || 1;
  20242. // Vertices
  20243. var halfSize = size / 2.0;
  20244. positions.push(-halfSize, -halfSize, 0);
  20245. normals.push(0, 0, -1.0);
  20246. uvs.push(0.0, 0.0);
  20247. positions.push(halfSize, -halfSize, 0);
  20248. normals.push(0, 0, -1.0);
  20249. uvs.push(1.0, 0.0);
  20250. positions.push(halfSize, halfSize, 0);
  20251. normals.push(0, 0, -1.0);
  20252. uvs.push(1.0, 1.0);
  20253. positions.push(-halfSize, halfSize, 0);
  20254. normals.push(0, 0, -1.0);
  20255. uvs.push(0.0, 1.0);
  20256. // Indices
  20257. indices.push(0);
  20258. indices.push(1);
  20259. indices.push(2);
  20260. indices.push(0);
  20261. indices.push(2);
  20262. indices.push(3);
  20263. // Result
  20264. var vertexData = new BABYLON.VertexData();
  20265. vertexData.indices = indices;
  20266. vertexData.positions = positions;
  20267. vertexData.normals = normals;
  20268. vertexData.uvs = uvs;
  20269. return vertexData;
  20270. };
  20271. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20272. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20273. var indices = [];
  20274. var positions = [];
  20275. var normals = [];
  20276. var uvs = [];
  20277. radius = radius || 2;
  20278. tube = tube || 0.5;
  20279. radialSegments = radialSegments || 32;
  20280. tubularSegments = tubularSegments || 32;
  20281. p = p || 2;
  20282. q = q || 3;
  20283. // Helper
  20284. var getPos = function (angle) {
  20285. var cu = Math.cos(angle);
  20286. var su = Math.sin(angle);
  20287. var quOverP = q / p * angle;
  20288. var cs = Math.cos(quOverP);
  20289. var tx = radius * (2 + cs) * 0.5 * cu;
  20290. var ty = radius * (2 + cs) * su * 0.5;
  20291. var tz = radius * Math.sin(quOverP) * 0.5;
  20292. return new BABYLON.Vector3(tx, ty, tz);
  20293. };
  20294. for (var i = 0; i <= radialSegments; i++) {
  20295. var modI = i % radialSegments;
  20296. var u = modI / radialSegments * 2 * p * Math.PI;
  20297. var p1 = getPos(u);
  20298. var p2 = getPos(u + 0.01);
  20299. var tang = p2.subtract(p1);
  20300. var n = p2.add(p1);
  20301. var bitan = BABYLON.Vector3.Cross(tang, n);
  20302. n = BABYLON.Vector3.Cross(bitan, tang);
  20303. bitan.normalize();
  20304. n.normalize();
  20305. for (var j = 0; j < tubularSegments; j++) {
  20306. var modJ = j % tubularSegments;
  20307. var v = modJ / tubularSegments * 2 * Math.PI;
  20308. var cx = -tube * Math.cos(v);
  20309. var cy = tube * Math.sin(v);
  20310. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20311. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20312. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20313. uvs.push(i / radialSegments);
  20314. uvs.push(j / tubularSegments);
  20315. }
  20316. }
  20317. for (i = 0; i < radialSegments; i++) {
  20318. for (j = 0; j < tubularSegments; j++) {
  20319. var jNext = (j + 1) % tubularSegments;
  20320. var a = i * tubularSegments + j;
  20321. var b = (i + 1) * tubularSegments + j;
  20322. var c = (i + 1) * tubularSegments + jNext;
  20323. var d = i * tubularSegments + jNext;
  20324. indices.push(d);
  20325. indices.push(b);
  20326. indices.push(a);
  20327. indices.push(d);
  20328. indices.push(c);
  20329. indices.push(b);
  20330. }
  20331. }
  20332. // Normals
  20333. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20334. // Result
  20335. var vertexData = new BABYLON.VertexData();
  20336. vertexData.indices = indices;
  20337. vertexData.positions = positions;
  20338. vertexData.normals = normals;
  20339. vertexData.uvs = uvs;
  20340. return vertexData;
  20341. };
  20342. // Tools
  20343. VertexData.ComputeNormals = function (positions, indices, normals) {
  20344. var positionVectors = [];
  20345. var facesOfVertices = [];
  20346. var index;
  20347. for (index = 0; index < positions.length; index += 3) {
  20348. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20349. positionVectors.push(vector3);
  20350. facesOfVertices.push([]);
  20351. }
  20352. // Compute normals
  20353. var facesNormals = [];
  20354. for (index = 0; index < indices.length / 3; index++) {
  20355. var i1 = indices[index * 3];
  20356. var i2 = indices[index * 3 + 1];
  20357. var i3 = indices[index * 3 + 2];
  20358. var p1 = positionVectors[i1];
  20359. var p2 = positionVectors[i2];
  20360. var p3 = positionVectors[i3];
  20361. var p1p2 = p1.subtract(p2);
  20362. var p3p2 = p3.subtract(p2);
  20363. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20364. facesOfVertices[i1].push(index);
  20365. facesOfVertices[i2].push(index);
  20366. facesOfVertices[i3].push(index);
  20367. }
  20368. for (index = 0; index < positionVectors.length; index++) {
  20369. var faces = facesOfVertices[index];
  20370. var normal = BABYLON.Vector3.Zero();
  20371. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20372. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20373. }
  20374. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20375. normals[index * 3] = normal.x;
  20376. normals[index * 3 + 1] = normal.y;
  20377. normals[index * 3 + 2] = normal.z;
  20378. }
  20379. };
  20380. return VertexData;
  20381. })();
  20382. BABYLON.VertexData = VertexData;
  20383. })(BABYLON || (BABYLON = {}));
  20384. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20385. var BABYLON;
  20386. (function (BABYLON) {
  20387. var buildCamera = function (that, name) {
  20388. that._leftCamera.isIntermediate = true;
  20389. that.subCameras.push(that._leftCamera);
  20390. that.subCameras.push(that._rightCamera);
  20391. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20392. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20393. that._anaglyphPostProcess.onApply = function (effect) {
  20394. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20395. };
  20396. that._update();
  20397. };
  20398. var AnaglyphArcRotateCamera = (function (_super) {
  20399. __extends(AnaglyphArcRotateCamera, _super);
  20400. // ANY
  20401. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20402. _super.call(this, name, alpha, beta, radius, target, scene);
  20403. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20404. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20405. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20406. buildCamera(this, name);
  20407. }
  20408. AnaglyphArcRotateCamera.prototype._update = function () {
  20409. this._updateCamera(this._leftCamera);
  20410. this._updateCamera(this._rightCamera);
  20411. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20412. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20413. _super.prototype._update.call(this);
  20414. };
  20415. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20416. camera.beta = this.beta;
  20417. camera.radius = this.radius;
  20418. camera.minZ = this.minZ;
  20419. camera.maxZ = this.maxZ;
  20420. camera.fov = this.fov;
  20421. camera.target = this.target;
  20422. };
  20423. return AnaglyphArcRotateCamera;
  20424. })(BABYLON.ArcRotateCamera);
  20425. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20426. var AnaglyphFreeCamera = (function (_super) {
  20427. __extends(AnaglyphFreeCamera, _super);
  20428. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20429. _super.call(this, name, position, scene);
  20430. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20431. this._transformMatrix = new BABYLON.Matrix();
  20432. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20433. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20434. buildCamera(this, name);
  20435. }
  20436. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20437. var target = this.getTarget();
  20438. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20439. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20440. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20441. };
  20442. AnaglyphFreeCamera.prototype._update = function () {
  20443. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20444. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20445. this._updateCamera(this._leftCamera);
  20446. this._updateCamera(this._rightCamera);
  20447. _super.prototype._update.call(this);
  20448. };
  20449. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20450. camera.minZ = this.minZ;
  20451. camera.maxZ = this.maxZ;
  20452. camera.fov = this.fov;
  20453. camera.viewport = this.viewport;
  20454. camera.setTarget(this.getTarget());
  20455. };
  20456. return AnaglyphFreeCamera;
  20457. })(BABYLON.FreeCamera);
  20458. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20459. })(BABYLON || (BABYLON = {}));
  20460. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20461. var BABYLON;
  20462. (function (BABYLON) {
  20463. var AnaglyphPostProcess = (function (_super) {
  20464. __extends(AnaglyphPostProcess, _super);
  20465. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20466. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20467. }
  20468. return AnaglyphPostProcess;
  20469. })(BABYLON.PostProcess);
  20470. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20471. })(BABYLON || (BABYLON = {}));
  20472. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20473. var BABYLON;
  20474. (function (BABYLON) {
  20475. var Tags = (function () {
  20476. function Tags() {
  20477. }
  20478. Tags.EnableFor = function (obj) {
  20479. obj._tags = obj._tags || {};
  20480. obj.hasTags = function () {
  20481. return Tags.HasTags(obj);
  20482. };
  20483. obj.addTags = function (tagsString) {
  20484. return Tags.AddTagsTo(obj, tagsString);
  20485. };
  20486. obj.removeTags = function (tagsString) {
  20487. return Tags.RemoveTagsFrom(obj, tagsString);
  20488. };
  20489. obj.matchesTagsQuery = function (tagsQuery) {
  20490. return Tags.MatchesQuery(obj, tagsQuery);
  20491. };
  20492. };
  20493. Tags.DisableFor = function (obj) {
  20494. delete obj._tags;
  20495. delete obj.hasTags;
  20496. delete obj.addTags;
  20497. delete obj.removeTags;
  20498. delete obj.matchesTagsQuery;
  20499. };
  20500. Tags.HasTags = function (obj) {
  20501. if (!obj._tags) {
  20502. return false;
  20503. }
  20504. return !BABYLON.Tools.IsEmpty(obj._tags);
  20505. };
  20506. Tags.GetTags = function (obj) {
  20507. if (!obj._tags) {
  20508. return null;
  20509. }
  20510. return obj._tags;
  20511. };
  20512. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20513. // a tag cannot start with '||', '&&', and '!'
  20514. // it cannot contain whitespaces
  20515. Tags.AddTagsTo = function (obj, tagsString) {
  20516. if (!tagsString) {
  20517. return;
  20518. }
  20519. var tags = tagsString.split(" ");
  20520. for (var t in tags) {
  20521. Tags._AddTagTo(obj, tags[t]);
  20522. }
  20523. };
  20524. Tags._AddTagTo = function (obj, tag) {
  20525. tag = tag.trim();
  20526. if (tag === "" || tag === "true" || tag === "false") {
  20527. return;
  20528. }
  20529. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20530. return;
  20531. }
  20532. Tags.EnableFor(obj);
  20533. obj._tags[tag] = true;
  20534. };
  20535. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20536. if (!Tags.HasTags(obj)) {
  20537. return;
  20538. }
  20539. var tags = tagsString.split(" ");
  20540. for (var t in tags) {
  20541. Tags._RemoveTagFrom(obj, tags[t]);
  20542. }
  20543. };
  20544. Tags._RemoveTagFrom = function (obj, tag) {
  20545. delete obj._tags[tag];
  20546. };
  20547. Tags.MatchesQuery = function (obj, tagsQuery) {
  20548. if (tagsQuery === undefined) {
  20549. return true;
  20550. }
  20551. if (tagsQuery === "") {
  20552. return Tags.HasTags(obj);
  20553. }
  20554. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20555. return Tags.HasTags(obj) && obj._tags[r];
  20556. });
  20557. };
  20558. return Tags;
  20559. })();
  20560. BABYLON.Tags = Tags;
  20561. })(BABYLON || (BABYLON = {}));
  20562. //# sourceMappingURL=babylon.tags.js.map
  20563. var BABYLON;
  20564. (function (BABYLON) {
  20565. (function (Internals) {
  20566. var AndOrNotEvaluator = (function () {
  20567. function AndOrNotEvaluator() {
  20568. }
  20569. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20570. if (!query.match(/\([^\(\)]*\)/g)) {
  20571. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20572. } else {
  20573. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20574. // remove parenthesis
  20575. r = r.slice(1, r.length - 1);
  20576. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20577. });
  20578. }
  20579. if (query === "true") {
  20580. return true;
  20581. }
  20582. if (query === "false") {
  20583. return false;
  20584. }
  20585. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20586. };
  20587. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20588. evaluateCallback = evaluateCallback || (function (r) {
  20589. return r === "true" ? true : false;
  20590. });
  20591. var result;
  20592. var or = parenthesisContent.split("||");
  20593. for (var i in or) {
  20594. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20595. var and = ori.split("&&");
  20596. if (and.length > 1) {
  20597. for (var j = 0; j < and.length; ++j) {
  20598. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20599. if (andj !== "true" && andj !== "false") {
  20600. if (andj[0] === "!") {
  20601. result = !evaluateCallback(andj.substring(1));
  20602. } else {
  20603. result = evaluateCallback(andj);
  20604. }
  20605. } else {
  20606. result = andj === "true" ? true : false;
  20607. }
  20608. if (!result) {
  20609. ori = "false";
  20610. break;
  20611. }
  20612. }
  20613. }
  20614. if (result || ori === "true") {
  20615. result = true;
  20616. break;
  20617. }
  20618. // result equals false (or undefined)
  20619. if (ori !== "true" && ori !== "false") {
  20620. if (ori[0] === "!") {
  20621. result = !evaluateCallback(ori.substring(1));
  20622. } else {
  20623. result = evaluateCallback(ori);
  20624. }
  20625. } else {
  20626. result = ori === "true" ? true : false;
  20627. }
  20628. }
  20629. // the whole parenthesis scope is replaced by 'true' or 'false'
  20630. return result ? "true" : "false";
  20631. };
  20632. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20633. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20634. // remove whitespaces
  20635. r = r.replace(/[\s]/g, function () {
  20636. return "";
  20637. });
  20638. return r.length % 2 ? "!" : "";
  20639. });
  20640. booleanString = booleanString.trim();
  20641. if (booleanString === "!true") {
  20642. booleanString = "false";
  20643. } else if (booleanString === "!false") {
  20644. booleanString = "true";
  20645. }
  20646. return booleanString;
  20647. };
  20648. return AndOrNotEvaluator;
  20649. })();
  20650. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20651. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20652. var Internals = BABYLON.Internals;
  20653. })(BABYLON || (BABYLON = {}));
  20654. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20655. var BABYLON;
  20656. (function (BABYLON) {
  20657. var PostProcessRenderPass = (function () {
  20658. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20659. this._enabled = true;
  20660. this._refCount = 0;
  20661. this._name = name;
  20662. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20663. this.setRenderList(renderList);
  20664. this._renderTexture.onBeforeRender = beforeRender;
  20665. this._renderTexture.onAfterRender = afterRender;
  20666. this._scene = scene;
  20667. this._renderList = renderList;
  20668. }
  20669. // private
  20670. PostProcessRenderPass.prototype._incRefCount = function () {
  20671. if (this._refCount === 0) {
  20672. this._scene.customRenderTargets.push(this._renderTexture);
  20673. }
  20674. return ++this._refCount;
  20675. };
  20676. PostProcessRenderPass.prototype._decRefCount = function () {
  20677. this._refCount--;
  20678. if (this._refCount <= 0) {
  20679. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20680. }
  20681. return this._refCount;
  20682. };
  20683. PostProcessRenderPass.prototype._update = function () {
  20684. this.setRenderList(this._renderList);
  20685. };
  20686. // public
  20687. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20688. this._renderTexture.renderList = renderList;
  20689. };
  20690. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20691. return this._renderTexture;
  20692. };
  20693. return PostProcessRenderPass;
  20694. })();
  20695. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20696. })(BABYLON || (BABYLON = {}));
  20697. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20698. var BABYLON;
  20699. (function (BABYLON) {
  20700. var PostProcessRenderEffect = (function () {
  20701. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20702. this._engine = engine;
  20703. this._name = name;
  20704. this._singleInstance = singleInstance || true;
  20705. this._getPostProcess = getPostProcess;
  20706. this._cameras = [];
  20707. this._indicesForCamera = [];
  20708. this._postProcesses = {};
  20709. this._renderPasses = {};
  20710. this._renderEffectAsPasses = {};
  20711. }
  20712. PostProcessRenderEffect.prototype._update = function () {
  20713. for (var renderPassName in this._renderPasses) {
  20714. this._renderPasses[renderPassName]._update();
  20715. }
  20716. };
  20717. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20718. this._renderPasses[renderPass._name] = renderPass;
  20719. this._linkParameters();
  20720. };
  20721. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20722. delete this._renderPasses[renderPass._name];
  20723. this._linkParameters();
  20724. };
  20725. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20726. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20727. this._linkParameters();
  20728. };
  20729. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20730. for (var renderPassName in this._renderPasses) {
  20731. if (renderPassName === passName) {
  20732. return this._renderPasses[passName];
  20733. }
  20734. }
  20735. };
  20736. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20737. this._renderPasses = {};
  20738. this._linkParameters();
  20739. };
  20740. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20741. var cameraKey;
  20742. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20743. for (var i = 0; i < _cam.length; i++) {
  20744. var camera = _cam[i];
  20745. var cameraName = camera.name;
  20746. if (this._singleInstance) {
  20747. cameraKey = 0;
  20748. } else {
  20749. cameraKey = cameraName;
  20750. }
  20751. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20752. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20753. if (!this._indicesForCamera[cameraName]) {
  20754. this._indicesForCamera[cameraName] = [];
  20755. }
  20756. this._indicesForCamera[cameraName].push(index);
  20757. if (this._cameras.indexOf(camera) === -1) {
  20758. this._cameras[cameraName] = camera;
  20759. }
  20760. for (var passName in this._renderPasses) {
  20761. this._renderPasses[passName]._incRefCount();
  20762. }
  20763. }
  20764. this._linkParameters();
  20765. };
  20766. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20767. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20768. for (var i = 0; i < _cam.length; i++) {
  20769. var camera = _cam[i];
  20770. var cameraName = camera.name;
  20771. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20772. var index = this._cameras.indexOf(cameraName);
  20773. this._indicesForCamera.splice(index, 1);
  20774. this._cameras.splice(index, 1);
  20775. for (var passName in this._renderPasses) {
  20776. this._renderPasses[passName]._decRefCount();
  20777. }
  20778. }
  20779. };
  20780. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20781. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20782. for (var i = 0; i < _cam.length; i++) {
  20783. var camera = _cam[i];
  20784. var cameraName = camera.name;
  20785. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20786. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20787. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20788. }
  20789. }
  20790. for (var passName in this._renderPasses) {
  20791. this._renderPasses[passName]._incRefCount();
  20792. }
  20793. }
  20794. };
  20795. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20796. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20797. for (var i = 0; i < _cam.length; i++) {
  20798. var camera = _cam[i];
  20799. var cameraName = camera.Name;
  20800. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20801. for (var passName in this._renderPasses) {
  20802. this._renderPasses[passName]._decRefCount();
  20803. }
  20804. }
  20805. };
  20806. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20807. if (this._singleInstance) {
  20808. return this._postProcesses[0];
  20809. } else {
  20810. return this._postProcesses[camera.name];
  20811. }
  20812. };
  20813. PostProcessRenderEffect.prototype._linkParameters = function () {
  20814. var _this = this;
  20815. for (var index in this._postProcesses) {
  20816. if (this.applyParameters) {
  20817. this.applyParameters(this._postProcesses[index]);
  20818. }
  20819. this._postProcesses[index].onBeforeRender = function (effect) {
  20820. _this._linkTextures(effect);
  20821. };
  20822. }
  20823. };
  20824. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  20825. for (var renderPassName in this._renderPasses) {
  20826. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  20827. }
  20828. for (var renderEffectName in this._renderEffectAsPasses) {
  20829. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  20830. }
  20831. };
  20832. return PostProcessRenderEffect;
  20833. })();
  20834. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  20835. })(BABYLON || (BABYLON = {}));
  20836. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  20837. var BABYLON;
  20838. (function (BABYLON) {
  20839. var PostProcessRenderPipeline = (function () {
  20840. function PostProcessRenderPipeline(engine, name) {
  20841. this._engine = engine;
  20842. this._name = name;
  20843. this._renderEffects = {};
  20844. this._renderEffectsForIsolatedPass = {};
  20845. this._cameras = [];
  20846. }
  20847. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  20848. this._renderEffects[renderEffect._name] = renderEffect;
  20849. };
  20850. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  20851. var renderEffects = this._renderEffects[renderEffectName];
  20852. if (!renderEffects) {
  20853. return;
  20854. }
  20855. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20856. };
  20857. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  20858. var renderEffects = this._renderEffects[renderEffectName];
  20859. if (!renderEffects) {
  20860. return;
  20861. }
  20862. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20863. };
  20864. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  20865. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20866. var indicesToDelete = [];
  20867. for (var i = 0; i < _cam.length; i++) {
  20868. var camera = _cam[i];
  20869. var cameraName = camera.name;
  20870. if (this._cameras.indexOf(camera) === -1) {
  20871. this._cameras[cameraName] = camera;
  20872. } else if (unique) {
  20873. indicesToDelete.push(i);
  20874. }
  20875. }
  20876. for (var i = 0; i < indicesToDelete.length; i++) {
  20877. cameras.splice(indicesToDelete[i], 1);
  20878. }
  20879. for (var renderEffectName in this._renderEffects) {
  20880. this._renderEffects[renderEffectName]._attachCameras(_cam);
  20881. }
  20882. };
  20883. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  20884. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20885. for (var renderEffectName in this._renderEffects) {
  20886. this._renderEffects[renderEffectName]._detachCameras(_cam);
  20887. }
  20888. for (var i = 0; i < _cam.length; i++) {
  20889. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  20890. }
  20891. };
  20892. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  20893. var _this = this;
  20894. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20895. var pass = null;
  20896. for (var renderEffectName in this._renderEffects) {
  20897. pass = this._renderEffects[renderEffectName].getPass(passName);
  20898. if (pass != null) {
  20899. break;
  20900. }
  20901. }
  20902. if (pass === null) {
  20903. return;
  20904. }
  20905. for (var renderEffectName in this._renderEffects) {
  20906. this._renderEffects[renderEffectName]._disable(_cam);
  20907. }
  20908. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  20909. for (var i = 0; i < _cam.length; i++) {
  20910. var camera = _cam[i];
  20911. var cameraName = camera.name;
  20912. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20913. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20914. });
  20915. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  20916. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  20917. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  20918. }
  20919. };
  20920. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  20921. var _this = this;
  20922. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20923. for (var i = 0; i < _cam.length; i++) {
  20924. var camera = _cam[i];
  20925. var cameraName = camera.name;
  20926. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20927. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20928. });
  20929. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  20930. }
  20931. for (var renderEffectName in this._renderEffects) {
  20932. this._renderEffects[renderEffectName]._enable(_cam);
  20933. }
  20934. };
  20935. PostProcessRenderPipeline.prototype._update = function () {
  20936. for (var renderEffectName in this._renderEffects) {
  20937. this._renderEffects[renderEffectName]._update();
  20938. }
  20939. for (var i = 0; i < this._cameras.length; i++) {
  20940. var cameraName = this._cameras[i].name;
  20941. if (this._renderEffectsForIsolatedPass[cameraName]) {
  20942. this._renderEffectsForIsolatedPass[cameraName]._update();
  20943. }
  20944. }
  20945. };
  20946. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  20947. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  20948. return PostProcessRenderPipeline;
  20949. })();
  20950. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  20951. })(BABYLON || (BABYLON = {}));
  20952. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  20953. var BABYLON;
  20954. (function (BABYLON) {
  20955. var PostProcessRenderPipelineManager = (function () {
  20956. function PostProcessRenderPipelineManager() {
  20957. this._renderPipelines = {};
  20958. }
  20959. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  20960. this._renderPipelines[renderPipeline._name] = renderPipeline;
  20961. };
  20962. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  20963. var renderPipeline = this._renderPipelines[renderPipelineName];
  20964. if (!renderPipeline) {
  20965. return;
  20966. }
  20967. renderPipeline._attachCameras(cameras, unique);
  20968. };
  20969. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  20970. var renderPipeline = this._renderPipelines[renderPipelineName];
  20971. if (!renderPipeline) {
  20972. return;
  20973. }
  20974. renderPipeline._detachCameras(cameras);
  20975. };
  20976. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20977. var renderPipeline = this._renderPipelines[renderPipelineName];
  20978. if (!renderPipeline) {
  20979. return;
  20980. }
  20981. renderPipeline._enableEffect(renderEffectName, cameras);
  20982. };
  20983. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20984. var renderPipeline = this._renderPipelines[renderPipelineName];
  20985. if (!renderPipeline) {
  20986. return;
  20987. }
  20988. renderPipeline._disableEffect(renderEffectName, cameras);
  20989. };
  20990. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  20991. var renderPipeline = this._renderPipelines[renderPipelineName];
  20992. if (!renderPipeline) {
  20993. return;
  20994. }
  20995. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  20996. };
  20997. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  20998. var renderPipeline = this._renderPipelines[renderPipelineName];
  20999. if (!renderPipeline) {
  21000. return;
  21001. }
  21002. renderPipeline._disableDisplayOnlyPass(cameras);
  21003. };
  21004. PostProcessRenderPipelineManager.prototype.update = function () {
  21005. for (var renderPipelineName in this._renderPipelines) {
  21006. this._renderPipelines[renderPipelineName]._update();
  21007. }
  21008. };
  21009. return PostProcessRenderPipelineManager;
  21010. })();
  21011. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21012. })(BABYLON || (BABYLON = {}));
  21013. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21014. var BABYLON;
  21015. (function (BABYLON) {
  21016. var DisplayPassPostProcess = (function (_super) {
  21017. __extends(DisplayPassPostProcess, _super);
  21018. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21019. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21020. }
  21021. return DisplayPassPostProcess;
  21022. })(BABYLON.PostProcess);
  21023. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21024. })(BABYLON || (BABYLON = {}));
  21025. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  21026. var BABYLON;
  21027. (function (BABYLON) {
  21028. var BoundingBoxRenderer = (function () {
  21029. function BoundingBoxRenderer(scene) {
  21030. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21031. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21032. this.showBackLines = true;
  21033. this.renderList = new BABYLON.SmartArray(32);
  21034. this._scene = scene;
  21035. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21036. attributes: ["position"],
  21037. uniforms: ["worldViewProjection", "color"]
  21038. });
  21039. var engine = this._scene.getEngine();
  21040. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21041. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21042. 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]);
  21043. }
  21044. BoundingBoxRenderer.prototype.reset = function () {
  21045. this.renderList.reset();
  21046. };
  21047. BoundingBoxRenderer.prototype.render = function () {
  21048. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21049. return;
  21050. }
  21051. var engine = this._scene.getEngine();
  21052. engine.setDepthWrite(false);
  21053. this._colorShader._preBind();
  21054. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21055. var boundingBox = this.renderList.data[boundingBoxIndex];
  21056. var min = boundingBox.minimum;
  21057. var max = boundingBox.maximum;
  21058. var diff = max.subtract(min);
  21059. var median = min.add(diff.scale(0.5));
  21060. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21061. // VBOs
  21062. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21063. if (this.showBackLines) {
  21064. // Back
  21065. engine.setDepthFunctionToGreaterOrEqual();
  21066. this._scene.resetCachedMaterial();
  21067. this._colorShader.setColor4("color", this.backColor.toColor4());
  21068. this._colorShader.bind(worldMatrix);
  21069. // Draw order
  21070. engine.draw(false, 0, 24);
  21071. }
  21072. // Front
  21073. engine.setDepthFunctionToLess();
  21074. this._scene.resetCachedMaterial();
  21075. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21076. this._colorShader.bind(worldMatrix);
  21077. // Draw order
  21078. engine.draw(false, 0, 24);
  21079. }
  21080. this._colorShader.unbind();
  21081. engine.setDepthFunctionToLessOrEqual();
  21082. engine.setDepthWrite(true);
  21083. };
  21084. BoundingBoxRenderer.prototype.dispose = function () {
  21085. this._colorShader.dispose();
  21086. this._vb.dispose();
  21087. this._scene.getEngine()._releaseBuffer(this._ib);
  21088. };
  21089. return BoundingBoxRenderer;
  21090. })();
  21091. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21092. })(BABYLON || (BABYLON = {}));
  21093. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  21094. /**
  21095. * Based on jsTGALoader - Javascript loader for TGA file
  21096. * By Vincent Thibault
  21097. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21098. */
  21099. var BABYLON;
  21100. (function (BABYLON) {
  21101. (function (Internals) {
  21102. var TGATools = (function () {
  21103. function TGATools() {
  21104. }
  21105. TGATools.GetTGAHeader = function (data) {
  21106. var offset = 0;
  21107. var header = {
  21108. id_length: data[offset++],
  21109. colormap_type: data[offset++],
  21110. image_type: data[offset++],
  21111. colormap_index: data[offset++] | data[offset++] << 8,
  21112. colormap_length: data[offset++] | data[offset++] << 8,
  21113. colormap_size: data[offset++],
  21114. origin: [
  21115. data[offset++] | data[offset++] << 8,
  21116. data[offset++] | data[offset++] << 8
  21117. ],
  21118. width: data[offset++] | data[offset++] << 8,
  21119. height: data[offset++] | data[offset++] << 8,
  21120. pixel_size: data[offset++],
  21121. flags: data[offset++]
  21122. };
  21123. return header;
  21124. };
  21125. TGATools.UploadContent = function (gl, data) {
  21126. // Not enough data to contain header ?
  21127. if (data.length < 19) {
  21128. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  21129. return;
  21130. }
  21131. // Read Header
  21132. var offset = 18;
  21133. var header = TGATools.GetTGAHeader(data);
  21134. // Assume it's a valid Targa file.
  21135. if (header.id_length + offset > data.length) {
  21136. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  21137. return;
  21138. }
  21139. // Skip not needed data
  21140. offset += header.id_length;
  21141. var use_rle = false;
  21142. var use_pal = false;
  21143. var use_rgb = false;
  21144. var use_grey = false;
  21145. switch (header.image_type) {
  21146. case TGATools._TYPE_RLE_INDEXED:
  21147. use_rle = true;
  21148. case TGATools._TYPE_INDEXED:
  21149. use_pal = true;
  21150. break;
  21151. case TGATools._TYPE_RLE_RGB:
  21152. use_rle = true;
  21153. case TGATools._TYPE_RGB:
  21154. use_rgb = true;
  21155. break;
  21156. case TGATools._TYPE_RLE_GREY:
  21157. use_rle = true;
  21158. case TGATools._TYPE_GREY:
  21159. use_grey = true;
  21160. break;
  21161. }
  21162. var pixel_data;
  21163. var numAlphaBits = header.flags & 0xf;
  21164. var pixel_size = header.pixel_size >> 3;
  21165. var pixel_total = header.width * header.height * pixel_size;
  21166. // Read palettes
  21167. var palettes;
  21168. if (use_pal) {
  21169. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  21170. }
  21171. // Read LRE
  21172. if (use_rle) {
  21173. pixel_data = new Uint8Array(pixel_total);
  21174. var c, count, i;
  21175. var localOffset = 0;
  21176. var pixels = new Uint8Array(pixel_size);
  21177. while (offset < pixel_total && localOffset < pixel_total) {
  21178. c = data[offset++];
  21179. count = (c & 0x7f) + 1;
  21180. // RLE pixels
  21181. if (c & 0x80) {
  21182. for (i = 0; i < pixel_size; ++i) {
  21183. pixels[i] = data[offset++];
  21184. }
  21185. for (i = 0; i < count; ++i) {
  21186. pixel_data.set(pixels, localOffset + i * pixel_size);
  21187. }
  21188. localOffset += pixel_size * count;
  21189. } else {
  21190. count *= pixel_size;
  21191. for (i = 0; i < count; ++i) {
  21192. pixel_data[localOffset + i] = data[offset++];
  21193. }
  21194. localOffset += count;
  21195. }
  21196. }
  21197. } else {
  21198. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  21199. }
  21200. // Load to texture
  21201. var x_start, y_start, x_step, y_step, y_end, x_end;
  21202. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  21203. default:
  21204. case TGATools._ORIGIN_UL:
  21205. x_start = 0;
  21206. x_step = 1;
  21207. x_end = header.width;
  21208. y_start = 0;
  21209. y_step = 1;
  21210. y_end = header.height;
  21211. break;
  21212. case TGATools._ORIGIN_BL:
  21213. x_start = 0;
  21214. x_step = 1;
  21215. x_end = header.width;
  21216. y_start = header.height - 1;
  21217. y_step = -1;
  21218. y_end = -1;
  21219. break;
  21220. case TGATools._ORIGIN_UR:
  21221. x_start = header.width - 1;
  21222. x_step = -1;
  21223. x_end = -1;
  21224. y_start = 0;
  21225. y_step = 1;
  21226. y_end = header.height;
  21227. break;
  21228. case TGATools._ORIGIN_BR:
  21229. x_start = header.width - 1;
  21230. x_step = -1;
  21231. x_end = -1;
  21232. y_start = header.height - 1;
  21233. y_step = -1;
  21234. y_end = -1;
  21235. break;
  21236. }
  21237. // Load the specify method
  21238. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  21239. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  21240. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  21241. };
  21242. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21243. var image = pixel_data, colormap = palettes;
  21244. var width = header.width, height = header.height;
  21245. var color, i = 0, x, y;
  21246. var imageData = new Uint8Array(width * height * 4);
  21247. for (y = y_start; y !== y_end; y += y_step) {
  21248. for (x = x_start; x !== x_end; x += x_step, i++) {
  21249. color = image[i];
  21250. imageData[(x + width * y) * 4 + 3] = 255;
  21251. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21252. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21253. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21254. }
  21255. }
  21256. return imageData;
  21257. };
  21258. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21259. var image = pixel_data;
  21260. var width = header.width, height = header.height;
  21261. var color, i = 0, x, y;
  21262. var imageData = new Uint8Array(width * height * 4);
  21263. for (y = y_start; y !== y_end; y += y_step) {
  21264. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21265. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21266. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21267. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21268. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21269. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21270. }
  21271. }
  21272. return imageData;
  21273. };
  21274. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21275. var image = pixel_data;
  21276. var width = header.width, height = header.height;
  21277. var i = 0, x, y;
  21278. var imageData = new Uint8Array(width * height * 4);
  21279. for (y = y_start; y !== y_end; y += y_step) {
  21280. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21281. imageData[(x + width * y) * 4 + 3] = 255;
  21282. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21283. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21284. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21285. }
  21286. }
  21287. return imageData;
  21288. };
  21289. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21290. var image = pixel_data;
  21291. var width = header.width, height = header.height;
  21292. var i = 0, x, y;
  21293. var imageData = new Uint8Array(width * height * 4);
  21294. for (y = y_start; y !== y_end; y += y_step) {
  21295. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21296. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21297. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21298. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21299. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21300. }
  21301. }
  21302. return imageData;
  21303. };
  21304. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21305. var image = pixel_data;
  21306. var width = header.width, height = header.height;
  21307. var color, i = 0, x, y;
  21308. var imageData = new Uint8Array(width * height * 4);
  21309. for (y = y_start; y !== y_end; y += y_step) {
  21310. for (x = x_start; x !== x_end; x += x_step, i++) {
  21311. color = image[i];
  21312. imageData[(x + width * y) * 4 + 0] = color;
  21313. imageData[(x + width * y) * 4 + 1] = color;
  21314. imageData[(x + width * y) * 4 + 2] = color;
  21315. imageData[(x + width * y) * 4 + 3] = 255;
  21316. }
  21317. }
  21318. return imageData;
  21319. };
  21320. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21321. var image = pixel_data;
  21322. var width = header.width, height = header.height;
  21323. var i = 0, x, y;
  21324. var imageData = new Uint8Array(width * height * 4);
  21325. for (y = y_start; y !== y_end; y += y_step) {
  21326. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21327. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21328. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21329. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21330. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21331. }
  21332. }
  21333. return imageData;
  21334. };
  21335. TGATools._TYPE_NO_DATA = 0;
  21336. TGATools._TYPE_INDEXED = 1;
  21337. TGATools._TYPE_RGB = 2;
  21338. TGATools._TYPE_GREY = 3;
  21339. TGATools._TYPE_RLE_INDEXED = 9;
  21340. TGATools._TYPE_RLE_RGB = 10;
  21341. TGATools._TYPE_RLE_GREY = 11;
  21342. TGATools._ORIGIN_MASK = 0x30;
  21343. TGATools._ORIGIN_SHIFT = 0x04;
  21344. TGATools._ORIGIN_BL = 0x00;
  21345. TGATools._ORIGIN_BR = 0x01;
  21346. TGATools._ORIGIN_UL = 0x02;
  21347. TGATools._ORIGIN_UR = 0x03;
  21348. return TGATools;
  21349. })();
  21350. Internals.TGATools = TGATools;
  21351. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21352. var Internals = BABYLON.Internals;
  21353. })(BABYLON || (BABYLON = {}));
  21354. //# sourceMappingURL=babylon.tools.tga.js.map
  21355. var BABYLON;
  21356. (function (BABYLON) {
  21357. (function (Internals) {
  21358. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21359. // All values and structures referenced from:
  21360. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21361. var DDS_MAGIC = 0x20534444;
  21362. 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;
  21363. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21364. 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;
  21365. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21366. function FourCCToInt32(value) {
  21367. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21368. }
  21369. function Int32ToFourCC(value) {
  21370. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21371. }
  21372. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21373. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21374. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21375. var headerLengthInt = 31;
  21376. // Offsets into the header array
  21377. var off_magic = 0;
  21378. var off_size = 1;
  21379. var off_flags = 2;
  21380. var off_height = 3;
  21381. var off_width = 4;
  21382. var off_mipmapCount = 7;
  21383. var off_pfFlags = 20;
  21384. var off_pfFourCC = 21;
  21385. var off_RGBbpp = 22;
  21386. var off_RMask = 23;
  21387. var off_GMask = 24;
  21388. var off_BMask = 25;
  21389. var off_AMask = 26;
  21390. var off_caps1 = 27;
  21391. var off_caps2 = 28;
  21392. ;
  21393. var DDSTools = (function () {
  21394. function DDSTools() {
  21395. }
  21396. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21397. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21398. var mipmapCount = 1;
  21399. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21400. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21401. }
  21402. return {
  21403. width: header[off_width],
  21404. height: header[off_height],
  21405. mipmapCount: mipmapCount,
  21406. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21407. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21408. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21409. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21410. };
  21411. };
  21412. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21413. var byteArray = new Uint8Array(dataLength);
  21414. var srcData = new Uint8Array(arrayBuffer);
  21415. var index = 0;
  21416. for (var y = height - 1; y >= 0; y--) {
  21417. for (var x = 0; x < width; x++) {
  21418. var srcPos = dataOffset + (x + y * width) * 4;
  21419. byteArray[index + 2] = srcData[srcPos];
  21420. byteArray[index + 1] = srcData[srcPos + 1];
  21421. byteArray[index] = srcData[srcPos + 2];
  21422. byteArray[index + 3] = srcData[srcPos + 3];
  21423. index += 4;
  21424. }
  21425. }
  21426. return byteArray;
  21427. };
  21428. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21429. var byteArray = new Uint8Array(dataLength);
  21430. var srcData = new Uint8Array(arrayBuffer);
  21431. var index = 0;
  21432. for (var y = height - 1; y >= 0; y--) {
  21433. for (var x = 0; x < width; x++) {
  21434. var srcPos = dataOffset + (x + y * width) * 3;
  21435. byteArray[index + 2] = srcData[srcPos];
  21436. byteArray[index + 1] = srcData[srcPos + 1];
  21437. byteArray[index] = srcData[srcPos + 2];
  21438. index += 3;
  21439. }
  21440. }
  21441. return byteArray;
  21442. };
  21443. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21444. var byteArray = new Uint8Array(dataLength);
  21445. var srcData = new Uint8Array(arrayBuffer);
  21446. var index = 0;
  21447. for (var y = height - 1; y >= 0; y--) {
  21448. for (var x = 0; x < width; x++) {
  21449. var srcPos = dataOffset + (x + y * width);
  21450. byteArray[index] = srcData[srcPos];
  21451. index++;
  21452. }
  21453. }
  21454. return byteArray;
  21455. };
  21456. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21457. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21458. if (header[off_magic] != DDS_MAGIC) {
  21459. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21460. return;
  21461. }
  21462. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21463. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21464. return;
  21465. }
  21466. if (info.isFourCC) {
  21467. fourCC = header[off_pfFourCC];
  21468. switch (fourCC) {
  21469. case FOURCC_DXT1:
  21470. blockBytes = 8;
  21471. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21472. break;
  21473. case FOURCC_DXT3:
  21474. blockBytes = 16;
  21475. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21476. break;
  21477. case FOURCC_DXT5:
  21478. blockBytes = 16;
  21479. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21480. break;
  21481. default:
  21482. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21483. return;
  21484. }
  21485. }
  21486. mipmapCount = 1;
  21487. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21488. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21489. }
  21490. var bpp = header[off_RGBbpp];
  21491. for (var face = 0; face < faces; face++) {
  21492. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21493. width = header[off_width];
  21494. height = header[off_height];
  21495. dataOffset = header[off_size] + 4;
  21496. for (i = 0; i < mipmapCount; ++i) {
  21497. if (info.isRGB) {
  21498. if (bpp == 24) {
  21499. dataLength = width * height * 3;
  21500. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21501. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21502. } else {
  21503. dataLength = width * height * 4;
  21504. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21505. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21506. }
  21507. } else if (info.isLuminance) {
  21508. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21509. var unpaddedRowSize = width;
  21510. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21511. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21512. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21513. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21514. } else {
  21515. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21516. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21517. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21518. }
  21519. dataOffset += dataLength;
  21520. width *= 0.5;
  21521. height *= 0.5;
  21522. width = Math.max(1.0, width);
  21523. height = Math.max(1.0, height);
  21524. }
  21525. }
  21526. };
  21527. return DDSTools;
  21528. })();
  21529. Internals.DDSTools = DDSTools;
  21530. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21531. var Internals = BABYLON.Internals;
  21532. })(BABYLON || (BABYLON = {}));
  21533. //# sourceMappingURL=babylon.tools.dds.js.map
  21534. var BABYLON;
  21535. (function (BABYLON) {
  21536. var SmartArray = (function () {
  21537. function SmartArray(capacity) {
  21538. this.length = 0;
  21539. this._duplicateId = 0;
  21540. this.data = new Array(capacity);
  21541. this._id = SmartArray._GlobalId++;
  21542. }
  21543. SmartArray.prototype.push = function (value) {
  21544. this.data[this.length++] = value;
  21545. if (this.length > this.data.length) {
  21546. this.data.length *= 2;
  21547. }
  21548. if (!value.__smartArrayFlags) {
  21549. value.__smartArrayFlags = {};
  21550. }
  21551. value.__smartArrayFlags[this._id] = this._duplicateId;
  21552. };
  21553. SmartArray.prototype.pushNoDuplicate = function (value) {
  21554. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21555. return;
  21556. }
  21557. this.push(value);
  21558. };
  21559. SmartArray.prototype.sort = function (compareFn) {
  21560. this.data.sort(compareFn);
  21561. };
  21562. SmartArray.prototype.reset = function () {
  21563. this.length = 0;
  21564. this._duplicateId++;
  21565. };
  21566. SmartArray.prototype.concat = function (array) {
  21567. if (array.length === 0) {
  21568. return;
  21569. }
  21570. if (this.length + array.length > this.data.length) {
  21571. this.data.length = (this.length + array.length) * 2;
  21572. }
  21573. for (var index = 0; index < array.length; index++) {
  21574. this.data[this.length++] = (array.data || array)[index];
  21575. }
  21576. };
  21577. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21578. if (array.length === 0) {
  21579. return;
  21580. }
  21581. if (this.length + array.length > this.data.length) {
  21582. this.data.length = (this.length + array.length) * 2;
  21583. }
  21584. for (var index = 0; index < array.length; index++) {
  21585. var item = (array.data || array)[index];
  21586. this.pushNoDuplicate(item);
  21587. }
  21588. };
  21589. SmartArray.prototype.indexOf = function (value) {
  21590. var position = this.data.indexOf(value);
  21591. if (position >= this.length) {
  21592. return -1;
  21593. }
  21594. return position;
  21595. };
  21596. SmartArray._GlobalId = 0;
  21597. return SmartArray;
  21598. })();
  21599. BABYLON.SmartArray = SmartArray;
  21600. })(BABYLON || (BABYLON = {}));
  21601. //# sourceMappingURL=babylon.smartArray.js.map
  21602. var BABYLON;
  21603. (function (BABYLON) {
  21604. var CannonJSPlugin = (function () {
  21605. function CannonJSPlugin() {
  21606. this._registeredMeshes = [];
  21607. this._physicsMaterials = [];
  21608. this.updateBodyPosition = function (mesh) {
  21609. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21610. var registeredMesh = this._registeredMeshes[index];
  21611. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21612. var body = registeredMesh.body;
  21613. var center = mesh.getBoundingInfo().boundingBox.center;
  21614. body.position.set(center.x, center.z, center.y);
  21615. body.quaternion.x = mesh.rotationQuaternion.x;
  21616. body.quaternion.z = mesh.rotationQuaternion.y;
  21617. body.quaternion.y = mesh.rotationQuaternion.z;
  21618. body.quaternion.w = -mesh.rotationQuaternion.w;
  21619. return;
  21620. }
  21621. }
  21622. };
  21623. }
  21624. CannonJSPlugin.prototype.initialize = function (iterations) {
  21625. if (typeof iterations === "undefined") { iterations = 10; }
  21626. this._world = new CANNON.World();
  21627. this._world.broadphase = new CANNON.NaiveBroadphase();
  21628. this._world.solver.iterations = iterations;
  21629. };
  21630. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21631. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21632. };
  21633. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21634. this._world.step(delta);
  21635. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21636. var registeredMesh = this._registeredMeshes[index];
  21637. if (registeredMesh.isChild) {
  21638. continue;
  21639. }
  21640. // Body position
  21641. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21642. var deltaPos = registeredMesh.delta;
  21643. if (deltaPos) {
  21644. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21645. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21646. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21647. } else {
  21648. registeredMesh.mesh.position.x = bodyX;
  21649. registeredMesh.mesh.position.y = bodyZ;
  21650. registeredMesh.mesh.position.z = bodyY;
  21651. }
  21652. if (!registeredMesh.mesh.rotationQuaternion) {
  21653. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21654. }
  21655. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21656. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21657. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21658. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21659. }
  21660. };
  21661. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21662. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21663. };
  21664. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21665. this.unregisterMesh(mesh);
  21666. mesh.computeWorldMatrix(true);
  21667. switch (impostor) {
  21668. case BABYLON.PhysicsEngine.SphereImpostor:
  21669. var bbox = mesh.getBoundingInfo().boundingBox;
  21670. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21671. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21672. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21673. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21674. case BABYLON.PhysicsEngine.BoxImpostor:
  21675. bbox = mesh.getBoundingInfo().boundingBox;
  21676. var min = bbox.minimumWorld;
  21677. var max = bbox.maximumWorld;
  21678. var box = max.subtract(min).scale(0.5);
  21679. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21680. case BABYLON.PhysicsEngine.PlaneImpostor:
  21681. return this._createPlane(mesh, options);
  21682. case BABYLON.PhysicsEngine.MeshImpostor:
  21683. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21684. var rawFaces = mesh.getIndices();
  21685. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21686. }
  21687. return null;
  21688. };
  21689. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21690. var shape = new CANNON.Sphere(radius);
  21691. if (!options) {
  21692. return shape;
  21693. }
  21694. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21695. };
  21696. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21697. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21698. if (!options) {
  21699. return shape;
  21700. }
  21701. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21702. };
  21703. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21704. var shape = new CANNON.Plane();
  21705. if (!options) {
  21706. return shape;
  21707. }
  21708. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21709. };
  21710. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21711. var verts = [], faces = [];
  21712. mesh.computeWorldMatrix(true);
  21713. for (var i = 0; i < rawVerts.length; i += 3) {
  21714. var transformed = BABYLON.Vector3.Zero();
  21715. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21716. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21717. }
  21718. for (var j = 0; j < rawFaces.length; j += 3) {
  21719. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21720. }
  21721. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21722. if (!options) {
  21723. return shape;
  21724. }
  21725. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21726. };
  21727. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21728. var index;
  21729. var mat;
  21730. for (index = 0; index < this._physicsMaterials.length; index++) {
  21731. mat = this._physicsMaterials[index];
  21732. if (mat.friction === friction && mat.restitution === restitution) {
  21733. return mat;
  21734. }
  21735. }
  21736. var currentMat = new CANNON.Material();
  21737. currentMat.friction = friction;
  21738. currentMat.restitution = restitution;
  21739. this._physicsMaterials.push(currentMat);
  21740. for (index = 0; index < this._physicsMaterials.length; index++) {
  21741. mat = this._physicsMaterials[index];
  21742. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21743. contactMaterial.contactEquationStiffness = 1e10;
  21744. contactMaterial.contactEquationRegularizationTime = 10;
  21745. this._world.addContactMaterial(contactMaterial);
  21746. }
  21747. return currentMat;
  21748. };
  21749. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21750. var initialRotation = null;
  21751. if (mesh.rotationQuaternion) {
  21752. initialRotation = mesh.rotationQuaternion.clone();
  21753. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21754. }
  21755. // The delta between the mesh position and the mesh bounding box center
  21756. var bbox = mesh.getBoundingInfo().boundingBox;
  21757. var deltaPosition = mesh.position.subtract(bbox.center);
  21758. var material = this._addMaterial(friction, restitution);
  21759. var body = new CANNON.RigidBody(mass, shape, material);
  21760. if (initialRotation) {
  21761. body.quaternion.x = initialRotation.x;
  21762. body.quaternion.z = initialRotation.y;
  21763. body.quaternion.y = initialRotation.z;
  21764. body.quaternion.w = -initialRotation.w;
  21765. }
  21766. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21767. this._world.add(body);
  21768. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21769. return body;
  21770. };
  21771. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21772. var compoundShape = new CANNON.Compound();
  21773. for (var index = 0; index < parts.length; index++) {
  21774. var mesh = parts[index].mesh;
  21775. var shape = this.registerMesh(mesh, parts[index].impostor);
  21776. if (index == 0) {
  21777. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21778. } else {
  21779. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21780. }
  21781. }
  21782. var initialMesh = parts[0].mesh;
  21783. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21784. body.parts = parts;
  21785. return body;
  21786. };
  21787. CannonJSPlugin.prototype._unbindBody = function (body) {
  21788. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21789. var registeredMesh = this._registeredMeshes[index];
  21790. if (registeredMesh.body === body) {
  21791. registeredMesh.body = null;
  21792. registeredMesh.delta = 0;
  21793. }
  21794. }
  21795. };
  21796. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21797. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21798. var registeredMesh = this._registeredMeshes[index];
  21799. if (registeredMesh.mesh === mesh) {
  21800. // Remove body
  21801. if (registeredMesh.body) {
  21802. this._world.remove(registeredMesh.body);
  21803. this._unbindBody(registeredMesh.body);
  21804. }
  21805. this._registeredMeshes.splice(index, 1);
  21806. return;
  21807. }
  21808. }
  21809. };
  21810. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21811. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21812. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21813. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21814. var registeredMesh = this._registeredMeshes[index];
  21815. if (registeredMesh.mesh === mesh) {
  21816. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21817. return;
  21818. }
  21819. }
  21820. };
  21821. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21822. var body1 = null, body2 = null;
  21823. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21824. var registeredMesh = this._registeredMeshes[index];
  21825. if (registeredMesh.mesh === mesh1) {
  21826. body1 = registeredMesh.body;
  21827. } else if (registeredMesh.mesh === mesh2) {
  21828. body2 = registeredMesh.body;
  21829. }
  21830. }
  21831. if (!body1 || !body2) {
  21832. return false;
  21833. }
  21834. 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));
  21835. this._world.addConstraint(constraint);
  21836. return true;
  21837. };
  21838. CannonJSPlugin.prototype.dispose = function () {
  21839. while (this._registeredMeshes.length) {
  21840. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21841. }
  21842. };
  21843. CannonJSPlugin.prototype.isSupported = function () {
  21844. return window.CANNON !== undefined;
  21845. };
  21846. return CannonJSPlugin;
  21847. })();
  21848. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21849. })(BABYLON || (BABYLON = {}));
  21850. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21851. var BABYLON;
  21852. (function (BABYLON) {
  21853. var Condition = (function () {
  21854. function Condition(actionManager) {
  21855. this._actionManager = actionManager;
  21856. }
  21857. Condition.prototype.isValid = function () {
  21858. return true;
  21859. };
  21860. Condition.prototype._getProperty = function (propertyPath) {
  21861. return this._actionManager._getProperty(propertyPath);
  21862. };
  21863. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  21864. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21865. };
  21866. return Condition;
  21867. })();
  21868. BABYLON.Condition = Condition;
  21869. var ValueCondition = (function (_super) {
  21870. __extends(ValueCondition, _super);
  21871. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  21872. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  21873. _super.call(this, actionManager);
  21874. this.propertyPath = propertyPath;
  21875. this.value = value;
  21876. this.operator = operator;
  21877. this._target = this._getEffectiveTarget(target, this.propertyPath);
  21878. this._property = this._getProperty(this.propertyPath);
  21879. }
  21880. Object.defineProperty(ValueCondition, "IsEqual", {
  21881. get: function () {
  21882. return ValueCondition._IsEqual;
  21883. },
  21884. enumerable: true,
  21885. configurable: true
  21886. });
  21887. Object.defineProperty(ValueCondition, "IsDifferent", {
  21888. get: function () {
  21889. return ValueCondition._IsDifferent;
  21890. },
  21891. enumerable: true,
  21892. configurable: true
  21893. });
  21894. Object.defineProperty(ValueCondition, "IsGreater", {
  21895. get: function () {
  21896. return ValueCondition._IsGreater;
  21897. },
  21898. enumerable: true,
  21899. configurable: true
  21900. });
  21901. Object.defineProperty(ValueCondition, "IsLesser", {
  21902. get: function () {
  21903. return ValueCondition._IsLesser;
  21904. },
  21905. enumerable: true,
  21906. configurable: true
  21907. });
  21908. // Methods
  21909. ValueCondition.prototype.isValid = function () {
  21910. switch (this.operator) {
  21911. case ValueCondition.IsGreater:
  21912. return this._target[this._property] > this.value;
  21913. case ValueCondition.IsLesser:
  21914. return this._target[this._property] < this.value;
  21915. case ValueCondition.IsEqual:
  21916. case ValueCondition.IsDifferent:
  21917. var check;
  21918. if (this.value.equals) {
  21919. check = this.value.equals(this._target[this._property]);
  21920. } else {
  21921. check = this.value === this._target[this._property];
  21922. }
  21923. return this.operator === ValueCondition.IsEqual ? check : !check;
  21924. }
  21925. return false;
  21926. };
  21927. ValueCondition._IsEqual = 0;
  21928. ValueCondition._IsDifferent = 1;
  21929. ValueCondition._IsGreater = 2;
  21930. ValueCondition._IsLesser = 3;
  21931. return ValueCondition;
  21932. })(Condition);
  21933. BABYLON.ValueCondition = ValueCondition;
  21934. var PredicateCondition = (function (_super) {
  21935. __extends(PredicateCondition, _super);
  21936. function PredicateCondition(actionManager, predicate) {
  21937. _super.call(this, actionManager);
  21938. this.predicate = predicate;
  21939. }
  21940. PredicateCondition.prototype.isValid = function () {
  21941. return this.predicate();
  21942. };
  21943. return PredicateCondition;
  21944. })(Condition);
  21945. BABYLON.PredicateCondition = PredicateCondition;
  21946. var StateCondition = (function (_super) {
  21947. __extends(StateCondition, _super);
  21948. function StateCondition(actionManager, target, value) {
  21949. _super.call(this, actionManager);
  21950. this.value = value;
  21951. this._target = target;
  21952. }
  21953. // Methods
  21954. StateCondition.prototype.isValid = function () {
  21955. return this._target.state === this.value;
  21956. };
  21957. return StateCondition;
  21958. })(Condition);
  21959. BABYLON.StateCondition = StateCondition;
  21960. })(BABYLON || (BABYLON = {}));
  21961. //# sourceMappingURL=babylon.condition.js.map
  21962. var BABYLON;
  21963. (function (BABYLON) {
  21964. var Action = (function () {
  21965. function Action(triggerOptions, condition) {
  21966. this.triggerOptions = triggerOptions;
  21967. if (triggerOptions.parameter) {
  21968. this.trigger = triggerOptions.trigger;
  21969. this._triggerParameter = triggerOptions.parameter;
  21970. } else {
  21971. this.trigger = triggerOptions;
  21972. }
  21973. this._nextActiveAction = this;
  21974. this._condition = condition;
  21975. }
  21976. // Methods
  21977. Action.prototype._prepare = function () {
  21978. };
  21979. Action.prototype.getTriggerParameter = function () {
  21980. return this._triggerParameter;
  21981. };
  21982. Action.prototype._executeCurrent = function (evt) {
  21983. if (this._condition) {
  21984. var currentRenderId = this._actionManager.getScene().getRenderId();
  21985. // We cache the current evaluation for the current frame
  21986. if (this._condition._evaluationId === currentRenderId) {
  21987. if (!this._condition._currentResult) {
  21988. return;
  21989. }
  21990. } else {
  21991. this._condition._evaluationId = currentRenderId;
  21992. if (!this._condition.isValid()) {
  21993. this._condition._currentResult = false;
  21994. return;
  21995. }
  21996. this._condition._currentResult = true;
  21997. }
  21998. }
  21999. this._nextActiveAction.execute(evt);
  22000. if (this._nextActiveAction._child) {
  22001. if (!this._nextActiveAction._child._actionManager) {
  22002. this._nextActiveAction._child._actionManager = this._actionManager;
  22003. }
  22004. this._nextActiveAction = this._nextActiveAction._child;
  22005. } else {
  22006. this._nextActiveAction = this;
  22007. }
  22008. };
  22009. Action.prototype.execute = function (evt) {
  22010. };
  22011. Action.prototype.then = function (action) {
  22012. this._child = action;
  22013. action._actionManager = this._actionManager;
  22014. action._prepare();
  22015. return action;
  22016. };
  22017. Action.prototype._getProperty = function (propertyPath) {
  22018. return this._actionManager._getProperty(propertyPath);
  22019. };
  22020. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22021. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22022. };
  22023. return Action;
  22024. })();
  22025. BABYLON.Action = Action;
  22026. })(BABYLON || (BABYLON = {}));
  22027. //# sourceMappingURL=babylon.action.js.map
  22028. var BABYLON;
  22029. (function (BABYLON) {
  22030. var ActionEvent = (function () {
  22031. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22032. this.source = source;
  22033. this.pointerX = pointerX;
  22034. this.pointerY = pointerY;
  22035. this.meshUnderPointer = meshUnderPointer;
  22036. this.sourceEvent = sourceEvent;
  22037. }
  22038. ActionEvent.CreateNew = function (source, evt) {
  22039. var scene = source.getScene();
  22040. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22041. };
  22042. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22043. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22044. };
  22045. return ActionEvent;
  22046. })();
  22047. BABYLON.ActionEvent = ActionEvent;
  22048. var ActionManager = (function () {
  22049. function ActionManager(scene) {
  22050. // Members
  22051. this.actions = new Array();
  22052. this._scene = scene;
  22053. scene._actionManagers.push(this);
  22054. }
  22055. Object.defineProperty(ActionManager, "NothingTrigger", {
  22056. get: function () {
  22057. return ActionManager._NothingTrigger;
  22058. },
  22059. enumerable: true,
  22060. configurable: true
  22061. });
  22062. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22063. get: function () {
  22064. return ActionManager._OnPickTrigger;
  22065. },
  22066. enumerable: true,
  22067. configurable: true
  22068. });
  22069. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22070. get: function () {
  22071. return ActionManager._OnLeftPickTrigger;
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22077. get: function () {
  22078. return ActionManager._OnRightPickTrigger;
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  22084. get: function () {
  22085. return ActionManager._OnCenterPickTrigger;
  22086. },
  22087. enumerable: true,
  22088. configurable: true
  22089. });
  22090. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  22091. get: function () {
  22092. return ActionManager._OnPointerOverTrigger;
  22093. },
  22094. enumerable: true,
  22095. configurable: true
  22096. });
  22097. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  22098. get: function () {
  22099. return ActionManager._OnPointerOutTrigger;
  22100. },
  22101. enumerable: true,
  22102. configurable: true
  22103. });
  22104. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  22105. get: function () {
  22106. return ActionManager._OnEveryFrameTrigger;
  22107. },
  22108. enumerable: true,
  22109. configurable: true
  22110. });
  22111. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  22112. get: function () {
  22113. return ActionManager._OnIntersectionEnterTrigger;
  22114. },
  22115. enumerable: true,
  22116. configurable: true
  22117. });
  22118. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  22119. get: function () {
  22120. return ActionManager._OnIntersectionExitTrigger;
  22121. },
  22122. enumerable: true,
  22123. configurable: true
  22124. });
  22125. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  22126. get: function () {
  22127. return ActionManager._OnKeyDownTrigger;
  22128. },
  22129. enumerable: true,
  22130. configurable: true
  22131. });
  22132. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  22133. get: function () {
  22134. return ActionManager._OnKeyUpTrigger;
  22135. },
  22136. enumerable: true,
  22137. configurable: true
  22138. });
  22139. // Methods
  22140. ActionManager.prototype.dispose = function () {
  22141. var index = this._scene._actionManagers.indexOf(this);
  22142. if (index > -1) {
  22143. this._scene._actionManagers.splice(index, 1);
  22144. }
  22145. };
  22146. ActionManager.prototype.getScene = function () {
  22147. return this._scene;
  22148. };
  22149. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  22150. for (var index = 0; index < this.actions.length; index++) {
  22151. var action = this.actions[index];
  22152. if (triggers.indexOf(action.trigger) > -1) {
  22153. return true;
  22154. }
  22155. }
  22156. return false;
  22157. };
  22158. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  22159. get: function () {
  22160. for (var index = 0; index < this.actions.length; index++) {
  22161. var action = this.actions[index];
  22162. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  22163. return true;
  22164. }
  22165. }
  22166. return false;
  22167. },
  22168. enumerable: true,
  22169. configurable: true
  22170. });
  22171. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  22172. get: function () {
  22173. for (var index = 0; index < this.actions.length; index++) {
  22174. var action = this.actions[index];
  22175. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  22176. return true;
  22177. }
  22178. }
  22179. return false;
  22180. },
  22181. enumerable: true,
  22182. configurable: true
  22183. });
  22184. ActionManager.prototype.registerAction = function (action) {
  22185. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  22186. if (this.getScene().actionManager !== this) {
  22187. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  22188. return null;
  22189. }
  22190. }
  22191. this.actions.push(action);
  22192. action._actionManager = this;
  22193. action._prepare();
  22194. return action;
  22195. };
  22196. ActionManager.prototype.processTrigger = function (trigger, evt) {
  22197. for (var index = 0; index < this.actions.length; index++) {
  22198. var action = this.actions[index];
  22199. if (action.trigger === trigger) {
  22200. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  22201. var parameter = action.getTriggerParameter();
  22202. if (parameter) {
  22203. if (evt.sourceEvent.key !== parameter) {
  22204. continue;
  22205. }
  22206. }
  22207. }
  22208. action._executeCurrent(evt);
  22209. }
  22210. }
  22211. };
  22212. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  22213. var properties = propertyPath.split(".");
  22214. for (var index = 0; index < properties.length - 1; index++) {
  22215. target = target[properties[index]];
  22216. }
  22217. return target;
  22218. };
  22219. ActionManager.prototype._getProperty = function (propertyPath) {
  22220. var properties = propertyPath.split(".");
  22221. return properties[properties.length - 1];
  22222. };
  22223. ActionManager._NothingTrigger = 0;
  22224. ActionManager._OnPickTrigger = 1;
  22225. ActionManager._OnLeftPickTrigger = 2;
  22226. ActionManager._OnRightPickTrigger = 3;
  22227. ActionManager._OnCenterPickTrigger = 4;
  22228. ActionManager._OnPointerOverTrigger = 5;
  22229. ActionManager._OnPointerOutTrigger = 6;
  22230. ActionManager._OnEveryFrameTrigger = 7;
  22231. ActionManager._OnIntersectionEnterTrigger = 8;
  22232. ActionManager._OnIntersectionExitTrigger = 9;
  22233. ActionManager._OnKeyDownTrigger = 10;
  22234. ActionManager._OnKeyUpTrigger = 11;
  22235. return ActionManager;
  22236. })();
  22237. BABYLON.ActionManager = ActionManager;
  22238. })(BABYLON || (BABYLON = {}));
  22239. //# sourceMappingURL=babylon.actionManager.js.map
  22240. var BABYLON;
  22241. (function (BABYLON) {
  22242. var InterpolateValueAction = (function (_super) {
  22243. __extends(InterpolateValueAction, _super);
  22244. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22245. if (typeof duration === "undefined") { duration = 1000; }
  22246. _super.call(this, triggerOptions, condition);
  22247. this.propertyPath = propertyPath;
  22248. this.value = value;
  22249. this.duration = duration;
  22250. this.stopOtherAnimations = stopOtherAnimations;
  22251. this._target = target;
  22252. }
  22253. InterpolateValueAction.prototype._prepare = function () {
  22254. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22255. this._property = this._getProperty(this.propertyPath);
  22256. };
  22257. InterpolateValueAction.prototype.execute = function () {
  22258. var scene = this._actionManager.getScene();
  22259. var keys = [
  22260. {
  22261. frame: 0,
  22262. value: this._target[this._property]
  22263. }, {
  22264. frame: 100,
  22265. value: this.value
  22266. }
  22267. ];
  22268. var dataType;
  22269. if (typeof this.value === "number") {
  22270. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22271. } else if (this.value instanceof BABYLON.Color3) {
  22272. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22273. } else if (this.value instanceof BABYLON.Vector3) {
  22274. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22275. } else if (this.value instanceof BABYLON.Matrix) {
  22276. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22277. } else if (this.value instanceof BABYLON.Quaternion) {
  22278. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22279. } else {
  22280. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22281. return;
  22282. }
  22283. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22284. animation.setKeys(keys);
  22285. if (this.stopOtherAnimations) {
  22286. scene.stopAnimation(this._target);
  22287. }
  22288. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22289. };
  22290. return InterpolateValueAction;
  22291. })(BABYLON.Action);
  22292. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22293. })(BABYLON || (BABYLON = {}));
  22294. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22295. var BABYLON;
  22296. (function (BABYLON) {
  22297. var SwitchBooleanAction = (function (_super) {
  22298. __extends(SwitchBooleanAction, _super);
  22299. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22300. _super.call(this, triggerOptions, condition);
  22301. this.propertyPath = propertyPath;
  22302. this._target = target;
  22303. }
  22304. SwitchBooleanAction.prototype._prepare = function () {
  22305. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22306. this._property = this._getProperty(this.propertyPath);
  22307. };
  22308. SwitchBooleanAction.prototype.execute = function () {
  22309. this._target[this._property] = !this._target[this._property];
  22310. };
  22311. return SwitchBooleanAction;
  22312. })(BABYLON.Action);
  22313. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22314. var SetStateAction = (function (_super) {
  22315. __extends(SetStateAction, _super);
  22316. function SetStateAction(triggerOptions, target, value, condition) {
  22317. _super.call(this, triggerOptions, condition);
  22318. this.value = value;
  22319. this._target = target;
  22320. }
  22321. SetStateAction.prototype.execute = function () {
  22322. this._target.state = this.value;
  22323. };
  22324. return SetStateAction;
  22325. })(BABYLON.Action);
  22326. BABYLON.SetStateAction = SetStateAction;
  22327. var SetValueAction = (function (_super) {
  22328. __extends(SetValueAction, _super);
  22329. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22330. _super.call(this, triggerOptions, condition);
  22331. this.propertyPath = propertyPath;
  22332. this.value = value;
  22333. this._target = target;
  22334. }
  22335. SetValueAction.prototype._prepare = function () {
  22336. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22337. this._property = this._getProperty(this.propertyPath);
  22338. };
  22339. SetValueAction.prototype.execute = function () {
  22340. this._target[this._property] = this.value;
  22341. };
  22342. return SetValueAction;
  22343. })(BABYLON.Action);
  22344. BABYLON.SetValueAction = SetValueAction;
  22345. var IncrementValueAction = (function (_super) {
  22346. __extends(IncrementValueAction, _super);
  22347. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22348. _super.call(this, triggerOptions, condition);
  22349. this.propertyPath = propertyPath;
  22350. this.value = value;
  22351. this._target = target;
  22352. }
  22353. IncrementValueAction.prototype._prepare = function () {
  22354. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22355. this._property = this._getProperty(this.propertyPath);
  22356. if (typeof this._target[this._property] !== "number") {
  22357. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22358. }
  22359. };
  22360. IncrementValueAction.prototype.execute = function () {
  22361. this._target[this._property] += this.value;
  22362. };
  22363. return IncrementValueAction;
  22364. })(BABYLON.Action);
  22365. BABYLON.IncrementValueAction = IncrementValueAction;
  22366. var PlayAnimationAction = (function (_super) {
  22367. __extends(PlayAnimationAction, _super);
  22368. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22369. _super.call(this, triggerOptions, condition);
  22370. this.from = from;
  22371. this.to = to;
  22372. this.loop = loop;
  22373. this._target = target;
  22374. }
  22375. PlayAnimationAction.prototype._prepare = function () {
  22376. };
  22377. PlayAnimationAction.prototype.execute = function () {
  22378. var scene = this._actionManager.getScene();
  22379. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22380. };
  22381. return PlayAnimationAction;
  22382. })(BABYLON.Action);
  22383. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22384. var StopAnimationAction = (function (_super) {
  22385. __extends(StopAnimationAction, _super);
  22386. function StopAnimationAction(triggerOptions, target, condition) {
  22387. _super.call(this, triggerOptions, condition);
  22388. this._target = target;
  22389. }
  22390. StopAnimationAction.prototype._prepare = function () {
  22391. };
  22392. StopAnimationAction.prototype.execute = function () {
  22393. var scene = this._actionManager.getScene();
  22394. scene.stopAnimation(this._target);
  22395. };
  22396. return StopAnimationAction;
  22397. })(BABYLON.Action);
  22398. BABYLON.StopAnimationAction = StopAnimationAction;
  22399. var DoNothingAction = (function (_super) {
  22400. __extends(DoNothingAction, _super);
  22401. function DoNothingAction(triggerOptions, condition) {
  22402. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22403. _super.call(this, triggerOptions, condition);
  22404. }
  22405. DoNothingAction.prototype.execute = function () {
  22406. };
  22407. return DoNothingAction;
  22408. })(BABYLON.Action);
  22409. BABYLON.DoNothingAction = DoNothingAction;
  22410. var CombineAction = (function (_super) {
  22411. __extends(CombineAction, _super);
  22412. function CombineAction(triggerOptions, children, condition) {
  22413. _super.call(this, triggerOptions, condition);
  22414. this.children = children;
  22415. }
  22416. CombineAction.prototype._prepare = function () {
  22417. for (var index = 0; index < this.children.length; index++) {
  22418. this.children[index]._actionManager = this._actionManager;
  22419. this.children[index]._prepare();
  22420. }
  22421. };
  22422. CombineAction.prototype.execute = function (evt) {
  22423. for (var index = 0; index < this.children.length; index++) {
  22424. this.children[index].execute(evt);
  22425. }
  22426. };
  22427. return CombineAction;
  22428. })(BABYLON.Action);
  22429. BABYLON.CombineAction = CombineAction;
  22430. var ExecuteCodeAction = (function (_super) {
  22431. __extends(ExecuteCodeAction, _super);
  22432. function ExecuteCodeAction(triggerOptions, func, condition) {
  22433. _super.call(this, triggerOptions, condition);
  22434. this.func = func;
  22435. }
  22436. ExecuteCodeAction.prototype.execute = function (evt) {
  22437. this.func(evt);
  22438. };
  22439. return ExecuteCodeAction;
  22440. })(BABYLON.Action);
  22441. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22442. var SetParentAction = (function (_super) {
  22443. __extends(SetParentAction, _super);
  22444. function SetParentAction(triggerOptions, target, parent, condition) {
  22445. _super.call(this, triggerOptions, condition);
  22446. this._target = target;
  22447. this._parent = parent;
  22448. }
  22449. SetParentAction.prototype._prepare = function () {
  22450. };
  22451. SetParentAction.prototype.execute = function () {
  22452. if (this._target.parent === this._parent) {
  22453. return;
  22454. }
  22455. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22456. invertParentWorldMatrix.invert();
  22457. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22458. this._target.parent = this._parent;
  22459. };
  22460. return SetParentAction;
  22461. })(BABYLON.Action);
  22462. BABYLON.SetParentAction = SetParentAction;
  22463. })(BABYLON || (BABYLON = {}));
  22464. //# sourceMappingURL=babylon.directActions.js.map
  22465. var BABYLON;
  22466. (function (BABYLON) {
  22467. var Geometry = (function () {
  22468. function Geometry(id, scene, vertexData, updatable, mesh) {
  22469. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22470. this._totalVertices = 0;
  22471. this._indices = [];
  22472. this.id = id;
  22473. this._engine = scene.getEngine();
  22474. this._meshes = [];
  22475. this._scene = scene;
  22476. // vertexData
  22477. if (vertexData) {
  22478. this.setAllVerticesData(vertexData, updatable);
  22479. } else {
  22480. this._totalVertices = 0;
  22481. this._indices = [];
  22482. }
  22483. // applyToMesh
  22484. if (mesh) {
  22485. this.applyToMesh(mesh);
  22486. }
  22487. }
  22488. Geometry.prototype.getScene = function () {
  22489. return this._scene;
  22490. };
  22491. Geometry.prototype.getEngine = function () {
  22492. return this._engine;
  22493. };
  22494. Geometry.prototype.isReady = function () {
  22495. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22496. };
  22497. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22498. vertexData.applyToGeometry(this, updatable);
  22499. };
  22500. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22501. this._vertexBuffers = this._vertexBuffers || {};
  22502. if (this._vertexBuffers[kind]) {
  22503. this._vertexBuffers[kind].dispose();
  22504. }
  22505. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22506. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22507. stride = this._vertexBuffers[kind].getStrideSize();
  22508. this._totalVertices = data.length / stride;
  22509. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22510. var meshes = this._meshes;
  22511. var numOfMeshes = meshes.length;
  22512. for (var index = 0; index < numOfMeshes; index++) {
  22513. var mesh = meshes[index];
  22514. mesh._resetPointsArrayCache();
  22515. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22516. mesh._createGlobalSubMesh();
  22517. mesh.computeWorldMatrix(true);
  22518. }
  22519. }
  22520. };
  22521. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22522. var vertexBuffer = this.getVertexBuffer(kind);
  22523. if (!vertexBuffer) {
  22524. return;
  22525. }
  22526. vertexBuffer.updateDirectly(data, offset);
  22527. };
  22528. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22529. var vertexBuffer = this.getVertexBuffer(kind);
  22530. if (!vertexBuffer) {
  22531. return;
  22532. }
  22533. vertexBuffer.update(data);
  22534. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22535. var extend;
  22536. var stride = vertexBuffer.getStrideSize();
  22537. this._totalVertices = data.length / stride;
  22538. if (updateExtends) {
  22539. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22540. }
  22541. var meshes = this._meshes;
  22542. var numOfMeshes = meshes.length;
  22543. for (var index = 0; index < numOfMeshes; index++) {
  22544. var mesh = meshes[index];
  22545. mesh._resetPointsArrayCache();
  22546. if (updateExtends) {
  22547. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22548. }
  22549. }
  22550. }
  22551. };
  22552. Geometry.prototype.getTotalVertices = function () {
  22553. if (!this.isReady()) {
  22554. return 0;
  22555. }
  22556. return this._totalVertices;
  22557. };
  22558. Geometry.prototype.getVerticesData = function (kind) {
  22559. var vertexBuffer = this.getVertexBuffer(kind);
  22560. if (!vertexBuffer) {
  22561. return null;
  22562. }
  22563. return vertexBuffer.getData();
  22564. };
  22565. Geometry.prototype.getVertexBuffer = function (kind) {
  22566. if (!this.isReady()) {
  22567. return null;
  22568. }
  22569. return this._vertexBuffers[kind];
  22570. };
  22571. Geometry.prototype.getVertexBuffers = function () {
  22572. if (!this.isReady()) {
  22573. return null;
  22574. }
  22575. return this._vertexBuffers;
  22576. };
  22577. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22578. if (!this._vertexBuffers) {
  22579. if (this._delayInfo) {
  22580. return this._delayInfo.indexOf(kind) !== -1;
  22581. }
  22582. return false;
  22583. }
  22584. return this._vertexBuffers[kind] !== undefined;
  22585. };
  22586. Geometry.prototype.getVerticesDataKinds = function () {
  22587. var result = [];
  22588. if (!this._vertexBuffers && this._delayInfo) {
  22589. for (var kind in this._delayInfo) {
  22590. result.push(kind);
  22591. }
  22592. } else {
  22593. for (kind in this._vertexBuffers) {
  22594. result.push(kind);
  22595. }
  22596. }
  22597. return result;
  22598. };
  22599. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22600. if (this._indexBuffer) {
  22601. this._engine._releaseBuffer(this._indexBuffer);
  22602. }
  22603. this._indices = indices;
  22604. if (this._meshes.length !== 0 && this._indices) {
  22605. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22606. }
  22607. if (totalVertices !== undefined) {
  22608. this._totalVertices = totalVertices;
  22609. }
  22610. var meshes = this._meshes;
  22611. var numOfMeshes = meshes.length;
  22612. for (var index = 0; index < numOfMeshes; index++) {
  22613. meshes[index]._createGlobalSubMesh();
  22614. }
  22615. };
  22616. Geometry.prototype.getTotalIndices = function () {
  22617. if (!this.isReady()) {
  22618. return 0;
  22619. }
  22620. return this._indices.length;
  22621. };
  22622. Geometry.prototype.getIndices = function () {
  22623. if (!this.isReady()) {
  22624. return null;
  22625. }
  22626. return this._indices;
  22627. };
  22628. Geometry.prototype.getIndexBuffer = function () {
  22629. if (!this.isReady()) {
  22630. return null;
  22631. }
  22632. return this._indexBuffer;
  22633. };
  22634. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22635. var meshes = this._meshes;
  22636. var index = meshes.indexOf(mesh);
  22637. if (index === -1) {
  22638. return;
  22639. }
  22640. for (var kind in this._vertexBuffers) {
  22641. this._vertexBuffers[kind].dispose();
  22642. }
  22643. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22644. this._indexBuffer = null;
  22645. }
  22646. meshes.splice(index, 1);
  22647. mesh._geometry = null;
  22648. if (meshes.length === 0 && shouldDispose) {
  22649. this.dispose();
  22650. }
  22651. };
  22652. Geometry.prototype.applyToMesh = function (mesh) {
  22653. if (mesh._geometry === this) {
  22654. return;
  22655. }
  22656. var previousGeometry = mesh._geometry;
  22657. if (previousGeometry) {
  22658. previousGeometry.releaseForMesh(mesh);
  22659. }
  22660. var meshes = this._meshes;
  22661. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22662. mesh._geometry = this;
  22663. this._scene.pushGeometry(this);
  22664. meshes.push(mesh);
  22665. if (this.isReady()) {
  22666. this._applyToMesh(mesh);
  22667. } else {
  22668. mesh._boundingInfo = this._boundingInfo;
  22669. }
  22670. };
  22671. Geometry.prototype._applyToMesh = function (mesh) {
  22672. var numOfMeshes = this._meshes.length;
  22673. for (var kind in this._vertexBuffers) {
  22674. if (numOfMeshes === 1) {
  22675. this._vertexBuffers[kind].create();
  22676. }
  22677. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22678. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22679. mesh._resetPointsArrayCache();
  22680. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22681. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22682. mesh._createGlobalSubMesh();
  22683. //bounding info was just created again, world matrix should be applied again.
  22684. mesh._updateBoundingInfo();
  22685. }
  22686. }
  22687. // indexBuffer
  22688. if (numOfMeshes === 1 && this._indices) {
  22689. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22690. }
  22691. if (this._indexBuffer) {
  22692. this._indexBuffer.references = numOfMeshes;
  22693. }
  22694. };
  22695. Geometry.prototype.load = function (scene, onLoaded) {
  22696. var _this = this;
  22697. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22698. return;
  22699. }
  22700. if (this.isReady()) {
  22701. if (onLoaded) {
  22702. onLoaded();
  22703. }
  22704. return;
  22705. }
  22706. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22707. scene._addPendingData(this);
  22708. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22709. _this._delayLoadingFunction(JSON.parse(data), _this);
  22710. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22711. _this._delayInfo = [];
  22712. scene._removePendingData(_this);
  22713. var meshes = _this._meshes;
  22714. var numOfMeshes = meshes.length;
  22715. for (var index = 0; index < numOfMeshes; index++) {
  22716. _this._applyToMesh(meshes[index]);
  22717. }
  22718. if (onLoaded) {
  22719. onLoaded();
  22720. }
  22721. }, function () {
  22722. }, scene.database);
  22723. };
  22724. Geometry.prototype.dispose = function () {
  22725. var meshes = this._meshes;
  22726. var numOfMeshes = meshes.length;
  22727. var index;
  22728. for (index = 0; index < numOfMeshes; index++) {
  22729. this.releaseForMesh(meshes[index]);
  22730. }
  22731. this._meshes = [];
  22732. for (var kind in this._vertexBuffers) {
  22733. this._vertexBuffers[kind].dispose();
  22734. }
  22735. this._vertexBuffers = [];
  22736. this._totalVertices = 0;
  22737. if (this._indexBuffer) {
  22738. this._engine._releaseBuffer(this._indexBuffer);
  22739. }
  22740. this._indexBuffer = null;
  22741. this._indices = [];
  22742. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22743. this.delayLoadingFile = null;
  22744. this._delayLoadingFunction = null;
  22745. this._delayInfo = [];
  22746. this._boundingInfo = null; // todo: .dispose()
  22747. var geometries = this._scene.getGeometries();
  22748. index = geometries.indexOf(this);
  22749. if (index > -1) {
  22750. geometries.splice(index, 1);
  22751. }
  22752. };
  22753. Geometry.prototype.copy = function (id) {
  22754. var vertexData = new BABYLON.VertexData();
  22755. vertexData.indices = [];
  22756. var indices = this.getIndices();
  22757. for (var index = 0; index < indices.length; index++) {
  22758. vertexData.indices.push(indices[index]);
  22759. }
  22760. var updatable = false;
  22761. var stopChecking = false;
  22762. for (var kind in this._vertexBuffers) {
  22763. vertexData.set(this.getVerticesData(kind), kind);
  22764. if (!stopChecking) {
  22765. updatable = this.getVertexBuffer(kind).isUpdatable();
  22766. stopChecking = !updatable;
  22767. }
  22768. }
  22769. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  22770. geometry.delayLoadState = this.delayLoadState;
  22771. geometry.delayLoadingFile = this.delayLoadingFile;
  22772. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22773. for (kind in this._delayInfo) {
  22774. geometry._delayInfo = geometry._delayInfo || [];
  22775. geometry._delayInfo.push(kind);
  22776. }
  22777. // Bounding info
  22778. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22779. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22780. return geometry;
  22781. };
  22782. // Statics
  22783. Geometry.ExtractFromMesh = function (mesh, id) {
  22784. var geometry = mesh._geometry;
  22785. if (!geometry) {
  22786. return null;
  22787. }
  22788. return geometry.copy(id);
  22789. };
  22790. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22791. // be aware Math.random() could cause collisions
  22792. Geometry.RandomId = function () {
  22793. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22794. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  22795. return v.toString(16);
  22796. });
  22797. };
  22798. return Geometry;
  22799. })();
  22800. BABYLON.Geometry = Geometry;
  22801. (function (Geometry) {
  22802. /////// Primitives //////////////////////////////////////////////
  22803. (function (Primitives) {
  22804. /// Abstract class
  22805. var _Primitive = (function (_super) {
  22806. __extends(_Primitive, _super);
  22807. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22808. this._beingRegenerated = true;
  22809. this._canBeRegenerated = canBeRegenerated;
  22810. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22811. this._beingRegenerated = false;
  22812. }
  22813. _Primitive.prototype.canBeRegenerated = function () {
  22814. return this._canBeRegenerated;
  22815. };
  22816. _Primitive.prototype.regenerate = function () {
  22817. if (!this._canBeRegenerated) {
  22818. return;
  22819. }
  22820. this._beingRegenerated = true;
  22821. this.setAllVerticesData(this._regenerateVertexData(), false);
  22822. this._beingRegenerated = false;
  22823. };
  22824. _Primitive.prototype.asNewGeometry = function (id) {
  22825. return _super.prototype.copy.call(this, id);
  22826. };
  22827. // overrides
  22828. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  22829. if (!this._beingRegenerated) {
  22830. return;
  22831. }
  22832. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  22833. };
  22834. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  22835. if (!this._beingRegenerated) {
  22836. return;
  22837. }
  22838. _super.prototype.setVerticesData.call(this, kind, data, false);
  22839. };
  22840. // to override
  22841. // protected
  22842. _Primitive.prototype._regenerateVertexData = function () {
  22843. throw new Error("Abstract method");
  22844. };
  22845. _Primitive.prototype.copy = function (id) {
  22846. throw new Error("Must be overriden in sub-classes.");
  22847. };
  22848. return _Primitive;
  22849. })(Geometry);
  22850. Primitives._Primitive = _Primitive;
  22851. var Box = (function (_super) {
  22852. __extends(Box, _super);
  22853. function Box(id, scene, size, canBeRegenerated, mesh) {
  22854. this.size = size;
  22855. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22856. }
  22857. Box.prototype._regenerateVertexData = function () {
  22858. return BABYLON.VertexData.CreateBox(this.size);
  22859. };
  22860. Box.prototype.copy = function (id) {
  22861. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22862. };
  22863. return Box;
  22864. })(_Primitive);
  22865. Primitives.Box = Box;
  22866. var Sphere = (function (_super) {
  22867. __extends(Sphere, _super);
  22868. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  22869. this.segments = segments;
  22870. this.diameter = diameter;
  22871. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22872. }
  22873. Sphere.prototype._regenerateVertexData = function () {
  22874. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  22875. };
  22876. Sphere.prototype.copy = function (id) {
  22877. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  22878. };
  22879. return Sphere;
  22880. })(_Primitive);
  22881. Primitives.Sphere = Sphere;
  22882. var Cylinder = (function (_super) {
  22883. __extends(Cylinder, _super);
  22884. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  22885. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  22886. this.height = height;
  22887. this.diameterTop = diameterTop;
  22888. this.diameterBottom = diameterBottom;
  22889. this.tessellation = tessellation;
  22890. this.subdivisions = subdivisions;
  22891. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22892. }
  22893. Cylinder.prototype._regenerateVertexData = function () {
  22894. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  22895. };
  22896. Cylinder.prototype.copy = function (id) {
  22897. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  22898. };
  22899. return Cylinder;
  22900. })(_Primitive);
  22901. Primitives.Cylinder = Cylinder;
  22902. var Torus = (function (_super) {
  22903. __extends(Torus, _super);
  22904. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  22905. this.diameter = diameter;
  22906. this.thickness = thickness;
  22907. this.tessellation = tessellation;
  22908. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22909. }
  22910. Torus.prototype._regenerateVertexData = function () {
  22911. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  22912. };
  22913. Torus.prototype.copy = function (id) {
  22914. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  22915. };
  22916. return Torus;
  22917. })(_Primitive);
  22918. Primitives.Torus = Torus;
  22919. var Ground = (function (_super) {
  22920. __extends(Ground, _super);
  22921. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  22922. this.width = width;
  22923. this.height = height;
  22924. this.subdivisions = subdivisions;
  22925. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22926. }
  22927. Ground.prototype._regenerateVertexData = function () {
  22928. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  22929. };
  22930. Ground.prototype.copy = function (id) {
  22931. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  22932. };
  22933. return Ground;
  22934. })(_Primitive);
  22935. Primitives.Ground = Ground;
  22936. var TiledGround = (function (_super) {
  22937. __extends(TiledGround, _super);
  22938. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  22939. this.xmin = xmin;
  22940. this.zmin = zmin;
  22941. this.xmax = xmax;
  22942. this.zmax = zmax;
  22943. this.subdivisions = subdivisions;
  22944. this.precision = precision;
  22945. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22946. }
  22947. TiledGround.prototype._regenerateVertexData = function () {
  22948. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  22949. };
  22950. TiledGround.prototype.copy = function (id) {
  22951. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  22952. };
  22953. return TiledGround;
  22954. })(_Primitive);
  22955. Primitives.TiledGround = TiledGround;
  22956. var Plane = (function (_super) {
  22957. __extends(Plane, _super);
  22958. function Plane(id, scene, size, canBeRegenerated, mesh) {
  22959. this.size = size;
  22960. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22961. }
  22962. Plane.prototype._regenerateVertexData = function () {
  22963. return BABYLON.VertexData.CreatePlane(this.size);
  22964. };
  22965. Plane.prototype.copy = function (id) {
  22966. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22967. };
  22968. return Plane;
  22969. })(_Primitive);
  22970. Primitives.Plane = Plane;
  22971. var TorusKnot = (function (_super) {
  22972. __extends(TorusKnot, _super);
  22973. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  22974. this.radius = radius;
  22975. this.tube = tube;
  22976. this.radialSegments = radialSegments;
  22977. this.tubularSegments = tubularSegments;
  22978. this.p = p;
  22979. this.q = q;
  22980. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22981. }
  22982. TorusKnot.prototype._regenerateVertexData = function () {
  22983. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  22984. };
  22985. TorusKnot.prototype.copy = function (id) {
  22986. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  22987. };
  22988. return TorusKnot;
  22989. })(_Primitive);
  22990. Primitives.TorusKnot = TorusKnot;
  22991. })(Geometry.Primitives || (Geometry.Primitives = {}));
  22992. var Primitives = Geometry.Primitives;
  22993. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  22994. var Geometry = BABYLON.Geometry;
  22995. })(BABYLON || (BABYLON = {}));
  22996. //# sourceMappingURL=babylon.geometry.js.map
  22997. var BABYLON;
  22998. (function (BABYLON) {
  22999. var Gamepads = (function () {
  23000. function Gamepads(ongamedpadconnected) {
  23001. var _this = this;
  23002. this.babylonGamepads = [];
  23003. this.oneGamepadConnected = false;
  23004. this.isMonitoring = false;
  23005. this.gamepadEventSupported = 'GamepadEvent' in window;
  23006. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23007. 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=";
  23008. this._callbackGamepadConnected = ongamedpadconnected;
  23009. if (this.gamepadSupportAvailable) {
  23010. // Checking if the gamepad connected event is supported (like in Firefox)
  23011. if (this.gamepadEventSupported) {
  23012. window.addEventListener('gamepadconnected', function (evt) {
  23013. _this._onGamepadConnected(evt);
  23014. }, false);
  23015. window.addEventListener('gamepaddisconnected', function (evt) {
  23016. _this._onGamepadDisconnected(evt);
  23017. }, false);
  23018. } else {
  23019. this._startMonitoringGamepads();
  23020. }
  23021. if (!this.oneGamepadConnected) {
  23022. this._insertGamepadDOMInstructions();
  23023. }
  23024. } else {
  23025. this._insertGamepadDOMNotSupported();
  23026. }
  23027. }
  23028. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23029. Gamepads.gamepadDOMInfo = document.createElement("div");
  23030. var buttonAImage = document.createElement("img");
  23031. buttonAImage.src = this.buttonADataURL;
  23032. var spanMessage = document.createElement("span");
  23033. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23034. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23035. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23036. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23037. Gamepads.gamepadDOMInfo.style.width = "100%";
  23038. Gamepads.gamepadDOMInfo.style.height = "48px";
  23039. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23040. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23041. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23042. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23043. buttonAImage.style.position = "relative";
  23044. buttonAImage.style.bottom = "8px";
  23045. spanMessage.style.position = "relative";
  23046. spanMessage.style.fontSize = "32px";
  23047. spanMessage.style.bottom = "32px";
  23048. spanMessage.style.color = "green";
  23049. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23050. };
  23051. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  23052. Gamepads.gamepadDOMInfo = document.createElement("div");
  23053. var spanMessage = document.createElement("span");
  23054. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  23055. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23056. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23057. Gamepads.gamepadDOMInfo.style.width = "100%";
  23058. Gamepads.gamepadDOMInfo.style.height = "40px";
  23059. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23060. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23061. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23062. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23063. spanMessage.style.position = "relative";
  23064. spanMessage.style.fontSize = "32px";
  23065. spanMessage.style.color = "red";
  23066. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23067. };
  23068. Gamepads.prototype.dispose = function () {
  23069. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23070. };
  23071. Gamepads.prototype._onGamepadConnected = function (evt) {
  23072. var newGamepad = this._addNewGamepad(evt.gamepad);
  23073. if (this._callbackGamepadConnected)
  23074. this._callbackGamepadConnected(newGamepad);
  23075. this._startMonitoringGamepads();
  23076. };
  23077. Gamepads.prototype._addNewGamepad = function (gamepad) {
  23078. if (!this.oneGamepadConnected) {
  23079. this.oneGamepadConnected = true;
  23080. if (Gamepads.gamepadDOMInfo) {
  23081. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23082. Gamepads.gamepadDOMInfo = null;
  23083. }
  23084. }
  23085. var newGamepad;
  23086. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  23087. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  23088. } else {
  23089. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  23090. }
  23091. this.babylonGamepads.push(newGamepad);
  23092. return newGamepad;
  23093. };
  23094. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  23095. for (var i in this.babylonGamepads) {
  23096. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  23097. this.babylonGamepads.splice(i, 1);
  23098. break;
  23099. }
  23100. }
  23101. // If no gamepads are left, stop the polling loop.
  23102. if (this.babylonGamepads.length == 0) {
  23103. this._stopMonitoringGamepads();
  23104. }
  23105. };
  23106. Gamepads.prototype._startMonitoringGamepads = function () {
  23107. if (!this.isMonitoring) {
  23108. this.isMonitoring = true;
  23109. this._checkGamepadsStatus();
  23110. }
  23111. };
  23112. Gamepads.prototype._stopMonitoringGamepads = function () {
  23113. this.isMonitoring = false;
  23114. };
  23115. Gamepads.prototype._checkGamepadsStatus = function () {
  23116. var _this = this;
  23117. // updating gamepad objects
  23118. this._updateGamepadObjects();
  23119. for (var i in this.babylonGamepads) {
  23120. this.babylonGamepads[i].update();
  23121. }
  23122. if (this.isMonitoring) {
  23123. if (window.requestAnimationFrame) {
  23124. window.requestAnimationFrame(function () {
  23125. _this._checkGamepadsStatus();
  23126. });
  23127. } else if (window.mozRequestAnimationFrame) {
  23128. window.mozRequestAnimationFrame(function () {
  23129. _this._checkGamepadsStatus();
  23130. });
  23131. } else if (window.webkitRequestAnimationFrame) {
  23132. window.webkitRequestAnimationFrame(function () {
  23133. _this._checkGamepadsStatus();
  23134. });
  23135. }
  23136. }
  23137. };
  23138. // This function is called only on Chrome, which does not yet support
  23139. // connection/disconnection events, but requires you to monitor
  23140. // an array for changes.
  23141. Gamepads.prototype._updateGamepadObjects = function () {
  23142. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  23143. for (var i = 0; i < gamepads.length; i++) {
  23144. if (gamepads[i]) {
  23145. if (!(gamepads[i].index in this.babylonGamepads)) {
  23146. var newGamepad = this._addNewGamepad(gamepads[i]);
  23147. if (this._callbackGamepadConnected) {
  23148. this._callbackGamepadConnected(newGamepad);
  23149. }
  23150. } else {
  23151. this.babylonGamepads[i].browserGamepad = gamepads[i];
  23152. }
  23153. }
  23154. }
  23155. };
  23156. return Gamepads;
  23157. })();
  23158. BABYLON.Gamepads = Gamepads;
  23159. var StickValues = (function () {
  23160. function StickValues(x, y) {
  23161. this.x = x;
  23162. this.y = y;
  23163. }
  23164. return StickValues;
  23165. })();
  23166. BABYLON.StickValues = StickValues;
  23167. var Gamepad = (function () {
  23168. function Gamepad(id, index, browserGamepad) {
  23169. this.id = id;
  23170. this.index = index;
  23171. this.browserGamepad = browserGamepad;
  23172. if (this.browserGamepad.axes.length >= 2) {
  23173. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23174. }
  23175. if (this.browserGamepad.axes.length >= 4) {
  23176. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23177. }
  23178. }
  23179. Gamepad.prototype.onleftstickchanged = function (callback) {
  23180. this._onleftstickchanged = callback;
  23181. };
  23182. Gamepad.prototype.onrightstickchanged = function (callback) {
  23183. this._onrightstickchanged = callback;
  23184. };
  23185. Object.defineProperty(Gamepad.prototype, "leftStick", {
  23186. get: function () {
  23187. return this._leftStick;
  23188. },
  23189. set: function (newValues) {
  23190. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  23191. this._onleftstickchanged(newValues);
  23192. }
  23193. this._leftStick = newValues;
  23194. },
  23195. enumerable: true,
  23196. configurable: true
  23197. });
  23198. Object.defineProperty(Gamepad.prototype, "rightStick", {
  23199. get: function () {
  23200. return this._rightStick;
  23201. },
  23202. set: function (newValues) {
  23203. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  23204. this._onrightstickchanged(newValues);
  23205. }
  23206. this._rightStick = newValues;
  23207. },
  23208. enumerable: true,
  23209. configurable: true
  23210. });
  23211. Gamepad.prototype.update = function () {
  23212. if (this._leftStick) {
  23213. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23214. }
  23215. if (this._rightStick) {
  23216. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23217. }
  23218. };
  23219. return Gamepad;
  23220. })();
  23221. BABYLON.Gamepad = Gamepad;
  23222. var GenericPad = (function (_super) {
  23223. __extends(GenericPad, _super);
  23224. function GenericPad(id, index, gamepad) {
  23225. _super.call(this, id, index, gamepad);
  23226. this.id = id;
  23227. this.index = index;
  23228. this.gamepad = gamepad;
  23229. this._buttons = new Array(gamepad.buttons.length);
  23230. }
  23231. GenericPad.prototype.onbuttondown = function (callback) {
  23232. this._onbuttondown = callback;
  23233. };
  23234. GenericPad.prototype.onbuttonup = function (callback) {
  23235. this._onbuttonup = callback;
  23236. };
  23237. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  23238. if (newValue !== currentValue) {
  23239. if (this._onbuttondown && newValue === 1) {
  23240. this._onbuttondown(buttonIndex);
  23241. }
  23242. if (this._onbuttonup && newValue === 0) {
  23243. this._onbuttonup(buttonIndex);
  23244. }
  23245. }
  23246. return newValue;
  23247. };
  23248. GenericPad.prototype.update = function () {
  23249. _super.prototype.update.call(this);
  23250. for (var index = 0; index < this._buttons.length; index++) {
  23251. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23252. }
  23253. };
  23254. return GenericPad;
  23255. })(Gamepad);
  23256. BABYLON.GenericPad = GenericPad;
  23257. (function (Xbox360Button) {
  23258. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23259. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23260. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23261. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23262. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23263. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23264. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23265. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23266. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23267. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23268. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23269. var Xbox360Button = BABYLON.Xbox360Button;
  23270. (function (Xbox360Dpad) {
  23271. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23272. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23273. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23274. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23275. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23276. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23277. var Xbox360Pad = (function (_super) {
  23278. __extends(Xbox360Pad, _super);
  23279. function Xbox360Pad() {
  23280. _super.apply(this, arguments);
  23281. this._leftTrigger = 0;
  23282. this._rightTrigger = 0;
  23283. this._buttonA = 0;
  23284. this._buttonB = 0;
  23285. this._buttonX = 0;
  23286. this._buttonY = 0;
  23287. this._buttonBack = 0;
  23288. this._buttonStart = 0;
  23289. this._buttonLB = 0;
  23290. this._buttonRB = 0;
  23291. this._buttonLeftStick = 0;
  23292. this._buttonRightStick = 0;
  23293. this._dPadUp = 0;
  23294. this._dPadDown = 0;
  23295. this._dPadLeft = 0;
  23296. this._dPadRight = 0;
  23297. }
  23298. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23299. this._onlefttriggerchanged = callback;
  23300. };
  23301. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23302. this._onrighttriggerchanged = callback;
  23303. };
  23304. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23305. get: function () {
  23306. return this._leftTrigger;
  23307. },
  23308. set: function (newValue) {
  23309. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23310. this._onlefttriggerchanged(newValue);
  23311. }
  23312. this._leftTrigger = newValue;
  23313. },
  23314. enumerable: true,
  23315. configurable: true
  23316. });
  23317. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23318. get: function () {
  23319. return this._rightTrigger;
  23320. },
  23321. set: function (newValue) {
  23322. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23323. this._onrighttriggerchanged(newValue);
  23324. }
  23325. this._rightTrigger = newValue;
  23326. },
  23327. enumerable: true,
  23328. configurable: true
  23329. });
  23330. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23331. this._onbuttondown = callback;
  23332. };
  23333. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23334. this._onbuttonup = callback;
  23335. };
  23336. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23337. this._ondpaddown = callback;
  23338. };
  23339. Xbox360Pad.prototype.ondpadup = function (callback) {
  23340. this._ondpadup = callback;
  23341. };
  23342. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23343. if (newValue !== currentValue) {
  23344. if (this._onbuttondown && newValue === 1) {
  23345. this._onbuttondown(buttonType);
  23346. }
  23347. if (this._onbuttonup && newValue === 0) {
  23348. this._onbuttonup(buttonType);
  23349. }
  23350. }
  23351. return newValue;
  23352. };
  23353. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23354. if (newValue !== currentValue) {
  23355. if (this._ondpaddown && newValue === 1) {
  23356. this._ondpaddown(buttonType);
  23357. }
  23358. if (this._ondpadup && newValue === 0) {
  23359. this._ondpadup(buttonType);
  23360. }
  23361. }
  23362. return newValue;
  23363. };
  23364. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23365. get: function () {
  23366. return this._buttonA;
  23367. },
  23368. set: function (value) {
  23369. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23370. },
  23371. enumerable: true,
  23372. configurable: true
  23373. });
  23374. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23375. get: function () {
  23376. return this._buttonB;
  23377. },
  23378. set: function (value) {
  23379. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23380. },
  23381. enumerable: true,
  23382. configurable: true
  23383. });
  23384. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23385. get: function () {
  23386. return this._buttonX;
  23387. },
  23388. set: function (value) {
  23389. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23390. },
  23391. enumerable: true,
  23392. configurable: true
  23393. });
  23394. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23395. get: function () {
  23396. return this._buttonY;
  23397. },
  23398. set: function (value) {
  23399. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23400. },
  23401. enumerable: true,
  23402. configurable: true
  23403. });
  23404. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23405. get: function () {
  23406. return this._buttonStart;
  23407. },
  23408. set: function (value) {
  23409. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23410. },
  23411. enumerable: true,
  23412. configurable: true
  23413. });
  23414. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23415. get: function () {
  23416. return this._buttonBack;
  23417. },
  23418. set: function (value) {
  23419. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23420. },
  23421. enumerable: true,
  23422. configurable: true
  23423. });
  23424. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23425. get: function () {
  23426. return this._buttonLB;
  23427. },
  23428. set: function (value) {
  23429. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23430. },
  23431. enumerable: true,
  23432. configurable: true
  23433. });
  23434. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23435. get: function () {
  23436. return this._buttonRB;
  23437. },
  23438. set: function (value) {
  23439. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23440. },
  23441. enumerable: true,
  23442. configurable: true
  23443. });
  23444. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23445. get: function () {
  23446. return this._buttonLeftStick;
  23447. },
  23448. set: function (value) {
  23449. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23450. },
  23451. enumerable: true,
  23452. configurable: true
  23453. });
  23454. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23455. get: function () {
  23456. return this._buttonRightStick;
  23457. },
  23458. set: function (value) {
  23459. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23460. },
  23461. enumerable: true,
  23462. configurable: true
  23463. });
  23464. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23465. get: function () {
  23466. return this._dPadUp;
  23467. },
  23468. set: function (value) {
  23469. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23470. },
  23471. enumerable: true,
  23472. configurable: true
  23473. });
  23474. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23475. get: function () {
  23476. return this._dPadDown;
  23477. },
  23478. set: function (value) {
  23479. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23480. },
  23481. enumerable: true,
  23482. configurable: true
  23483. });
  23484. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23485. get: function () {
  23486. return this._dPadLeft;
  23487. },
  23488. set: function (value) {
  23489. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23490. },
  23491. enumerable: true,
  23492. configurable: true
  23493. });
  23494. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23495. get: function () {
  23496. return this._dPadRight;
  23497. },
  23498. set: function (value) {
  23499. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23500. },
  23501. enumerable: true,
  23502. configurable: true
  23503. });
  23504. Xbox360Pad.prototype.update = function () {
  23505. _super.prototype.update.call(this);
  23506. this.buttonA = this.browserGamepad.buttons[0].value;
  23507. this.buttonB = this.browserGamepad.buttons[1].value;
  23508. this.buttonX = this.browserGamepad.buttons[2].value;
  23509. this.buttonY = this.browserGamepad.buttons[3].value;
  23510. this.buttonLB = this.browserGamepad.buttons[4].value;
  23511. this.buttonRB = this.browserGamepad.buttons[5].value;
  23512. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23513. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23514. this.buttonBack = this.browserGamepad.buttons[8].value;
  23515. this.buttonStart = this.browserGamepad.buttons[9].value;
  23516. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23517. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23518. this.dPadUp = this.browserGamepad.buttons[12].value;
  23519. this.dPadDown = this.browserGamepad.buttons[13].value;
  23520. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23521. this.dPadRight = this.browserGamepad.buttons[15].value;
  23522. };
  23523. return Xbox360Pad;
  23524. })(Gamepad);
  23525. BABYLON.Xbox360Pad = Xbox360Pad;
  23526. })(BABYLON || (BABYLON = {}));
  23527. //# sourceMappingURL=babylon.gamepads.js.map
  23528. var BABYLON;
  23529. (function (BABYLON) {
  23530. // We're mainly based on the logic defined into the FreeCamera code
  23531. var GamepadCamera = (function (_super) {
  23532. __extends(GamepadCamera, _super);
  23533. function GamepadCamera(name, position, scene) {
  23534. var _this = this;
  23535. _super.call(this, name, position, scene);
  23536. this.angularSensibility = 200;
  23537. this.moveSensibility = 75;
  23538. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23539. _this._onNewGameConnected(gamepad);
  23540. });
  23541. }
  23542. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23543. // Only the first gamepad can control the camera
  23544. if (gamepad.index === 0) {
  23545. this._gamepad = gamepad;
  23546. }
  23547. };
  23548. GamepadCamera.prototype._checkInputs = function () {
  23549. if (!this._gamepad) {
  23550. return;
  23551. }
  23552. var LSValues = this._gamepad.leftStick;
  23553. var normalizedLX = LSValues.x / this.moveSensibility;
  23554. var normalizedLY = LSValues.y / this.moveSensibility;
  23555. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23556. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23557. var RSValues = this._gamepad.rightStick;
  23558. var normalizedRX = RSValues.x / this.angularSensibility;
  23559. var normalizedRY = RSValues.y / this.angularSensibility;
  23560. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23561. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23562. ;
  23563. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23564. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23565. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23566. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23567. };
  23568. GamepadCamera.prototype.dispose = function () {
  23569. this._gamepads.dispose();
  23570. _super.prototype.dispose.call(this);
  23571. };
  23572. return GamepadCamera;
  23573. })(BABYLON.FreeCamera);
  23574. BABYLON.GamepadCamera = GamepadCamera;
  23575. })(BABYLON || (BABYLON = {}));
  23576. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23577. var BABYLON;
  23578. (function (BABYLON) {
  23579. var LinesMesh = (function (_super) {
  23580. __extends(LinesMesh, _super);
  23581. function LinesMesh(name, scene, updatable) {
  23582. if (typeof updatable === "undefined") { updatable = false; }
  23583. _super.call(this, name, scene);
  23584. this.color = new BABYLON.Color3(1, 1, 1);
  23585. this.alpha = 1;
  23586. this._indices = new Array();
  23587. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23588. attributes: ["position"],
  23589. uniforms: ["worldViewProjection", "color"],
  23590. needAlphaBlending: true
  23591. });
  23592. }
  23593. Object.defineProperty(LinesMesh.prototype, "material", {
  23594. get: function () {
  23595. return this._colorShader;
  23596. },
  23597. enumerable: true,
  23598. configurable: true
  23599. });
  23600. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23601. get: function () {
  23602. return false;
  23603. },
  23604. enumerable: true,
  23605. configurable: true
  23606. });
  23607. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23608. get: function () {
  23609. return false;
  23610. },
  23611. enumerable: true,
  23612. configurable: true
  23613. });
  23614. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23615. var engine = this.getScene().getEngine();
  23616. var indexToBind = this._geometry.getIndexBuffer();
  23617. // VBOs
  23618. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23619. // Color
  23620. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23621. };
  23622. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23623. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23624. return;
  23625. }
  23626. var engine = this.getScene().getEngine();
  23627. // Draw order
  23628. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23629. };
  23630. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23631. return null;
  23632. };
  23633. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23634. this._colorShader.dispose();
  23635. _super.prototype.dispose.call(this, doNotRecurse);
  23636. };
  23637. return LinesMesh;
  23638. })(BABYLON.Mesh);
  23639. BABYLON.LinesMesh = LinesMesh;
  23640. })(BABYLON || (BABYLON = {}));
  23641. //# sourceMappingURL=babylon.linesMesh.js.map
  23642. var BABYLON;
  23643. (function (BABYLON) {
  23644. var OutlineRenderer = (function () {
  23645. function OutlineRenderer(scene) {
  23646. this._scene = scene;
  23647. }
  23648. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23649. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23650. var scene = this._scene;
  23651. var engine = this._scene.getEngine();
  23652. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23653. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23654. return;
  23655. }
  23656. var mesh = subMesh.getRenderingMesh();
  23657. var material = subMesh.getMaterial();
  23658. engine.enableEffect(this._effect);
  23659. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23660. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23661. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23662. // Bones
  23663. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23664. if (useBones) {
  23665. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23666. }
  23667. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23668. // Alpha test
  23669. if (material && material.needAlphaTesting()) {
  23670. var alphaTexture = material.getAlphaTestTexture();
  23671. this._effect.setTexture("diffuseSampler", alphaTexture);
  23672. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23673. }
  23674. if (hardwareInstancedRendering) {
  23675. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23676. } else {
  23677. if (batch.renderSelf[subMesh._id]) {
  23678. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23679. // Draw
  23680. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23681. }
  23682. if (batch.visibleInstances[subMesh._id]) {
  23683. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23684. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23685. this._effect.setMatrix("world", instance.getWorldMatrix());
  23686. // Draw
  23687. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23688. }
  23689. }
  23690. }
  23691. };
  23692. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23693. var defines = [];
  23694. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23695. var mesh = subMesh.getMesh();
  23696. var material = subMesh.getMaterial();
  23697. // Alpha test
  23698. if (material && material.needAlphaTesting()) {
  23699. defines.push("#define ALPHATEST");
  23700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23701. attribs.push(BABYLON.VertexBuffer.UVKind);
  23702. defines.push("#define UV1");
  23703. }
  23704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23705. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23706. defines.push("#define UV2");
  23707. }
  23708. }
  23709. // Bones
  23710. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23711. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23712. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23713. defines.push("#define BONES");
  23714. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23715. }
  23716. // Instances
  23717. if (useInstances) {
  23718. defines.push("#define INSTANCES");
  23719. attribs.push("world0");
  23720. attribs.push("world1");
  23721. attribs.push("world2");
  23722. attribs.push("world3");
  23723. }
  23724. // Get correct effect
  23725. var join = defines.join("\n");
  23726. if (this._cachedDefines != join) {
  23727. this._cachedDefines = join;
  23728. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23729. }
  23730. return this._effect.isReady();
  23731. };
  23732. return OutlineRenderer;
  23733. })();
  23734. BABYLON.OutlineRenderer = OutlineRenderer;
  23735. })(BABYLON || (BABYLON = {}));
  23736. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23737. var BABYLON;
  23738. (function (BABYLON) {
  23739. var MeshAssetTask = (function () {
  23740. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23741. this.name = name;
  23742. this.meshesNames = meshesNames;
  23743. this.rootUrl = rootUrl;
  23744. this.sceneFilename = sceneFilename;
  23745. this.isCompleted = false;
  23746. }
  23747. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23748. var _this = this;
  23749. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23750. _this.loadedMeshes = meshes;
  23751. _this.loadedParticleSystems = particleSystems;
  23752. _this.loadedSkeletons = skeletons;
  23753. _this.isCompleted = true;
  23754. if (_this.onSuccess) {
  23755. _this.onSuccess(_this);
  23756. }
  23757. onSuccess();
  23758. }, null, function () {
  23759. if (_this.onError) {
  23760. _this.onError(_this);
  23761. }
  23762. onError();
  23763. });
  23764. };
  23765. return MeshAssetTask;
  23766. })();
  23767. BABYLON.MeshAssetTask = MeshAssetTask;
  23768. var TextFileAssetTask = (function () {
  23769. function TextFileAssetTask(name, url) {
  23770. this.name = name;
  23771. this.url = url;
  23772. this.isCompleted = false;
  23773. }
  23774. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23775. var _this = this;
  23776. BABYLON.Tools.LoadFile(this.url, function (data) {
  23777. _this.text = data;
  23778. _this.isCompleted = true;
  23779. if (_this.onSuccess) {
  23780. _this.onSuccess(_this);
  23781. }
  23782. onSuccess();
  23783. }, null, scene.database, false, function () {
  23784. if (_this.onError) {
  23785. _this.onError(_this);
  23786. }
  23787. onError();
  23788. });
  23789. };
  23790. return TextFileAssetTask;
  23791. })();
  23792. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23793. var BinaryFileAssetTask = (function () {
  23794. function BinaryFileAssetTask(name, url) {
  23795. this.name = name;
  23796. this.url = url;
  23797. this.isCompleted = false;
  23798. }
  23799. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23800. var _this = this;
  23801. BABYLON.Tools.LoadFile(this.url, function (data) {
  23802. _this.data = data;
  23803. _this.isCompleted = true;
  23804. if (_this.onSuccess) {
  23805. _this.onSuccess(_this);
  23806. }
  23807. onSuccess();
  23808. }, null, scene.database, true, function () {
  23809. if (_this.onError) {
  23810. _this.onError(_this);
  23811. }
  23812. onError();
  23813. });
  23814. };
  23815. return BinaryFileAssetTask;
  23816. })();
  23817. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  23818. var ImageAssetTask = (function () {
  23819. function ImageAssetTask(name, url) {
  23820. this.name = name;
  23821. this.url = url;
  23822. this.isCompleted = false;
  23823. }
  23824. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23825. var _this = this;
  23826. var img = new Image();
  23827. img.onload = function () {
  23828. _this.image = img;
  23829. _this.isCompleted = true;
  23830. if (_this.onSuccess) {
  23831. _this.onSuccess(_this);
  23832. }
  23833. onSuccess();
  23834. };
  23835. img.onerror = function () {
  23836. if (_this.onError) {
  23837. _this.onError(_this);
  23838. }
  23839. onError();
  23840. };
  23841. img.src = this.url;
  23842. };
  23843. return ImageAssetTask;
  23844. })();
  23845. BABYLON.ImageAssetTask = ImageAssetTask;
  23846. var TextureAssetTask = (function () {
  23847. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  23848. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23849. this.name = name;
  23850. this.url = url;
  23851. this.noMipmap = noMipmap;
  23852. this.invertY = invertY;
  23853. this.samplingMode = samplingMode;
  23854. this.isCompleted = false;
  23855. }
  23856. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23857. var _this = this;
  23858. var onload = function () {
  23859. _this.isCompleted = true;
  23860. if (_this.onSuccess) {
  23861. _this.onSuccess(_this);
  23862. }
  23863. onSuccess();
  23864. };
  23865. var onerror = function () {
  23866. if (_this.onError) {
  23867. _this.onError(_this);
  23868. }
  23869. onError();
  23870. };
  23871. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  23872. };
  23873. return TextureAssetTask;
  23874. })();
  23875. BABYLON.TextureAssetTask = TextureAssetTask;
  23876. var AssetsManager = (function () {
  23877. function AssetsManager(scene) {
  23878. this._tasks = new Array();
  23879. this._waitingTasksCount = 0;
  23880. this.useDefaultLoadingScreen = true;
  23881. this._scene = scene;
  23882. }
  23883. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  23884. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  23885. this._tasks.push(task);
  23886. return task;
  23887. };
  23888. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  23889. var task = new TextFileAssetTask(taskName, url);
  23890. this._tasks.push(task);
  23891. return task;
  23892. };
  23893. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  23894. var task = new BinaryFileAssetTask(taskName, url);
  23895. this._tasks.push(task);
  23896. return task;
  23897. };
  23898. AssetsManager.prototype.addImageTask = function (taskName, url) {
  23899. var task = new ImageAssetTask(taskName, url);
  23900. this._tasks.push(task);
  23901. return task;
  23902. };
  23903. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  23904. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23905. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  23906. this._tasks.push(task);
  23907. return task;
  23908. };
  23909. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  23910. this._waitingTasksCount--;
  23911. if (this._waitingTasksCount === 0) {
  23912. if (this.onFinish) {
  23913. this.onFinish(this._tasks);
  23914. }
  23915. this._scene.getEngine().hideLoadingUI();
  23916. }
  23917. };
  23918. AssetsManager.prototype._runTask = function (task) {
  23919. var _this = this;
  23920. task.run(this._scene, function () {
  23921. if (_this.onTaskSuccess) {
  23922. _this.onTaskSuccess(task);
  23923. }
  23924. _this._decreaseWaitingTasksCount();
  23925. }, function () {
  23926. if (_this.onTaskError) {
  23927. _this.onTaskError(task);
  23928. }
  23929. _this._decreaseWaitingTasksCount();
  23930. });
  23931. };
  23932. AssetsManager.prototype.reset = function () {
  23933. this._tasks = new Array();
  23934. return this;
  23935. };
  23936. AssetsManager.prototype.load = function () {
  23937. this._waitingTasksCount = this._tasks.length;
  23938. if (this._waitingTasksCount === 0) {
  23939. if (this.onFinish) {
  23940. this.onFinish(this._tasks);
  23941. }
  23942. return this;
  23943. }
  23944. if (this.useDefaultLoadingScreen) {
  23945. this._scene.getEngine().displayLoadingUI();
  23946. }
  23947. for (var index = 0; index < this._tasks.length; index++) {
  23948. var task = this._tasks[index];
  23949. this._runTask(task);
  23950. }
  23951. return this;
  23952. };
  23953. return AssetsManager;
  23954. })();
  23955. BABYLON.AssetsManager = AssetsManager;
  23956. })(BABYLON || (BABYLON = {}));
  23957. //# sourceMappingURL=babylon.assetsManager.js.map
  23958. var BABYLON;
  23959. (function (BABYLON) {
  23960. var VRDeviceOrientationCamera = (function (_super) {
  23961. __extends(VRDeviceOrientationCamera, _super);
  23962. function VRDeviceOrientationCamera(name, position, scene) {
  23963. _super.call(this, name, position, scene);
  23964. this._alpha = 0;
  23965. this._beta = 0;
  23966. this._gamma = 0;
  23967. }
  23968. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  23969. this._alpha = +evt.alpha | 0;
  23970. this._beta = +evt.beta | 0;
  23971. this._gamma = +evt.gamma | 0;
  23972. if (this._gamma < 0) {
  23973. this._gamma = 90 + this._gamma;
  23974. } else {
  23975. // Incline it in the correct angle.
  23976. this._gamma = 270 - this._gamma;
  23977. }
  23978. this.rotation.x = this._gamma / 180.0 * Math.PI;
  23979. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  23980. this.rotation.z = this._beta / 180.0 * Math.PI;
  23981. };
  23982. return VRDeviceOrientationCamera;
  23983. })(BABYLON.OculusCamera);
  23984. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  23985. })(BABYLON || (BABYLON = {}));
  23986. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  23987. var BABYLON;
  23988. (function (BABYLON) {
  23989. var WebVRCamera = (function (_super) {
  23990. __extends(WebVRCamera, _super);
  23991. function WebVRCamera(name, position, scene) {
  23992. _super.call(this, name, position, scene);
  23993. this._hmdDevice = null;
  23994. this._sensorDevice = null;
  23995. this._cacheState = null;
  23996. this._cacheQuaternion = new BABYLON.Quaternion();
  23997. this._cacheRotation = BABYLON.Vector3.Zero();
  23998. this._vrEnabled = false;
  23999. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24000. }
  24001. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24002. var size = devices.length;
  24003. var i = 0;
  24004. // Reset devices.
  24005. this._sensorDevice = null;
  24006. this._hmdDevice = null;
  24007. while (i < size && this._hmdDevice === null) {
  24008. if (devices[i] instanceof HMDVRDevice) {
  24009. this._hmdDevice = devices[i];
  24010. }
  24011. i++;
  24012. }
  24013. i = 0;
  24014. while (i < size && this._sensorDevice === null) {
  24015. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24016. this._sensorDevice = devices[i];
  24017. }
  24018. i++;
  24019. }
  24020. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24021. };
  24022. WebVRCamera.prototype._update = function () {
  24023. if (this._vrEnabled) {
  24024. this._cacheState = this._sensorDevice.getState();
  24025. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24026. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24027. this.rotation.x = -this._cacheRotation.z;
  24028. this.rotation.y = -this._cacheRotation.y;
  24029. this.rotation.z = this._cacheRotation.x;
  24030. }
  24031. _super.prototype._update.call(this);
  24032. };
  24033. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24034. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24035. if (navigator.getVRDevices) {
  24036. navigator.getVRDevices().then(this._getWebVRDevices);
  24037. } else if (navigator.mozGetVRDevices) {
  24038. navigator.mozGetVRDevices(this._getWebVRDevices);
  24039. }
  24040. };
  24041. WebVRCamera.prototype.detachControl = function (element) {
  24042. _super.prototype.detachControl.call(this, element);
  24043. this._vrEnabled = false;
  24044. };
  24045. return WebVRCamera;
  24046. })(BABYLON.OculusCamera);
  24047. BABYLON.WebVRCamera = WebVRCamera;
  24048. })(BABYLON || (BABYLON = {}));
  24049. //# sourceMappingURL=babylon.webVRCamera.js.map
  24050. var BABYLON;
  24051. (function (BABYLON) {
  24052. // Standard optimizations
  24053. var SceneOptimization = (function () {
  24054. function SceneOptimization(priority) {
  24055. if (typeof priority === "undefined") { priority = 0; }
  24056. this.priority = priority;
  24057. this.apply = function (scene) {
  24058. return true;
  24059. };
  24060. }
  24061. return SceneOptimization;
  24062. })();
  24063. BABYLON.SceneOptimization = SceneOptimization;
  24064. var TextureOptimization = (function (_super) {
  24065. __extends(TextureOptimization, _super);
  24066. function TextureOptimization(priority, maximumSize) {
  24067. if (typeof priority === "undefined") { priority = 0; }
  24068. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  24069. var _this = this;
  24070. _super.call(this, priority);
  24071. this.priority = priority;
  24072. this.maximumSize = maximumSize;
  24073. this.apply = function (scene) {
  24074. var allDone = true;
  24075. for (var index = 0; index < scene.textures.length; index++) {
  24076. var texture = scene.textures[index];
  24077. if (!texture.canRescale) {
  24078. continue;
  24079. }
  24080. var currentSize = texture.getSize();
  24081. var maxDimension = Math.max(currentSize.width, currentSize.height);
  24082. if (maxDimension > _this.maximumSize) {
  24083. texture.scale(0.5);
  24084. allDone = false;
  24085. }
  24086. }
  24087. return allDone;
  24088. };
  24089. }
  24090. return TextureOptimization;
  24091. })(SceneOptimization);
  24092. BABYLON.TextureOptimization = TextureOptimization;
  24093. var HardwareScalingOptimization = (function (_super) {
  24094. __extends(HardwareScalingOptimization, _super);
  24095. function HardwareScalingOptimization(priority, maximumScale) {
  24096. if (typeof priority === "undefined") { priority = 0; }
  24097. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  24098. var _this = this;
  24099. _super.call(this, priority);
  24100. this.priority = priority;
  24101. this.maximumScale = maximumScale;
  24102. this._currentScale = 1;
  24103. this.apply = function (scene) {
  24104. _this._currentScale++;
  24105. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  24106. return _this._currentScale >= _this.maximumScale;
  24107. };
  24108. }
  24109. return HardwareScalingOptimization;
  24110. })(SceneOptimization);
  24111. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  24112. var ShadowsOptimization = (function (_super) {
  24113. __extends(ShadowsOptimization, _super);
  24114. function ShadowsOptimization() {
  24115. _super.apply(this, arguments);
  24116. this.apply = function (scene) {
  24117. scene.shadowsEnabled = false;
  24118. return true;
  24119. };
  24120. }
  24121. return ShadowsOptimization;
  24122. })(SceneOptimization);
  24123. BABYLON.ShadowsOptimization = ShadowsOptimization;
  24124. var PostProcessesOptimization = (function (_super) {
  24125. __extends(PostProcessesOptimization, _super);
  24126. function PostProcessesOptimization() {
  24127. _super.apply(this, arguments);
  24128. this.apply = function (scene) {
  24129. scene.postProcessesEnabled = false;
  24130. return true;
  24131. };
  24132. }
  24133. return PostProcessesOptimization;
  24134. })(SceneOptimization);
  24135. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  24136. var LensFlaresOptimization = (function (_super) {
  24137. __extends(LensFlaresOptimization, _super);
  24138. function LensFlaresOptimization() {
  24139. _super.apply(this, arguments);
  24140. this.apply = function (scene) {
  24141. scene.lensFlaresEnabled = false;
  24142. return true;
  24143. };
  24144. }
  24145. return LensFlaresOptimization;
  24146. })(SceneOptimization);
  24147. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  24148. var ParticlesOptimization = (function (_super) {
  24149. __extends(ParticlesOptimization, _super);
  24150. function ParticlesOptimization() {
  24151. _super.apply(this, arguments);
  24152. this.apply = function (scene) {
  24153. scene.particlesEnabled = false;
  24154. return true;
  24155. };
  24156. }
  24157. return ParticlesOptimization;
  24158. })(SceneOptimization);
  24159. BABYLON.ParticlesOptimization = ParticlesOptimization;
  24160. var RenderTargetsOptimization = (function (_super) {
  24161. __extends(RenderTargetsOptimization, _super);
  24162. function RenderTargetsOptimization() {
  24163. _super.apply(this, arguments);
  24164. this.apply = function (scene) {
  24165. scene.renderTargetsEnabled = false;
  24166. return true;
  24167. };
  24168. }
  24169. return RenderTargetsOptimization;
  24170. })(SceneOptimization);
  24171. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  24172. var MergeMeshesOptimization = (function (_super) {
  24173. __extends(MergeMeshesOptimization, _super);
  24174. function MergeMeshesOptimization() {
  24175. _super.apply(this, arguments);
  24176. var _this = this;
  24177. this._canBeMerged = function (abstractMesh) {
  24178. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  24179. return false;
  24180. }
  24181. var mesh = abstractMesh;
  24182. if (!mesh.isVisible || !mesh.isEnabled()) {
  24183. return false;
  24184. }
  24185. if (mesh.instances.length > 0) {
  24186. return false;
  24187. }
  24188. if (mesh.skeleton || mesh.hasLODLevels) {
  24189. return false;
  24190. }
  24191. return true;
  24192. };
  24193. this.apply = function (scene) {
  24194. var globalPool = scene.meshes.slice(0);
  24195. var globalLength = globalPool.length;
  24196. for (var index = 0; index < globalLength; index++) {
  24197. var currentPool = new Array();
  24198. var current = globalPool[index];
  24199. // Checks
  24200. if (!_this._canBeMerged(current)) {
  24201. continue;
  24202. }
  24203. currentPool.push(current);
  24204. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  24205. var otherMesh = globalPool[subIndex];
  24206. if (!_this._canBeMerged(otherMesh)) {
  24207. continue;
  24208. }
  24209. if (otherMesh.material !== current.material) {
  24210. continue;
  24211. }
  24212. if (otherMesh.checkCollisions !== current.checkCollisions) {
  24213. continue;
  24214. }
  24215. currentPool.push(otherMesh);
  24216. globalLength--;
  24217. globalPool.splice(subIndex, 1);
  24218. subIndex--;
  24219. }
  24220. if (currentPool.length < 2) {
  24221. continue;
  24222. }
  24223. // Merge meshes
  24224. BABYLON.Mesh.MergeMeshes(currentPool);
  24225. }
  24226. return true;
  24227. };
  24228. }
  24229. return MergeMeshesOptimization;
  24230. })(SceneOptimization);
  24231. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  24232. // Options
  24233. var SceneOptimizerOptions = (function () {
  24234. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  24235. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  24236. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  24237. this.targetFrameRate = targetFrameRate;
  24238. this.trackerDuration = trackerDuration;
  24239. this.optimizations = new Array();
  24240. }
  24241. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  24242. var result = new SceneOptimizerOptions(targetFrameRate);
  24243. var priority = 0;
  24244. result.optimizations.push(new MergeMeshesOptimization(priority));
  24245. result.optimizations.push(new ShadowsOptimization(priority));
  24246. result.optimizations.push(new LensFlaresOptimization(priority));
  24247. // Next priority
  24248. priority++;
  24249. result.optimizations.push(new PostProcessesOptimization(priority));
  24250. result.optimizations.push(new ParticlesOptimization(priority));
  24251. // Next priority
  24252. priority++;
  24253. result.optimizations.push(new TextureOptimization(priority, 1024));
  24254. return result;
  24255. };
  24256. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24257. var result = new SceneOptimizerOptions(targetFrameRate);
  24258. var priority = 0;
  24259. result.optimizations.push(new MergeMeshesOptimization(priority));
  24260. result.optimizations.push(new ShadowsOptimization(priority));
  24261. result.optimizations.push(new LensFlaresOptimization(priority));
  24262. // Next priority
  24263. priority++;
  24264. result.optimizations.push(new PostProcessesOptimization(priority));
  24265. result.optimizations.push(new ParticlesOptimization(priority));
  24266. // Next priority
  24267. priority++;
  24268. result.optimizations.push(new TextureOptimization(priority, 512));
  24269. // Next priority
  24270. priority++;
  24271. result.optimizations.push(new RenderTargetsOptimization(priority));
  24272. // Next priority
  24273. priority++;
  24274. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24275. return result;
  24276. };
  24277. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24278. var result = new SceneOptimizerOptions(targetFrameRate);
  24279. var priority = 0;
  24280. result.optimizations.push(new MergeMeshesOptimization(priority));
  24281. result.optimizations.push(new ShadowsOptimization(priority));
  24282. result.optimizations.push(new LensFlaresOptimization(priority));
  24283. // Next priority
  24284. priority++;
  24285. result.optimizations.push(new PostProcessesOptimization(priority));
  24286. result.optimizations.push(new ParticlesOptimization(priority));
  24287. // Next priority
  24288. priority++;
  24289. result.optimizations.push(new TextureOptimization(priority, 256));
  24290. // Next priority
  24291. priority++;
  24292. result.optimizations.push(new RenderTargetsOptimization(priority));
  24293. // Next priority
  24294. priority++;
  24295. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24296. return result;
  24297. };
  24298. return SceneOptimizerOptions;
  24299. })();
  24300. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24301. // Scene optimizer tool
  24302. var SceneOptimizer = (function () {
  24303. function SceneOptimizer() {
  24304. }
  24305. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24306. // TODO: add an epsilon
  24307. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24308. if (onSuccess) {
  24309. onSuccess();
  24310. }
  24311. return;
  24312. }
  24313. // Apply current level of optimizations
  24314. var allDone = true;
  24315. var noOptimizationApplied = true;
  24316. for (var index = 0; index < options.optimizations.length; index++) {
  24317. var optimization = options.optimizations[index];
  24318. if (optimization.priority === currentPriorityLevel) {
  24319. noOptimizationApplied = false;
  24320. allDone = allDone && optimization.apply(scene);
  24321. }
  24322. }
  24323. // If no optimization was applied, this is a failure :(
  24324. if (noOptimizationApplied) {
  24325. if (onFailure) {
  24326. onFailure();
  24327. }
  24328. return;
  24329. }
  24330. // If all optimizations were done, move to next level
  24331. if (allDone) {
  24332. currentPriorityLevel++;
  24333. }
  24334. // Let's the system running for a specific amount of time before checking FPS
  24335. scene.executeWhenReady(function () {
  24336. setTimeout(function () {
  24337. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24338. }, options.trackerDuration);
  24339. });
  24340. };
  24341. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24342. if (!options) {
  24343. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24344. }
  24345. // Let's the system running for a specific amount of time before checking FPS
  24346. scene.executeWhenReady(function () {
  24347. setTimeout(function () {
  24348. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24349. }, options.trackerDuration);
  24350. });
  24351. };
  24352. return SceneOptimizer;
  24353. })();
  24354. BABYLON.SceneOptimizer = SceneOptimizer;
  24355. })(BABYLON || (BABYLON = {}));
  24356. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24357. var BABYLON;
  24358. (function (BABYLON) {
  24359. (function (Internals) {
  24360. var MeshLODLevel = (function () {
  24361. function MeshLODLevel(distance, mesh) {
  24362. this.distance = distance;
  24363. this.mesh = mesh;
  24364. }
  24365. return MeshLODLevel;
  24366. })();
  24367. Internals.MeshLODLevel = MeshLODLevel;
  24368. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24369. var Internals = BABYLON.Internals;
  24370. })(BABYLON || (BABYLON = {}));
  24371. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24372. var BABYLON;
  24373. (function (BABYLON) {
  24374. var AudioEngine = (function () {
  24375. function AudioEngine() {
  24376. this.audioContext = null;
  24377. this.canUseWebAudio = false;
  24378. try {
  24379. if (typeof AudioContext !== 'undefined') {
  24380. this.audioContext = new AudioContext();
  24381. this.canUseWebAudio = true;
  24382. } else if (typeof webkitAudioContext !== 'undefined') {
  24383. this.audioContext = new webkitAudioContext();
  24384. this.canUseWebAudio = true;
  24385. }
  24386. } catch (e) {
  24387. this.canUseWebAudio = false;
  24388. }
  24389. // create a global volume gain node
  24390. if (this.canUseWebAudio) {
  24391. this.masterGain = this.audioContext.createGain();
  24392. this.masterGain.gain.value = 1;
  24393. this.masterGain.connect(this.audioContext.destination);
  24394. }
  24395. }
  24396. AudioEngine.prototype.getGlobalVolume = function () {
  24397. if (this.canUseWebAudio) {
  24398. return this.masterGain.gain.value;
  24399. } else {
  24400. return -1;
  24401. }
  24402. };
  24403. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24404. if (this.canUseWebAudio) {
  24405. this.masterGain.gain.value = newVolume;
  24406. }
  24407. };
  24408. return AudioEngine;
  24409. })();
  24410. BABYLON.AudioEngine = AudioEngine;
  24411. })(BABYLON || (BABYLON = {}));
  24412. //# sourceMappingURL=babylon.audioengine.js.map
  24413. var BABYLON;
  24414. (function (BABYLON) {
  24415. var Sound = (function () {
  24416. /**
  24417. * Create a sound and attach it to a scene
  24418. * @param name Name of your sound
  24419. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  24420. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24421. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  24422. */
  24423. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  24424. var _this = this;
  24425. this.autoplay = false;
  24426. this.loop = false;
  24427. this.useCustomAttenuation = false;
  24428. this.spatialSound = false;
  24429. this.refDistance = 1;
  24430. this.rolloffFactor = 1;
  24431. this.maxDistance = 100;
  24432. this.distanceModel = "linear";
  24433. this.panningModel = "HRTF";
  24434. this.startTime = 0;
  24435. this.startOffset = 0;
  24436. this._position = BABYLON.Vector3.Zero();
  24437. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24438. this._volume = 1;
  24439. this._isLoaded = false;
  24440. this._isReadyToPlay = false;
  24441. this._isPlaying = false;
  24442. this._isDirectional = false;
  24443. // Used if you'd like to create a directional sound.
  24444. // If not set, the sound will be omnidirectional
  24445. this._coneInnerAngle = 360;
  24446. this._coneOuterAngle = 360;
  24447. this._coneOuterGain = 0;
  24448. this._name = name;
  24449. this._scene = scene;
  24450. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24451. this._readyToPlayCallback = readyToPlayCallback;
  24452. // Default custom attenuation function is a linear attenuation
  24453. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  24454. if (currentDistance < maxDistance) {
  24455. return currentVolume * (1 - currentDistance / maxDistance);
  24456. } else {
  24457. return 0;
  24458. }
  24459. };
  24460. if (options) {
  24461. this.autoplay = options.autoplay || false;
  24462. this.loop = options.loop || false;
  24463. this._volume = options.volume || 1;
  24464. this.spatialSound = options.spatialSound || false;
  24465. this.maxDistance = options.maxDistance || 100;
  24466. this.useCustomAttenuation = options.useCustomAttenation || false;
  24467. this.rolloffFactor = options.rolloffFactor || 1;
  24468. this.refDistance = options.refDistance || 1;
  24469. this.distanceModel = options.distanceModel || "linear";
  24470. this.panningModel = options.panningModel || "HRTF";
  24471. }
  24472. if (this._audioEngine.canUseWebAudio) {
  24473. this._soundGain = this._audioEngine.audioContext.createGain();
  24474. this._soundGain.gain.value = this._volume;
  24475. if (this.spatialSound) {
  24476. this._createSpatialParameters();
  24477. } else {
  24478. this._audioNode = this._soundGain;
  24479. }
  24480. this._scene.mainSoundTrack.AddSound(this);
  24481. if (typeof (urlOrArrayBuffer) === "string") {
  24482. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  24483. _this._soundLoaded(data);
  24484. }, null, null, true);
  24485. } else {
  24486. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  24487. this._soundLoaded(urlOrArrayBuffer);
  24488. } else {
  24489. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  24490. }
  24491. }
  24492. }
  24493. }
  24494. Sound.prototype.updateOptions = function (options) {
  24495. if (options) {
  24496. this.loop = options.loop || this.loop;
  24497. this.maxDistance = options.maxDistance || this.maxDistance;
  24498. this.useCustomAttenuation = options.useCustomAttenation || this.useCustomAttenuation;
  24499. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  24500. this.refDistance = options.refDistance || this.refDistance;
  24501. this.distanceModel = options.distanceModel || this.distanceModel;
  24502. this.panningModel = options.panningModel || this.panningModel;
  24503. }
  24504. };
  24505. Sound.prototype._createSpatialParameters = function () {
  24506. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24507. if (this.useCustomAttenuation) {
  24508. // Tricks to disable in a way embedded Web Audio attenuation
  24509. this._soundPanner.distanceModel = "linear";
  24510. this._soundPanner.maxDistance = Number.MAX_VALUE;
  24511. this._soundPanner.refDistance = 1;
  24512. this._soundPanner.rolloffFactor = 1;
  24513. this._soundPanner.panningModel = "HRTF";
  24514. } else {
  24515. this._soundPanner.distanceModel = this.distanceModel;
  24516. this._soundPanner.maxDistance = this.maxDistance;
  24517. this._soundPanner.refDistance = this.refDistance;
  24518. this._soundPanner.rolloffFactor = this.rolloffFactor;
  24519. this._soundPanner.panningModel = this.panningModel;
  24520. }
  24521. this._soundPanner.connect(this._soundGain);
  24522. this._audioNode = this._soundPanner;
  24523. };
  24524. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24525. if (this._audioEngine.canUseWebAudio) {
  24526. this._audioNode.disconnect();
  24527. this._audioNode.connect(soundTrackAudioNode);
  24528. }
  24529. };
  24530. /**
  24531. * Transform this sound into a directional source
  24532. * @param coneInnerAngle Size of the inner cone in degree
  24533. * @param coneOuterAngle Size of the outer cone in degree
  24534. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24535. */
  24536. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24537. if (coneOuterAngle < coneInnerAngle) {
  24538. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24539. return;
  24540. }
  24541. this._coneInnerAngle = coneInnerAngle;
  24542. this._coneOuterAngle = coneOuterAngle;
  24543. this._coneOuterGain = coneOuterGain;
  24544. this._isDirectional = true;
  24545. if (this._isPlaying && this.loop) {
  24546. this.stop();
  24547. this.play();
  24548. }
  24549. };
  24550. Sound.prototype.setPosition = function (newPosition) {
  24551. this._position = newPosition;
  24552. if (this._isPlaying && this.spatialSound) {
  24553. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24554. }
  24555. };
  24556. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24557. this._localDirection = newLocalDirection;
  24558. if (this._connectedMesh && this._isPlaying) {
  24559. this._updateDirection();
  24560. }
  24561. };
  24562. Sound.prototype._updateDirection = function () {
  24563. var mat = this._connectedMesh.getWorldMatrix();
  24564. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24565. direction.normalize();
  24566. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24567. };
  24568. Sound.prototype.updateDistanceFromListener = function () {
  24569. if (this._connectedMesh && this.useCustomAttenuation) {
  24570. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24571. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  24572. }
  24573. };
  24574. Sound.prototype.setAttenuationFunction = function (callback) {
  24575. this._customAttenuationFunction = callback;
  24576. };
  24577. /**
  24578. * Play the sound
  24579. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24580. */
  24581. Sound.prototype.play = function (time) {
  24582. if (this._isReadyToPlay) {
  24583. try {
  24584. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24585. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24586. this._soundSource.buffer = this._audioBuffer;
  24587. if (this.spatialSound) {
  24588. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24589. if (this._isDirectional) {
  24590. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24591. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24592. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24593. if (this._connectedMesh) {
  24594. this._updateDirection();
  24595. } else {
  24596. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24597. }
  24598. }
  24599. }
  24600. this._soundSource.connect(this._audioNode);
  24601. this._soundSource.loop = this.loop;
  24602. this.startTime = startTime;
  24603. this._soundSource.start(startTime, this.startOffset % this._soundSource.buffer.duration);
  24604. this._isPlaying = true;
  24605. } catch (ex) {
  24606. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24607. }
  24608. }
  24609. };
  24610. /**
  24611. * Stop the sound
  24612. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24613. */
  24614. Sound.prototype.stop = function (time) {
  24615. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24616. this._soundSource.stop(stopTime);
  24617. this._isPlaying = false;
  24618. };
  24619. Sound.prototype.pause = function () {
  24620. this._soundSource.stop(0);
  24621. this.startOffset += this._audioEngine.audioContext.currentTime - this.startTime;
  24622. };
  24623. Sound.prototype.setVolume = function (newVolume) {
  24624. this._volume = newVolume;
  24625. this._soundGain.gain.value = newVolume;
  24626. };
  24627. Sound.prototype.getVolume = function () {
  24628. return this._volume;
  24629. };
  24630. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24631. var _this = this;
  24632. this._connectedMesh = meshToConnectTo;
  24633. if (!this.spatialSound) {
  24634. this._createSpatialParameters();
  24635. this.spatialSound = true;
  24636. if (this._isPlaying && this.loop) {
  24637. this.stop();
  24638. this.play();
  24639. }
  24640. }
  24641. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24642. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24643. });
  24644. };
  24645. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24646. this.setPosition(connectedMesh.position);
  24647. if (this._isDirectional && this._isPlaying) {
  24648. this._updateDirection();
  24649. }
  24650. };
  24651. Sound.prototype._soundLoaded = function (audioData) {
  24652. var _this = this;
  24653. this._isLoaded = true;
  24654. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24655. _this._audioBuffer = buffer;
  24656. _this._isReadyToPlay = true;
  24657. if (_this.autoplay) {
  24658. _this.play();
  24659. }
  24660. if (_this._readyToPlayCallback) {
  24661. _this._readyToPlayCallback();
  24662. }
  24663. }, function (error) {
  24664. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24665. });
  24666. };
  24667. return Sound;
  24668. })();
  24669. BABYLON.Sound = Sound;
  24670. })(BABYLON || (BABYLON = {}));
  24671. //# sourceMappingURL=babylon.sound.js.map
  24672. var BABYLON;
  24673. (function (BABYLON) {
  24674. var SoundTrack = (function () {
  24675. function SoundTrack(scene, options) {
  24676. this.id = -1;
  24677. this._isMainTrack = false;
  24678. this._scene = scene;
  24679. this._audioEngine = scene.getEngine().getAudioEngine();
  24680. this.soundCollection = new Array();
  24681. if (this._audioEngine.canUseWebAudio) {
  24682. this._trackGain = this._audioEngine.audioContext.createGain();
  24683. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24684. //this._trackConvolver.connect(this._trackGain);
  24685. this._trackGain.connect(this._audioEngine.masterGain);
  24686. if (options) {
  24687. if (options.volume) {
  24688. this._trackGain.gain.value = options.volume;
  24689. }
  24690. if (options.mainTrack) {
  24691. this._isMainTrack = options.mainTrack;
  24692. }
  24693. }
  24694. }
  24695. if (!this._isMainTrack) {
  24696. this._scene.soundTracks.push(this);
  24697. this.id = this._scene.soundTracks.length - 1;
  24698. }
  24699. }
  24700. SoundTrack.prototype.AddSound = function (sound) {
  24701. sound.connectToSoundTrackAudioNode(this._trackGain);
  24702. if (sound.soundTrackId) {
  24703. if (sound.soundTrackId === -1) {
  24704. this._scene.mainSoundTrack.RemoveSound(sound);
  24705. } else {
  24706. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24707. }
  24708. }
  24709. this.soundCollection.push(sound);
  24710. sound.soundTrackId = this.id;
  24711. };
  24712. SoundTrack.prototype.RemoveSound = function (sound) {
  24713. var index = this.soundCollection.indexOf(sound);
  24714. if (index !== -1) {
  24715. this.soundCollection.splice(index, 1);
  24716. }
  24717. };
  24718. SoundTrack.prototype.setVolume = function (newVolume) {
  24719. if (this._audioEngine.canUseWebAudio) {
  24720. this._trackGain.gain.value = newVolume;
  24721. }
  24722. };
  24723. return SoundTrack;
  24724. })();
  24725. BABYLON.SoundTrack = SoundTrack;
  24726. })(BABYLON || (BABYLON = {}));
  24727. //# sourceMappingURL=babylon.soundtrack.js.map
  24728. var BABYLON;
  24729. (function (BABYLON) {
  24730. var DebugLayer = (function () {
  24731. function DebugLayer(scene) {
  24732. var _this = this;
  24733. this._enabled = false;
  24734. this._labelsEnabled = false;
  24735. this._displayStatistics = true;
  24736. this._displayTree = false;
  24737. this._displayLogs = false;
  24738. this._identityMatrix = BABYLON.Matrix.Identity();
  24739. this.axisRatio = 0.02;
  24740. this.accentColor = "orange";
  24741. this._scene = scene;
  24742. this._syncPositions = function () {
  24743. var engine = _this._scene.getEngine();
  24744. var canvasRect = engine.getRenderingCanvasClientRect();
  24745. if (_this._showUI) {
  24746. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  24747. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  24748. _this._statsDiv.style.width = "400px";
  24749. _this._statsDiv.style.height = "auto";
  24750. _this._statsSubsetDiv.style.maxHeight = "240px";
  24751. _this._optionsDiv.style.left = "0px";
  24752. _this._optionsDiv.style.top = "10px";
  24753. _this._optionsDiv.style.width = "200px";
  24754. _this._optionsDiv.style.height = "auto";
  24755. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24756. _this._logDiv.style.left = "0px";
  24757. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24758. _this._logDiv.style.width = "600px";
  24759. _this._logDiv.style.height = "160px";
  24760. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24761. _this._treeDiv.style.top = "10px";
  24762. _this._treeDiv.style.width = "300px";
  24763. _this._treeDiv.style.height = "auto";
  24764. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  24765. }
  24766. _this._globalDiv.style.left = canvasRect.left + "px";
  24767. _this._globalDiv.style.top = canvasRect.top + "px";
  24768. _this._drawingCanvas.style.left = "0px";
  24769. _this._drawingCanvas.style.top = "0px";
  24770. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24771. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24772. var devicePixelRatio = window.devicePixelRatio || 1;
  24773. var context = _this._drawingContext;
  24774. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24775. _this._ratio = devicePixelRatio / backingStoreRatio;
  24776. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24777. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24778. };
  24779. this._onCanvasClick = function (evt) {
  24780. _this._clickPosition = {
  24781. x: evt.clientX * _this._ratio,
  24782. y: evt.clientY * _this._ratio
  24783. };
  24784. };
  24785. this._syncData = function () {
  24786. if (_this._showUI) {
  24787. if (_this._displayStatistics) {
  24788. _this._displayStats();
  24789. _this._statsDiv.style.display = "";
  24790. } else {
  24791. _this._statsDiv.style.display = "none";
  24792. }
  24793. if (_this._displayLogs) {
  24794. _this._logDiv.style.display = "";
  24795. } else {
  24796. _this._logDiv.style.display = "none";
  24797. }
  24798. if (_this._displayTree) {
  24799. _this._treeDiv.style.display = "";
  24800. if (_this._needToRefreshMeshesTree) {
  24801. _this._needToRefreshMeshesTree = false;
  24802. _this._refreshMeshesTreeContent();
  24803. }
  24804. } else {
  24805. _this._treeDiv.style.display = "none";
  24806. }
  24807. }
  24808. if (_this._labelsEnabled || !_this._showUI) {
  24809. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  24810. var engine = _this._scene.getEngine();
  24811. var viewport = _this._scene.activeCamera.viewport;
  24812. var globalViewport = viewport.toGlobal(engine);
  24813. // Meshes
  24814. var meshes = _this._scene.getActiveMeshes();
  24815. for (var index = 0; index < meshes.length; index++) {
  24816. var mesh = meshes.data[index];
  24817. var position = mesh.getBoundingInfo().boundingSphere.center;
  24818. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24819. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  24820. _this._renderAxis(projectedPosition, mesh, globalViewport);
  24821. }
  24822. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  24823. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  24824. mesh.renderOverlay = !mesh.renderOverlay;
  24825. }, function () {
  24826. return mesh.renderOverlay ? 'red' : 'black';
  24827. });
  24828. }
  24829. }
  24830. // Cameras
  24831. var cameras = _this._scene.cameras;
  24832. for (index = 0; index < cameras.length; index++) {
  24833. var camera = cameras[index];
  24834. if (camera === _this._scene.activeCamera) {
  24835. continue;
  24836. }
  24837. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24838. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  24839. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  24840. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  24841. _this._scene.activeCamera = camera;
  24842. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  24843. }, function () {
  24844. return "purple";
  24845. });
  24846. }
  24847. }
  24848. // Lights
  24849. var lights = _this._scene.lights;
  24850. for (index = 0; index < lights.length; index++) {
  24851. var light = lights[index];
  24852. if (light.position) {
  24853. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  24854. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  24855. _this._renderLabel(light.name, projectedPosition, -20, function () {
  24856. light.setEnabled(!light.isEnabled());
  24857. }, function () {
  24858. return light.isEnabled() ? "orange" : "gray";
  24859. });
  24860. }
  24861. }
  24862. }
  24863. }
  24864. _this._clickPosition = undefined;
  24865. };
  24866. }
  24867. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  24868. while (this._treeSubsetDiv.hasChildNodes()) {
  24869. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  24870. }
  24871. // Add meshes
  24872. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  24873. sortedArray.sort(function (a, b) {
  24874. if (a.name === b.name) {
  24875. return 0;
  24876. }
  24877. return (a.name > b.name) ? 1 : -1;
  24878. });
  24879. for (var index = 0; index < sortedArray.length; index++) {
  24880. var mesh = sortedArray[index];
  24881. if (!mesh.isEnabled()) {
  24882. continue;
  24883. }
  24884. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  24885. m.isVisible = element.checked;
  24886. }, mesh);
  24887. }
  24888. };
  24889. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  24890. this._drawingContext.beginPath();
  24891. this._drawingContext.moveTo(zero.x, zero.y);
  24892. this._drawingContext.lineTo(unit.x, unit.y);
  24893. this._drawingContext.strokeStyle = color;
  24894. this._drawingContext.lineWidth = 4;
  24895. this._drawingContext.stroke();
  24896. this._drawingContext.font = "normal 14px Segoe UI";
  24897. this._drawingContext.fillStyle = color;
  24898. this._drawingContext.fillText(label, unitText.x, unitText.y);
  24899. };
  24900. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  24901. var position = mesh.getBoundingInfo().boundingSphere.center;
  24902. var worldMatrix = mesh.getWorldMatrix();
  24903. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  24904. var unit = (unprojectedVector.subtract(position)).length();
  24905. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24906. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24907. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  24908. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24909. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24910. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  24911. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24912. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24913. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  24914. };
  24915. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  24916. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  24917. this._drawingContext.font = "normal 12px Segoe UI";
  24918. var textMetrics = this._drawingContext.measureText(text);
  24919. var centerX = projectedPosition.x - textMetrics.width / 2;
  24920. var centerY = projectedPosition.y;
  24921. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  24922. onClick();
  24923. }
  24924. this._drawingContext.beginPath();
  24925. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  24926. this._drawingContext.fillStyle = getFillStyle();
  24927. this._drawingContext.globalAlpha = 0.5;
  24928. this._drawingContext.fill();
  24929. this._drawingContext.globalAlpha = 1.0;
  24930. this._drawingContext.strokeStyle = '#FFFFFF';
  24931. this._drawingContext.lineWidth = 1;
  24932. this._drawingContext.stroke();
  24933. this._drawingContext.fillStyle = "#FFFFFF";
  24934. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  24935. this._drawingContext.beginPath();
  24936. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  24937. this._drawingContext.fill();
  24938. }
  24939. };
  24940. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  24941. if (!this._clickPosition) {
  24942. return false;
  24943. }
  24944. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  24945. return false;
  24946. }
  24947. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  24948. return false;
  24949. }
  24950. return true;
  24951. };
  24952. DebugLayer.prototype.isVisible = function () {
  24953. return this._enabled;
  24954. };
  24955. DebugLayer.prototype.hide = function () {
  24956. if (!this._enabled) {
  24957. return;
  24958. }
  24959. this._enabled = false;
  24960. var engine = this._scene.getEngine();
  24961. this._scene.unregisterAfterRender(this._syncData);
  24962. document.body.removeChild(this._globalDiv);
  24963. window.removeEventListener("resize", this._syncPositions);
  24964. this._scene.forceShowBoundingBoxes = false;
  24965. this._scene.forceWireframe = false;
  24966. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  24967. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  24968. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  24969. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  24970. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  24971. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  24972. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  24973. this._scene.shadowsEnabled = true;
  24974. this._scene.particlesEnabled = true;
  24975. this._scene.postProcessesEnabled = true;
  24976. this._scene.collisionsEnabled = true;
  24977. this._scene.lightsEnabled = true;
  24978. this._scene.texturesEnabled = true;
  24979. this._scene.lensFlaresEnabled = true;
  24980. this._scene.proceduralTexturesEnabled = true;
  24981. this._scene.renderTargetsEnabled = true;
  24982. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  24983. };
  24984. DebugLayer.prototype.show = function (showUI) {
  24985. if (typeof showUI === "undefined") { showUI = true; }
  24986. if (this._enabled) {
  24987. return;
  24988. }
  24989. this._enabled = true;
  24990. this._showUI = showUI;
  24991. var engine = this._scene.getEngine();
  24992. this._globalDiv = document.createElement("div");
  24993. document.body.appendChild(this._globalDiv);
  24994. this._generateDOMelements();
  24995. window.addEventListener("resize", this._syncPositions);
  24996. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  24997. this._syncPositions();
  24998. this._scene.registerAfterRender(this._syncData);
  24999. };
  25000. DebugLayer.prototype._clearLabels = function () {
  25001. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  25002. for (var index = 0; index < this._scene.meshes.length; index++) {
  25003. var mesh = this._scene.meshes[index];
  25004. mesh.renderOverlay = false;
  25005. }
  25006. };
  25007. DebugLayer.prototype._generateheader = function (root, text) {
  25008. var header = document.createElement("div");
  25009. header.innerHTML = text + "&nbsp;";
  25010. header.style.textAlign = "right";
  25011. header.style.width = "100%";
  25012. header.style.color = "white";
  25013. header.style.backgroundColor = "Black";
  25014. header.style.padding = "5px 5px 4px 0px";
  25015. header.style.marginLeft = "-5px";
  25016. header.style.fontWeight = "bold";
  25017. root.appendChild(header);
  25018. };
  25019. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  25020. var label = document.createElement("label");
  25021. label.innerHTML = title;
  25022. label.style.color = color;
  25023. root.appendChild(label);
  25024. root.appendChild(document.createElement("br"));
  25025. };
  25026. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  25027. if (typeof tag === "undefined") { tag = null; }
  25028. var label = document.createElement("label");
  25029. var boundingBoxesCheckbox = document.createElement("input");
  25030. boundingBoxesCheckbox.type = "checkbox";
  25031. boundingBoxesCheckbox.checked = initialState;
  25032. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25033. task(evt.target, tag);
  25034. });
  25035. label.appendChild(boundingBoxesCheckbox);
  25036. var container = document.createElement("span");
  25037. var leftPart = document.createElement("span");
  25038. var rightPart = document.createElement("span");
  25039. rightPart.style.cssFloat = "right";
  25040. leftPart.innerHTML = leftTitle;
  25041. rightPart.innerHTML = rightTitle;
  25042. rightPart.style.fontSize = "12px";
  25043. rightPart.style.maxWidth = "200px";
  25044. container.appendChild(leftPart);
  25045. container.appendChild(rightPart);
  25046. label.appendChild(container);
  25047. root.appendChild(label);
  25048. root.appendChild(document.createElement("br"));
  25049. };
  25050. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  25051. if (typeof tag === "undefined") { tag = null; }
  25052. var label = document.createElement("label");
  25053. var boundingBoxesCheckbox = document.createElement("input");
  25054. boundingBoxesCheckbox.type = "checkbox";
  25055. boundingBoxesCheckbox.checked = initialState;
  25056. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25057. task(evt.target, tag);
  25058. });
  25059. label.appendChild(boundingBoxesCheckbox);
  25060. label.appendChild(document.createTextNode(title));
  25061. root.appendChild(label);
  25062. root.appendChild(document.createElement("br"));
  25063. };
  25064. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  25065. if (typeof tag === "undefined") { tag = null; }
  25066. var label = document.createElement("label");
  25067. var boundingBoxesRadio = document.createElement("input");
  25068. boundingBoxesRadio.type = "radio";
  25069. boundingBoxesRadio.name = name;
  25070. boundingBoxesRadio.checked = initialState;
  25071. boundingBoxesRadio.addEventListener("change", function (evt) {
  25072. task(evt.target, tag);
  25073. });
  25074. label.appendChild(boundingBoxesRadio);
  25075. label.appendChild(document.createTextNode(title));
  25076. root.appendChild(label);
  25077. root.appendChild(document.createElement("br"));
  25078. };
  25079. DebugLayer.prototype._generateDOMelements = function () {
  25080. var _this = this;
  25081. this._globalDiv.id = "DebugLayer";
  25082. this._globalDiv.style.position = "absolute";
  25083. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  25084. this._globalDiv.style.fontSize = "14px";
  25085. this._globalDiv.style.color = "white";
  25086. // Drawing canvas
  25087. this._drawingCanvas = document.createElement("canvas");
  25088. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  25089. this._drawingCanvas.style.position = "absolute";
  25090. this._drawingCanvas.style.pointerEvents = "none";
  25091. this._drawingContext = this._drawingCanvas.getContext("2d");
  25092. this._globalDiv.appendChild(this._drawingCanvas);
  25093. if (this._showUI) {
  25094. var background = "rgba(128, 128, 128, 0.4)";
  25095. var border = "rgb(180, 180, 180) solid 1px";
  25096. // Stats
  25097. this._statsDiv = document.createElement("div");
  25098. this._statsDiv.id = "DebugLayerStats";
  25099. this._statsDiv.style.border = border;
  25100. this._statsDiv.style.position = "absolute";
  25101. this._statsDiv.style.background = background;
  25102. this._statsDiv.style.padding = "0px 0px 0px 5px";
  25103. this._generateheader(this._statsDiv, "STATISTICS");
  25104. this._statsSubsetDiv = document.createElement("div");
  25105. this._statsSubsetDiv.style.paddingTop = "5px";
  25106. this._statsSubsetDiv.style.paddingBottom = "5px";
  25107. this._statsSubsetDiv.style.overflowY = "auto";
  25108. this._statsDiv.appendChild(this._statsSubsetDiv);
  25109. // Tree
  25110. this._treeDiv = document.createElement("div");
  25111. this._treeDiv.id = "DebugLayerTree";
  25112. this._treeDiv.style.border = border;
  25113. this._treeDiv.style.position = "absolute";
  25114. this._treeDiv.style.background = background;
  25115. this._treeDiv.style.padding = "0px 0px 0px 5px";
  25116. this._treeDiv.style.display = "none";
  25117. this._generateheader(this._treeDiv, "MESHES TREE");
  25118. this._treeSubsetDiv = document.createElement("div");
  25119. this._treeSubsetDiv.style.paddingTop = "5px";
  25120. this._treeSubsetDiv.style.paddingRight = "5px";
  25121. this._treeSubsetDiv.style.overflowY = "auto";
  25122. this._treeSubsetDiv.style.maxHeight = "300px";
  25123. this._treeDiv.appendChild(this._treeSubsetDiv);
  25124. this._needToRefreshMeshesTree = true;
  25125. // Logs
  25126. this._logDiv = document.createElement("div");
  25127. this._logDiv.style.border = border;
  25128. this._logDiv.id = "DebugLayerLogs";
  25129. this._logDiv.style.position = "absolute";
  25130. this._logDiv.style.background = background;
  25131. this._logDiv.style.padding = "0px 0px 0px 5px";
  25132. this._logDiv.style.display = "none";
  25133. this._generateheader(this._logDiv, "LOGS");
  25134. this._logSubsetDiv = document.createElement("div");
  25135. this._logSubsetDiv.style.height = "127px";
  25136. this._logSubsetDiv.style.paddingTop = "5px";
  25137. this._logSubsetDiv.style.overflowY = "auto";
  25138. this._logSubsetDiv.style.fontSize = "12px";
  25139. this._logSubsetDiv.style.fontFamily = "consolas";
  25140. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  25141. this._logDiv.appendChild(this._logSubsetDiv);
  25142. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  25143. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  25144. };
  25145. // Options
  25146. this._optionsDiv = document.createElement("div");
  25147. this._optionsDiv.id = "DebugLayerOptions";
  25148. this._optionsDiv.style.border = border;
  25149. this._optionsDiv.style.position = "absolute";
  25150. this._optionsDiv.style.background = background;
  25151. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  25152. this._optionsDiv.style.overflowY = "auto";
  25153. this._generateheader(this._optionsDiv, "OPTIONS");
  25154. this._optionsSubsetDiv = document.createElement("div");
  25155. this._optionsSubsetDiv.style.paddingTop = "5px";
  25156. this._optionsSubsetDiv.style.paddingBottom = "5px";
  25157. this._optionsSubsetDiv.style.overflowY = "auto";
  25158. this._optionsSubsetDiv.style.maxHeight = "200px";
  25159. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  25160. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  25161. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  25162. _this._displayStatistics = element.checked;
  25163. });
  25164. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  25165. _this._displayLogs = element.checked;
  25166. });
  25167. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  25168. _this._displayTree = element.checked;
  25169. _this._needToRefreshMeshesTree = true;
  25170. });
  25171. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25172. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  25173. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  25174. _this._scene.forceShowBoundingBoxes = element.checked;
  25175. });
  25176. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  25177. _this._labelsEnabled = element.checked;
  25178. if (!_this._labelsEnabled) {
  25179. _this._clearLabels();
  25180. }
  25181. });
  25182. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  25183. if (element.checked) {
  25184. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  25185. } else {
  25186. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  25187. }
  25188. });
  25189. ;
  25190. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25191. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  25192. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  25193. if (element.checked) {
  25194. _this._scene.forceWireframe = false;
  25195. _this._scene.forcePointsCloud = false;
  25196. }
  25197. });
  25198. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  25199. if (element.checked) {
  25200. _this._scene.forceWireframe = true;
  25201. _this._scene.forcePointsCloud = false;
  25202. }
  25203. });
  25204. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  25205. if (element.checked) {
  25206. _this._scene.forceWireframe = false;
  25207. _this._scene.forcePointsCloud = true;
  25208. }
  25209. });
  25210. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25211. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  25212. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  25213. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  25214. });
  25215. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  25216. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  25217. });
  25218. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  25219. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  25220. });
  25221. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  25222. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  25223. });
  25224. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  25225. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  25226. });
  25227. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  25228. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  25229. });
  25230. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  25231. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  25232. });
  25233. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  25234. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  25235. });
  25236. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25237. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  25238. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  25239. _this._scene.animationsEnabled = element.checked;
  25240. });
  25241. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  25242. _this._scene.collisionsEnabled = element.checked;
  25243. });
  25244. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  25245. _this._scene.fogEnabled = element.checked;
  25246. });
  25247. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  25248. _this._scene.lensFlaresEnabled = element.checked;
  25249. });
  25250. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  25251. _this._scene.lightsEnabled = element.checked;
  25252. });
  25253. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  25254. _this._scene.particlesEnabled = element.checked;
  25255. });
  25256. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  25257. _this._scene.postProcessesEnabled = element.checked;
  25258. });
  25259. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  25260. _this._scene.proceduralTexturesEnabled = element.checked;
  25261. });
  25262. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  25263. _this._scene.renderTargetsEnabled = element.checked;
  25264. });
  25265. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  25266. _this._scene.shadowsEnabled = element.checked;
  25267. });
  25268. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  25269. _this._scene.skeletonsEnabled = element.checked;
  25270. });
  25271. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  25272. _this._scene.texturesEnabled = element.checked;
  25273. });
  25274. this._globalDiv.appendChild(this._statsDiv);
  25275. this._globalDiv.appendChild(this._logDiv);
  25276. this._globalDiv.appendChild(this._optionsDiv);
  25277. this._globalDiv.appendChild(this._treeDiv);
  25278. }
  25279. };
  25280. DebugLayer.prototype._displayStats = function () {
  25281. var scene = this._scene;
  25282. var engine = scene.getEngine();
  25283. var glInfo = engine.getGlInfo();
  25284. 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>";
  25285. if (this.customStatsFunction) {
  25286. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  25287. }
  25288. };
  25289. return DebugLayer;
  25290. })();
  25291. BABYLON.DebugLayer = DebugLayer;
  25292. })(BABYLON || (BABYLON = {}));
  25293. //# sourceMappingURL=babylon.debugLayer.js.map
  25294. var BABYLON;
  25295. (function (BABYLON) {
  25296. var RawTexture = (function (_super) {
  25297. __extends(RawTexture, _super);
  25298. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  25299. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25300. if (typeof invertY === "undefined") { invertY = false; }
  25301. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25302. _super.call(this, null, scene, !generateMipMaps, invertY);
  25303. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  25304. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25305. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25306. }
  25307. // Statics
  25308. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25309. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25310. if (typeof invertY === "undefined") { invertY = false; }
  25311. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25312. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  25313. };
  25314. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25315. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25316. if (typeof invertY === "undefined") { invertY = false; }
  25317. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25318. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25319. };
  25320. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25321. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25322. if (typeof invertY === "undefined") { invertY = false; }
  25323. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25324. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25325. };
  25326. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25327. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25328. if (typeof invertY === "undefined") { invertY = false; }
  25329. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25330. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  25331. };
  25332. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25333. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25334. if (typeof invertY === "undefined") { invertY = false; }
  25335. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25336. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  25337. };
  25338. return RawTexture;
  25339. })(BABYLON.Texture);
  25340. BABYLON.RawTexture = RawTexture;
  25341. })(BABYLON || (BABYLON = {}));
  25342. //# sourceMappingURL=babylon.rawTexture.js.map
  25343. var BABYLON;
  25344. (function (BABYLON) {
  25345. var IndexedVector2 = (function (_super) {
  25346. __extends(IndexedVector2, _super);
  25347. function IndexedVector2(original, index) {
  25348. _super.call(this, original.x, original.y);
  25349. this.index = index;
  25350. }
  25351. return IndexedVector2;
  25352. })(BABYLON.Vector2);
  25353. var PolygonPoints = (function () {
  25354. function PolygonPoints() {
  25355. this.elements = new Array();
  25356. }
  25357. PolygonPoints.prototype.add = function (originalPoints) {
  25358. var _this = this;
  25359. var result = new Array();
  25360. originalPoints.forEach(function (point) {
  25361. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  25362. var newPoint = new IndexedVector2(point, _this.elements.length);
  25363. result.push(newPoint);
  25364. _this.elements.push(newPoint);
  25365. }
  25366. });
  25367. return result;
  25368. };
  25369. PolygonPoints.prototype.computeBounds = function () {
  25370. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25371. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25372. this.elements.forEach(function (point) {
  25373. // x
  25374. if (point.x < lmin.x) {
  25375. lmin.x = point.x;
  25376. } else if (point.x > lmax.x) {
  25377. lmax.x = point.x;
  25378. }
  25379. // y
  25380. if (point.y < lmin.y) {
  25381. lmin.y = point.y;
  25382. } else if (point.y > lmax.y) {
  25383. lmax.y = point.y;
  25384. }
  25385. });
  25386. return {
  25387. min: lmin,
  25388. max: lmax,
  25389. width: lmax.x - lmin.x,
  25390. height: lmax.y - lmin.y
  25391. };
  25392. };
  25393. return PolygonPoints;
  25394. })();
  25395. var Polygon = (function () {
  25396. function Polygon() {
  25397. }
  25398. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  25399. return [
  25400. new BABYLON.Vector2(xmin, ymin),
  25401. new BABYLON.Vector2(xmax, ymin),
  25402. new BABYLON.Vector2(xmax, ymax),
  25403. new BABYLON.Vector2(xmin, ymax)
  25404. ];
  25405. };
  25406. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  25407. if (typeof cx === "undefined") { cx = 0; }
  25408. if (typeof cy === "undefined") { cy = 0; }
  25409. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  25410. var result = new Array();
  25411. var angle = 0;
  25412. var increment = (Math.PI * 2) / numberOfSides;
  25413. for (var i = 0; i < numberOfSides; i++) {
  25414. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25415. angle -= increment;
  25416. }
  25417. return result;
  25418. };
  25419. Polygon.Parse = function (input) {
  25420. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25421. return (!isNaN(val));
  25422. });
  25423. var i, result = [];
  25424. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25425. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25426. }
  25427. return result;
  25428. };
  25429. Polygon.StartingAt = function (x, y) {
  25430. return BABYLON.Path2.StartingAt(x, y);
  25431. };
  25432. return Polygon;
  25433. })();
  25434. BABYLON.Polygon = Polygon;
  25435. var PolygonMeshBuilder = (function () {
  25436. function PolygonMeshBuilder(name, contours, scene) {
  25437. this._points = new PolygonPoints();
  25438. if (!("poly2tri" in window)) {
  25439. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25440. }
  25441. this._name = name;
  25442. this._scene = scene;
  25443. var points;
  25444. if (contours instanceof BABYLON.Path2) {
  25445. points = contours.getPoints();
  25446. } else {
  25447. points = contours;
  25448. }
  25449. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  25450. }
  25451. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25452. this._swctx.addHole(this._points.add(hole));
  25453. return this;
  25454. };
  25455. PolygonMeshBuilder.prototype.build = function (updatable) {
  25456. if (typeof updatable === "undefined") { updatable = false; }
  25457. var result = new BABYLON.Mesh(this._name, this._scene);
  25458. var normals = [];
  25459. var positions = [];
  25460. var uvs = [];
  25461. var bounds = this._points.computeBounds();
  25462. this._points.elements.forEach(function (p) {
  25463. normals.push(0, 1.0, 0);
  25464. positions.push(p.x, 0, p.y);
  25465. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25466. });
  25467. var indices = [];
  25468. this._swctx.triangulate();
  25469. this._swctx.getTriangles().forEach(function (triangle) {
  25470. triangle.getPoints().forEach(function (point) {
  25471. indices.push(point.index);
  25472. });
  25473. });
  25474. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25475. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25476. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25477. result.setIndices(indices);
  25478. return result;
  25479. };
  25480. return PolygonMeshBuilder;
  25481. })();
  25482. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25483. })(BABYLON || (BABYLON = {}));
  25484. //# sourceMappingURL=babylon.polygonMesh.js.map
  25485. var BABYLON;
  25486. (function (BABYLON) {
  25487. var SimplificationSettings = (function () {
  25488. function SimplificationSettings(quality, distance) {
  25489. this.quality = quality;
  25490. this.distance = distance;
  25491. }
  25492. return SimplificationSettings;
  25493. })();
  25494. BABYLON.SimplificationSettings = SimplificationSettings;
  25495. /**
  25496. * The implemented types of simplification.
  25497. * At the moment only Quadratic Error Decimation is implemented.
  25498. */
  25499. (function (SimplificationType) {
  25500. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  25501. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  25502. var SimplificationType = BABYLON.SimplificationType;
  25503. var DecimationTriangle = (function () {
  25504. function DecimationTriangle(vertices) {
  25505. this.vertices = vertices;
  25506. this.error = new Array(4);
  25507. this.deleted = false;
  25508. this.isDirty = false;
  25509. this.borderFactor = 0;
  25510. }
  25511. return DecimationTriangle;
  25512. })();
  25513. BABYLON.DecimationTriangle = DecimationTriangle;
  25514. var DecimationVertex = (function () {
  25515. function DecimationVertex(position, normal, uv, id) {
  25516. this.position = position;
  25517. this.normal = normal;
  25518. this.uv = uv;
  25519. this.id = id;
  25520. this.isBorder = true;
  25521. this.q = new QuadraticMatrix();
  25522. this.triangleCount = 0;
  25523. this.triangleStart = 0;
  25524. }
  25525. return DecimationVertex;
  25526. })();
  25527. BABYLON.DecimationVertex = DecimationVertex;
  25528. var QuadraticMatrix = (function () {
  25529. function QuadraticMatrix(data) {
  25530. this.data = new Array(10);
  25531. for (var i = 0; i < 10; ++i) {
  25532. if (data && data[i]) {
  25533. this.data[i] = data[i];
  25534. } else {
  25535. this.data[i] = 0;
  25536. }
  25537. }
  25538. }
  25539. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  25540. 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];
  25541. return det;
  25542. };
  25543. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  25544. for (var i = 0; i < 10; ++i) {
  25545. this.data[i] += matrix.data[i];
  25546. }
  25547. };
  25548. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  25549. for (var i = 0; i < 10; ++i) {
  25550. this.data[i] += data[i];
  25551. }
  25552. };
  25553. QuadraticMatrix.prototype.add = function (matrix) {
  25554. var m = new QuadraticMatrix();
  25555. for (var i = 0; i < 10; ++i) {
  25556. m.data[i] = this.data[i] + matrix.data[i];
  25557. }
  25558. return m;
  25559. };
  25560. QuadraticMatrix.FromData = function (a, b, c, d) {
  25561. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  25562. };
  25563. //returning an array to avoid garbage collection
  25564. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  25565. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  25566. };
  25567. return QuadraticMatrix;
  25568. })();
  25569. BABYLON.QuadraticMatrix = QuadraticMatrix;
  25570. var Reference = (function () {
  25571. function Reference(vertexId, triangleId) {
  25572. this.vertexId = vertexId;
  25573. this.triangleId = triangleId;
  25574. }
  25575. return Reference;
  25576. })();
  25577. BABYLON.Reference = Reference;
  25578. /**
  25579. * An implementation of the Quadratic Error simplification algorithm.
  25580. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  25581. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  25582. * @author RaananW
  25583. */
  25584. var QuadraticErrorSimplification = (function () {
  25585. function QuadraticErrorSimplification(_mesh) {
  25586. this._mesh = _mesh;
  25587. this.initialised = false;
  25588. this.syncIterations = 5000;
  25589. this.agressiveness = 7;
  25590. this.decimationIterations = 100;
  25591. }
  25592. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  25593. var _this = this;
  25594. this.initWithMesh(this._mesh, function () {
  25595. _this.runDecimation(settings, successCallback);
  25596. });
  25597. };
  25598. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  25599. var _this = this;
  25600. var targetCount = ~~(this.triangles.length * settings.quality);
  25601. var deletedTriangles = 0;
  25602. var triangleCount = this.triangles.length;
  25603. var iterationFunction = function (iteration, callback) {
  25604. setTimeout(function () {
  25605. if (iteration % 5 === 0) {
  25606. _this.updateMesh(iteration === 0);
  25607. }
  25608. for (var i = 0; i < _this.triangles.length; ++i) {
  25609. _this.triangles[i].isDirty = false;
  25610. }
  25611. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.agressiveness);
  25612. var trianglesIterator = function (i) {
  25613. var t = _this.triangles[i];
  25614. if (!t)
  25615. return;
  25616. if (t.error[3] > threshold) {
  25617. return;
  25618. }
  25619. if (t.deleted) {
  25620. return;
  25621. }
  25622. if (t.isDirty) {
  25623. return;
  25624. }
  25625. for (var j = 0; j < 3; ++j) {
  25626. if (t.error[j] < threshold) {
  25627. var deleted0 = [];
  25628. var deleted1 = [];
  25629. var i0 = t.vertices[j];
  25630. var i1 = t.vertices[(j + 1) % 3];
  25631. var v0 = _this.vertices[i0];
  25632. var v1 = _this.vertices[i1];
  25633. if (v0.isBorder !== v1.isBorder)
  25634. continue;
  25635. var p = BABYLON.Vector3.Zero();
  25636. var n = BABYLON.Vector3.Zero();
  25637. var uv = BABYLON.Vector2.Zero();
  25638. _this.calculateError(v0, v1, p, n, uv);
  25639. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor))
  25640. continue;
  25641. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor))
  25642. continue;
  25643. v0.position = p;
  25644. v0.normal = n;
  25645. v0.uv = uv;
  25646. v0.q = v1.q.add(v0.q);
  25647. var tStart = _this.references.length;
  25648. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  25649. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  25650. var tCount = _this.references.length - tStart;
  25651. if (tCount <= v0.triangleCount) {
  25652. if (tCount) {
  25653. for (var c = 0; c < tCount; c++) {
  25654. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  25655. }
  25656. }
  25657. } else {
  25658. v0.triangleStart = tStart;
  25659. }
  25660. v0.triangleCount = tCount;
  25661. break;
  25662. }
  25663. }
  25664. };
  25665. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  25666. return (triangleCount - deletedTriangles <= targetCount);
  25667. });
  25668. }, 0);
  25669. };
  25670. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  25671. if (triangleCount - deletedTriangles <= targetCount)
  25672. loop.breakLoop();
  25673. else {
  25674. iterationFunction(loop.index, function () {
  25675. loop.executeNext();
  25676. });
  25677. }
  25678. }, function () {
  25679. setTimeout(function () {
  25680. successCallback(_this.reconstructMesh());
  25681. }, 0);
  25682. });
  25683. };
  25684. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  25685. var _this = this;
  25686. if (!mesh)
  25687. return;
  25688. this.vertices = [];
  25689. this.triangles = [];
  25690. this._mesh = mesh;
  25691. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25692. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25693. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25694. var indices = mesh.getIndices();
  25695. var vertexInit = function (i) {
  25696. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), BABYLON.Vector2.FromArray(uvs, i * 2), i);
  25697. _this.vertices.push(vertex);
  25698. };
  25699. var totalVertices = mesh.getTotalVertices();
  25700. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  25701. var indicesInit = function (i) {
  25702. var pos = i * 3;
  25703. var i0 = indices[pos + 0];
  25704. var i1 = indices[pos + 1];
  25705. var i2 = indices[pos + 2];
  25706. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  25707. _this.triangles.push(triangle);
  25708. };
  25709. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  25710. _this.init(callback);
  25711. });
  25712. });
  25713. };
  25714. QuadraticErrorSimplification.prototype.init = function (callback) {
  25715. var _this = this;
  25716. var triangleInit1 = function (i) {
  25717. var t = _this.triangles[i];
  25718. 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();
  25719. for (var j = 0; j < 3; j++) {
  25720. _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))));
  25721. }
  25722. };
  25723. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  25724. var triangleInit2 = function (i) {
  25725. var t = _this.triangles[i];
  25726. for (var j = 0; j < 3; ++j) {
  25727. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  25728. }
  25729. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  25730. };
  25731. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  25732. _this.initialised = true;
  25733. callback();
  25734. });
  25735. });
  25736. };
  25737. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  25738. var newTriangles = [];
  25739. var i;
  25740. for (i = 0; i < this.vertices.length; ++i) {
  25741. this.vertices[i].triangleCount = 0;
  25742. }
  25743. var t;
  25744. var j;
  25745. for (i = 0; i < this.triangles.length; ++i) {
  25746. if (!this.triangles[i].deleted) {
  25747. t = this.triangles[i];
  25748. for (j = 0; j < 3; ++j) {
  25749. this.vertices[t.vertices[j]].triangleCount = 1;
  25750. }
  25751. newTriangles.push(t);
  25752. }
  25753. }
  25754. var newVerticesOrder = [];
  25755. //compact vertices, get the IDs of the vertices used.
  25756. var dst = 0;
  25757. for (i = 0; i < this.vertices.length; ++i) {
  25758. if (this.vertices[i].triangleCount) {
  25759. this.vertices[i].triangleStart = dst;
  25760. this.vertices[dst].position = this.vertices[i].position;
  25761. this.vertices[dst].normal = this.vertices[i].normal;
  25762. this.vertices[dst].uv = this.vertices[i].uv;
  25763. newVerticesOrder.push(i);
  25764. dst++;
  25765. }
  25766. }
  25767. for (i = 0; i < newTriangles.length; ++i) {
  25768. t = newTriangles[i];
  25769. for (j = 0; j < 3; ++j) {
  25770. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  25771. }
  25772. }
  25773. this.vertices = this.vertices.slice(0, dst);
  25774. var newPositionData = [];
  25775. var newNormalData = [];
  25776. var newUVsData = [];
  25777. for (i = 0; i < newVerticesOrder.length; ++i) {
  25778. newPositionData.push(this.vertices[i].position.x);
  25779. newPositionData.push(this.vertices[i].position.y);
  25780. newPositionData.push(this.vertices[i].position.z);
  25781. newNormalData.push(this.vertices[i].normal.x);
  25782. newNormalData.push(this.vertices[i].normal.y);
  25783. newNormalData.push(this.vertices[i].normal.z);
  25784. newUVsData.push(this.vertices[i].uv.x);
  25785. newUVsData.push(this.vertices[i].uv.y);
  25786. }
  25787. var newIndicesArray = [];
  25788. for (i = 0; i < newTriangles.length; ++i) {
  25789. newIndicesArray.push(newTriangles[i].vertices[0]);
  25790. newIndicesArray.push(newTriangles[i].vertices[1]);
  25791. newIndicesArray.push(newTriangles[i].vertices[2]);
  25792. }
  25793. var newMesh = new BABYLON.Mesh(this._mesh + "Decimated", this._mesh.getScene());
  25794. newMesh.material = this._mesh.material;
  25795. newMesh.parent = this._mesh.parent;
  25796. newMesh.setIndices(newIndicesArray);
  25797. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  25798. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  25799. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  25800. //preparing the skeleton support
  25801. if (this._mesh.skeleton) {
  25802. //newMesh.skeleton = this._mesh.skeleton.clone("", "");
  25803. //newMesh.getScene().beginAnimation(newMesh.skeleton, 0, 100, true, 1.0);
  25804. }
  25805. return newMesh;
  25806. };
  25807. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor) {
  25808. for (var i = 0; i < vertex1.triangleCount; ++i) {
  25809. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  25810. if (t.deleted)
  25811. continue;
  25812. var s = this.references[vertex1.triangleStart + i].vertexId;
  25813. var id1 = t.vertices[(s + 1) % 3];
  25814. var id2 = t.vertices[(s + 2) % 3];
  25815. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  25816. deletedArray[i] = true;
  25817. continue;
  25818. }
  25819. var d1 = this.vertices[id1].position.subtract(point);
  25820. d1 = d1.normalize();
  25821. var d2 = this.vertices[id2].position.subtract(point);
  25822. d2 = d2.normalize();
  25823. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  25824. return true;
  25825. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  25826. deletedArray[i] = false;
  25827. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  25828. return true;
  25829. }
  25830. return false;
  25831. };
  25832. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  25833. var newDeleted = deletedTriangles;
  25834. for (var i = 0; i < vertex.triangleCount; ++i) {
  25835. var ref = this.references[vertex.triangleStart + i];
  25836. var t = this.triangles[ref.triangleId];
  25837. if (t.deleted)
  25838. continue;
  25839. if (deletedArray[i]) {
  25840. t.deleted = true;
  25841. newDeleted++;
  25842. continue;
  25843. }
  25844. t.vertices[ref.vertexId] = vertexId;
  25845. t.isDirty = true;
  25846. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  25847. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  25848. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  25849. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  25850. this.references.push(ref);
  25851. }
  25852. return newDeleted;
  25853. };
  25854. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  25855. for (var i = 0; i < this.vertices.length; ++i) {
  25856. var vCount = [];
  25857. var vId = [];
  25858. var v = this.vertices[i];
  25859. var j;
  25860. for (j = 0; j < v.triangleCount; ++j) {
  25861. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  25862. for (var ii = 0; ii < 3; ii++) {
  25863. var ofs = 0;
  25864. var id = triangle.vertices[ii];
  25865. while (ofs < vCount.length) {
  25866. if (vId[ofs] === id)
  25867. break;
  25868. ++ofs;
  25869. }
  25870. if (ofs === vCount.length) {
  25871. vCount.push(1);
  25872. vId.push(id);
  25873. } else {
  25874. vCount[ofs]++;
  25875. }
  25876. }
  25877. }
  25878. for (j = 0; j < vCount.length; ++j) {
  25879. if (vCount[j] === 1) {
  25880. this.vertices[vId[j]].isBorder = true;
  25881. } else {
  25882. this.vertices[vId[j]].isBorder = false;
  25883. }
  25884. }
  25885. }
  25886. };
  25887. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  25888. if (typeof identifyBorders === "undefined") { identifyBorders = false; }
  25889. var i;
  25890. if (!identifyBorders) {
  25891. var newTrianglesVector = [];
  25892. for (i = 0; i < this.triangles.length; ++i) {
  25893. if (!this.triangles[i].deleted) {
  25894. newTrianglesVector.push(this.triangles[i]);
  25895. }
  25896. }
  25897. this.triangles = newTrianglesVector;
  25898. }
  25899. for (i = 0; i < this.vertices.length; ++i) {
  25900. this.vertices[i].triangleCount = 0;
  25901. this.vertices[i].triangleStart = 0;
  25902. }
  25903. var t;
  25904. var j;
  25905. var v;
  25906. for (i = 0; i < this.triangles.length; ++i) {
  25907. t = this.triangles[i];
  25908. for (j = 0; j < 3; ++j) {
  25909. v = this.vertices[t.vertices[j]];
  25910. v.triangleCount++;
  25911. }
  25912. }
  25913. var tStart = 0;
  25914. for (i = 0; i < this.vertices.length; ++i) {
  25915. this.vertices[i].triangleStart = tStart;
  25916. tStart += this.vertices[i].triangleCount;
  25917. this.vertices[i].triangleCount = 0;
  25918. }
  25919. var newReferences = new Array(this.triangles.length * 3);
  25920. for (i = 0; i < this.triangles.length; ++i) {
  25921. t = this.triangles[i];
  25922. for (j = 0; j < 3; ++j) {
  25923. v = this.vertices[t.vertices[j]];
  25924. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  25925. v.triangleCount++;
  25926. }
  25927. }
  25928. this.references = newReferences;
  25929. if (identifyBorders) {
  25930. this.identifyBorder();
  25931. }
  25932. };
  25933. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  25934. var x = point.x;
  25935. var y = point.y;
  25936. var z = point.z;
  25937. 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];
  25938. };
  25939. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult) {
  25940. var q = vertex1.q.add(vertex2.q);
  25941. var border = vertex1.isBorder && vertex2.isBorder;
  25942. var error = 0;
  25943. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  25944. if (qDet !== 0 && !border) {
  25945. if (!pointResult) {
  25946. pointResult = BABYLON.Vector3.Zero();
  25947. }
  25948. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  25949. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  25950. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  25951. error = this.vertexError(q, pointResult);
  25952. //TODO this should be correctly calculated
  25953. if (normalResult) {
  25954. normalResult.copyFrom(vertex1.normal);
  25955. uvResult.copyFrom(vertex1.uv);
  25956. }
  25957. } else {
  25958. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  25959. var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new BABYLON.Vector3(2, 2, 2)).normalize();
  25960. var error1 = this.vertexError(q, vertex1.position);
  25961. var error2 = this.vertexError(q, vertex2.position);
  25962. var error3 = this.vertexError(q, p3);
  25963. error = Math.min(error1, error2, error3);
  25964. if (error === error1) {
  25965. if (pointResult) {
  25966. pointResult.copyFrom(vertex1.position);
  25967. normalResult.copyFrom(vertex1.normal);
  25968. uvResult.copyFrom(vertex1.uv);
  25969. }
  25970. } else if (error === error2) {
  25971. if (pointResult) {
  25972. pointResult.copyFrom(vertex2.position);
  25973. normalResult.copyFrom(vertex2.normal);
  25974. uvResult.copyFrom(vertex2.uv);
  25975. }
  25976. } else {
  25977. if (pointResult) {
  25978. pointResult.copyFrom(p3);
  25979. normalResult.copyFrom(norm3);
  25980. uvResult.copyFrom(vertex1.uv);
  25981. }
  25982. }
  25983. }
  25984. return error;
  25985. };
  25986. return QuadraticErrorSimplification;
  25987. })();
  25988. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  25989. })(BABYLON || (BABYLON = {}));
  25990. //# sourceMappingURL=babylon.meshSimplification.js.map