babylon.2.1-alpha.debug.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  639. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  640. var m0 = SIMD.float32x4.load(transformation.m, 0);
  641. var m1 = SIMD.float32x4.load(transformation.m, 4);
  642. var m2 = SIMD.float32x4.load(transformation.m, 8);
  643. var m3 = SIMD.float32x4.load(transformation.m, 12);
  644. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  645. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  646. SIMD.float32x4.storeXYZ(result._data, 0, r);
  647. };
  648. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  649. var v0 = SIMD.float32x4.splat(x);
  650. var v1 = SIMD.float32x4.splat(y);
  651. var v2 = SIMD.float32x4.splat(z);
  652. var m0 = SIMD.float32x4.load(transformation.m, 0);
  653. var m1 = SIMD.float32x4.load(transformation.m, 4);
  654. var m2 = SIMD.float32x4.load(transformation.m, 8);
  655. var m3 = SIMD.float32x4.load(transformation.m, 12);
  656. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  657. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  658. SIMD.float32x4.storeXYZ(result._data, 0, r);
  659. };
  660. Vector3.TransformNormal = function (vector, transformation) {
  661. var result = Vector3.Zero();
  662. Vector3.TransformNormalToRef(vector, transformation, result);
  663. return result;
  664. };
  665. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  666. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  667. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  668. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  669. };
  670. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  671. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  672. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  673. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  674. };
  675. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  676. var squared = amount * amount;
  677. var cubed = amount * squared;
  678. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  679. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  680. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  681. return new Vector3(x, y, z);
  682. };
  683. Vector3.Clamp = function (value, min, max) {
  684. var x = value.x;
  685. x = (x > max.x) ? max.x : x;
  686. x = (x < min.x) ? min.x : x;
  687. var y = value.y;
  688. y = (y > max.y) ? max.y : y;
  689. y = (y < min.y) ? min.y : y;
  690. var z = value.z;
  691. z = (z > max.z) ? max.z : z;
  692. z = (z < min.z) ? min.z : z;
  693. return new Vector3(x, y, z);
  694. };
  695. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  696. var squared = amount * amount;
  697. var cubed = amount * squared;
  698. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  699. var part2 = (-2.0 * cubed) + (3.0 * squared);
  700. var part3 = (cubed - (2.0 * squared)) + amount;
  701. var part4 = cubed - squared;
  702. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  703. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  704. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  705. return new Vector3(x, y, z);
  706. };
  707. Vector3.Lerp = function (start, end, amount) {
  708. var x = start.x + ((end.x - start.x) * amount);
  709. var y = start.y + ((end.y - start.y) * amount);
  710. var z = start.z + ((end.z - start.z) * amount);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Dot = function (left, right) {
  714. return (left.x * right.x + left.y * right.y + left.z * right.z);
  715. };
  716. Vector3.Cross = function (left, right) {
  717. var result = Vector3.Zero();
  718. Vector3.CrossToRef(left, right, result);
  719. return result;
  720. };
  721. Vector3.CrossToRef = function (left, right, result) {
  722. result.x = left.y * right.z - left.z * right.y;
  723. result.y = left.z * right.x - left.x * right.z;
  724. result.z = left.x * right.y - left.y * right.x;
  725. };
  726. Vector3.Normalize = function (vector) {
  727. var result = Vector3.Zero();
  728. Vector3.NormalizeToRef(vector, result);
  729. return result;
  730. };
  731. Vector3.NormalizeToRef = function (vector, result) {
  732. result.copyFrom(vector);
  733. result.normalize();
  734. };
  735. Vector3.Project = function (vector, world, transform, viewport) {
  736. var cw = viewport.width;
  737. var ch = viewport.height;
  738. var cx = viewport.x;
  739. var cy = viewport.y;
  740. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  741. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  742. return Vector3.TransformCoordinates(vector, finalMatrix);
  743. };
  744. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  745. var matrix = world.multiply(transform);
  746. matrix.invert();
  747. source.x = source.x / viewportWidth * 2 - 1;
  748. source.y = -(source.y / viewportHeight * 2 - 1);
  749. var vector = Vector3.TransformCoordinates(source, matrix);
  750. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  751. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  752. vector = vector.scale(1.0 / num);
  753. }
  754. return vector;
  755. };
  756. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  757. var matrix = world.multiply(view).multiply(projection);
  758. matrix.invert();
  759. source.x = source.x / viewportWidth * 2 - 1;
  760. source.y = -(source.y / viewportHeight * 2 - 1);
  761. var vector = Vector3.TransformCoordinates(source, matrix);
  762. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  763. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  764. vector = vector.scale(1.0 / num);
  765. }
  766. return vector;
  767. };
  768. Vector3.Minimize = function (left, right) {
  769. var min = left.clone();
  770. min.MinimizeInPlace(right);
  771. return min;
  772. };
  773. Vector3.Maximize = function (left, right) {
  774. var max = left.clone();
  775. max.MaximizeInPlace(right);
  776. return max;
  777. };
  778. Vector3.Distance = function (value1, value2) {
  779. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  780. };
  781. Vector3.DistanceSquared = function (value1, value2) {
  782. var x = value1.x - value2.x;
  783. var y = value1.y - value2.y;
  784. var z = value1.z - value2.z;
  785. return (x * x) + (y * y) + (z * z);
  786. };
  787. Vector3.Center = function (value1, value2) {
  788. var center = value1.add(value2);
  789. center.scaleInPlace(0.5);
  790. return center;
  791. };
  792. return Vector3;
  793. })();
  794. BABYLON.Vector3 = Vector3;
  795. //Vector4 class created for EulerAngle class conversion to Quaternion
  796. var Vector4 = (function () {
  797. function Vector4(x, y, z, w) {
  798. this.x = x;
  799. this.y = y;
  800. this.z = z;
  801. this.w = w;
  802. }
  803. Vector4.prototype.toString = function () {
  804. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  805. };
  806. // Operators
  807. Vector4.prototype.asArray = function () {
  808. var result = [];
  809. this.toArray(result, 0);
  810. return result;
  811. };
  812. Vector4.prototype.toArray = function (array, index) {
  813. if (index === undefined) {
  814. index = 0;
  815. }
  816. array[index] = this.x;
  817. array[index + 1] = this.y;
  818. array[index + 2] = this.z;
  819. array[index + 3] = this.w;
  820. return this;
  821. };
  822. Vector4.prototype.addInPlace = function (otherVector) {
  823. this.x += otherVector.x;
  824. this.y += otherVector.y;
  825. this.z += otherVector.z;
  826. this.w += otherVector.w;
  827. return this;
  828. };
  829. Vector4.prototype.add = function (otherVector) {
  830. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  831. };
  832. Vector4.prototype.addToRef = function (otherVector, result) {
  833. result.x = this.x + otherVector.x;
  834. result.y = this.y + otherVector.y;
  835. result.z = this.z + otherVector.z;
  836. result.w = this.w + otherVector.w;
  837. return this;
  838. };
  839. Vector4.prototype.subtractInPlace = function (otherVector) {
  840. this.x -= otherVector.x;
  841. this.y -= otherVector.y;
  842. this.z -= otherVector.z;
  843. this.w -= otherVector.w;
  844. return this;
  845. };
  846. Vector4.prototype.subtract = function (otherVector) {
  847. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  848. };
  849. Vector4.prototype.subtractToRef = function (otherVector, result) {
  850. result.x = this.x - otherVector.x;
  851. result.y = this.y - otherVector.y;
  852. result.z = this.z - otherVector.z;
  853. result.w = this.w - otherVector.w;
  854. return this;
  855. };
  856. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  857. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  858. };
  859. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  860. result.x = this.x - x;
  861. result.y = this.y - y;
  862. result.z = this.z - z;
  863. result.w = this.w - w;
  864. return this;
  865. };
  866. Vector4.prototype.negate = function () {
  867. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  868. };
  869. Vector4.prototype.scaleInPlace = function (scale) {
  870. this.x *= scale;
  871. this.y *= scale;
  872. this.z *= scale;
  873. this.w *= scale;
  874. return this;
  875. };
  876. Vector4.prototype.scale = function (scale) {
  877. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  878. };
  879. Vector4.prototype.scaleToRef = function (scale, result) {
  880. result.x = this.x * scale;
  881. result.y = this.y * scale;
  882. result.z = this.z * scale;
  883. result.w = this.w * scale;
  884. };
  885. Vector4.prototype.equals = function (otherVector) {
  886. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  887. };
  888. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  889. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  890. };
  891. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  892. return this.x === x && this.y === y && this.z === z && this.w === w;
  893. };
  894. Vector4.prototype.multiplyInPlace = function (otherVector) {
  895. this.x *= otherVector.x;
  896. this.y *= otherVector.y;
  897. this.z *= otherVector.z;
  898. this.w *= otherVector.w;
  899. return this;
  900. };
  901. Vector4.prototype.multiply = function (otherVector) {
  902. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  903. };
  904. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  905. result.x = this.x * otherVector.x;
  906. result.y = this.y * otherVector.y;
  907. result.z = this.z * otherVector.z;
  908. result.w = this.w * otherVector.w;
  909. return this;
  910. };
  911. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  912. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  913. };
  914. Vector4.prototype.divide = function (otherVector) {
  915. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  916. };
  917. Vector4.prototype.divideToRef = function (otherVector, result) {
  918. result.x = this.x / otherVector.x;
  919. result.y = this.y / otherVector.y;
  920. result.z = this.z / otherVector.z;
  921. result.w = this.w / otherVector.w;
  922. return this;
  923. };
  924. Vector4.prototype.MinimizeInPlace = function (other) {
  925. if (other.x < this.x)
  926. this.x = other.x;
  927. if (other.y < this.y)
  928. this.y = other.y;
  929. if (other.z < this.z)
  930. this.z = other.z;
  931. if (other.w < this.w)
  932. this.w = other.w;
  933. return this;
  934. };
  935. Vector4.prototype.MaximizeInPlace = function (other) {
  936. if (other.x > this.x)
  937. this.x = other.x;
  938. if (other.y > this.y)
  939. this.y = other.y;
  940. if (other.z > this.z)
  941. this.z = other.z;
  942. if (other.w > this.w)
  943. this.w = other.w;
  944. return this;
  945. };
  946. // Properties
  947. Vector4.prototype.length = function () {
  948. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  949. };
  950. Vector4.prototype.lengthSquared = function () {
  951. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  952. };
  953. // Methods
  954. Vector4.prototype.normalize = function () {
  955. var len = this.length();
  956. if (len === 0)
  957. return this;
  958. var num = 1.0 / len;
  959. this.x *= num;
  960. this.y *= num;
  961. this.z *= num;
  962. this.w *= num;
  963. return this;
  964. };
  965. Vector4.prototype.clone = function () {
  966. return new Vector4(this.x, this.y, this.z, this.w);
  967. };
  968. Vector4.prototype.copyFrom = function (source) {
  969. this.x = source.x;
  970. this.y = source.y;
  971. this.z = source.z;
  972. this.w = source.w;
  973. return this;
  974. };
  975. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. return this;
  981. };
  982. // Statics
  983. Vector4.FromArray = function (array, offset) {
  984. if (!offset) {
  985. offset = 0;
  986. }
  987. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  988. };
  989. Vector4.FromArrayToRef = function (array, offset, result) {
  990. result.x = array[offset];
  991. result.y = array[offset + 1];
  992. result.z = array[offset + 2];
  993. result.w = array[offset + 3];
  994. };
  995. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1002. result.x = x;
  1003. result.y = y;
  1004. result.z = z;
  1005. result.w = w;
  1006. };
  1007. Vector4.Zero = function () {
  1008. return new Vector4(0, 0, 0, 0);
  1009. };
  1010. Vector4.Normalize = function (vector) {
  1011. var result = Vector4.Zero();
  1012. Vector4.NormalizeToRef(vector, result);
  1013. return result;
  1014. };
  1015. Vector4.NormalizeToRef = function (vector, result) {
  1016. result.copyFrom(vector);
  1017. result.normalize();
  1018. };
  1019. Vector4.Minimize = function (left, right) {
  1020. var min = left.clone();
  1021. min.MinimizeInPlace(right);
  1022. return min;
  1023. };
  1024. Vector4.Maximize = function (left, right) {
  1025. var max = left.clone();
  1026. max.MaximizeInPlace(right);
  1027. return max;
  1028. };
  1029. Vector4.Distance = function (value1, value2) {
  1030. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1031. };
  1032. Vector4.DistanceSquared = function (value1, value2) {
  1033. var x = value1.x - value2.x;
  1034. var y = value1.y - value2.y;
  1035. var z = value1.z - value2.z;
  1036. var w = value1.w - value2.w;
  1037. return (x * x) + (y * y) + (z * z) + (w * w);
  1038. };
  1039. Vector4.Center = function (value1, value2) {
  1040. var center = value1.add(value2);
  1041. center.scaleInPlace(0.5);
  1042. return center;
  1043. };
  1044. return Vector4;
  1045. })();
  1046. BABYLON.Vector4 = Vector4;
  1047. var Quaternion = (function () {
  1048. function Quaternion(x, y, z, w) {
  1049. if (x === void 0) { x = 0; }
  1050. if (y === void 0) { y = 0; }
  1051. if (z === void 0) { z = 0; }
  1052. if (w === void 0) { w = 1; }
  1053. this.x = x;
  1054. this.y = y;
  1055. this.z = z;
  1056. this.w = w;
  1057. }
  1058. Quaternion.prototype.toString = function () {
  1059. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1060. };
  1061. Quaternion.prototype.asArray = function () {
  1062. return [this.x, this.y, this.z, this.w];
  1063. };
  1064. Quaternion.prototype.equals = function (otherQuaternion) {
  1065. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1066. };
  1067. Quaternion.prototype.clone = function () {
  1068. return new Quaternion(this.x, this.y, this.z, this.w);
  1069. };
  1070. Quaternion.prototype.copyFrom = function (other) {
  1071. this.x = other.x;
  1072. this.y = other.y;
  1073. this.z = other.z;
  1074. this.w = other.w;
  1075. return this;
  1076. };
  1077. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1078. this.x = x;
  1079. this.y = y;
  1080. this.z = z;
  1081. this.w = w;
  1082. return this;
  1083. };
  1084. Quaternion.prototype.add = function (other) {
  1085. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1086. };
  1087. Quaternion.prototype.subtract = function (other) {
  1088. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1089. };
  1090. Quaternion.prototype.scale = function (value) {
  1091. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1092. };
  1093. Quaternion.prototype.multiply = function (q1) {
  1094. var result = new Quaternion(0, 0, 0, 1.0);
  1095. this.multiplyToRef(q1, result);
  1096. return result;
  1097. };
  1098. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1099. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1100. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1101. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1102. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1103. return this;
  1104. };
  1105. Quaternion.prototype.length = function () {
  1106. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1107. };
  1108. Quaternion.prototype.normalize = function () {
  1109. var length = 1.0 / this.length();
  1110. this.x *= length;
  1111. this.y *= length;
  1112. this.z *= length;
  1113. this.w *= length;
  1114. return this;
  1115. };
  1116. Quaternion.prototype.toEulerAngles = function () {
  1117. var result = Vector3.Zero();
  1118. this.toEulerAnglesToRef(result);
  1119. return result;
  1120. };
  1121. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1122. //result is an EulerAngles in the in the z-x-z convention
  1123. var qx = this.x;
  1124. var qy = this.y;
  1125. var qz = this.z;
  1126. var qw = this.w;
  1127. var qxy = qx * qy;
  1128. var qxz = qx * qz;
  1129. var qwy = qw * qy;
  1130. var qwz = qw * qz;
  1131. var qwx = qw * qx;
  1132. var qyz = qy * qz;
  1133. var sqx = qx * qx;
  1134. var sqy = qy * qy;
  1135. var determinant = sqx + sqy;
  1136. if (determinant !== 0.000 && determinant !== 1.000) {
  1137. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1138. result.y = Math.acos(1 - 2 * determinant);
  1139. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1140. }
  1141. else {
  1142. if (determinant === 0.0) {
  1143. result.x = 0.0;
  1144. result.y = 0.0;
  1145. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1146. }
  1147. else {
  1148. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1149. result.y = Math.PI;
  1150. result.z = 0.0;
  1151. }
  1152. }
  1153. return this;
  1154. };
  1155. Quaternion.prototype.toRotationMatrix = function (result) {
  1156. var xx = this.x * this.x;
  1157. var yy = this.y * this.y;
  1158. var zz = this.z * this.z;
  1159. var xy = this.x * this.y;
  1160. var zw = this.z * this.w;
  1161. var zx = this.z * this.x;
  1162. var yw = this.y * this.w;
  1163. var yz = this.y * this.z;
  1164. var xw = this.x * this.w;
  1165. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1166. result.m[1] = 2.0 * (xy + zw);
  1167. result.m[2] = 2.0 * (zx - yw);
  1168. result.m[3] = 0;
  1169. result.m[4] = 2.0 * (xy - zw);
  1170. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1171. result.m[6] = 2.0 * (yz + xw);
  1172. result.m[7] = 0;
  1173. result.m[8] = 2.0 * (zx + yw);
  1174. result.m[9] = 2.0 * (yz - xw);
  1175. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1176. result.m[11] = 0;
  1177. result.m[12] = 0;
  1178. result.m[13] = 0;
  1179. result.m[14] = 0;
  1180. result.m[15] = 1.0;
  1181. return this;
  1182. };
  1183. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1184. Quaternion.FromRotationMatrixToRef(matrix, this);
  1185. return this;
  1186. };
  1187. // Statics
  1188. Quaternion.FromRotationMatrix = function (matrix) {
  1189. var result = new Quaternion();
  1190. Quaternion.FromRotationMatrixToRef(matrix, result);
  1191. return result;
  1192. };
  1193. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1194. var data = matrix.m;
  1195. var m11 = data[0], m12 = data[4], m13 = data[8];
  1196. var m21 = data[1], m22 = data[5], m23 = data[9];
  1197. var m31 = data[2], m32 = data[6], m33 = data[10];
  1198. var trace = m11 + m22 + m33;
  1199. var s;
  1200. if (trace > 0) {
  1201. s = 0.5 / Math.sqrt(trace + 1.0);
  1202. result.w = 0.25 / s;
  1203. result.x = (m32 - m23) * s;
  1204. result.y = (m13 - m31) * s;
  1205. result.z = (m21 - m12) * s;
  1206. }
  1207. else if (m11 > m22 && m11 > m33) {
  1208. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1209. result.w = (m32 - m23) / s;
  1210. result.x = 0.25 * s;
  1211. result.y = (m12 + m21) / s;
  1212. result.z = (m13 + m31) / s;
  1213. }
  1214. else if (m22 > m33) {
  1215. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1216. result.w = (m13 - m31) / s;
  1217. result.x = (m12 + m21) / s;
  1218. result.y = 0.25 * s;
  1219. result.z = (m23 + m32) / s;
  1220. }
  1221. else {
  1222. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1223. result.w = (m21 - m12) / s;
  1224. result.x = (m13 + m31) / s;
  1225. result.y = (m23 + m32) / s;
  1226. result.z = 0.25 * s;
  1227. }
  1228. };
  1229. Quaternion.Inverse = function (q) {
  1230. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1231. };
  1232. Quaternion.Identity = function () {
  1233. return new Quaternion(0, 0, 0, 1);
  1234. };
  1235. Quaternion.RotationAxis = function (axis, angle) {
  1236. var result = new Quaternion();
  1237. var sin = Math.sin(angle / 2);
  1238. result.w = Math.cos(angle / 2);
  1239. result.x = axis.x * sin;
  1240. result.y = axis.y * sin;
  1241. result.z = axis.z * sin;
  1242. return result;
  1243. };
  1244. Quaternion.FromArray = function (array, offset) {
  1245. if (!offset) {
  1246. offset = 0;
  1247. }
  1248. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1249. };
  1250. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1251. var result = new Quaternion();
  1252. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1253. return result;
  1254. };
  1255. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1256. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1257. var halfRoll = roll * 0.5;
  1258. var halfPitch = pitch * 0.5;
  1259. var halfYaw = yaw * 0.5;
  1260. var sinRoll = Math.sin(halfRoll);
  1261. var cosRoll = Math.cos(halfRoll);
  1262. var sinPitch = Math.sin(halfPitch);
  1263. var cosPitch = Math.cos(halfPitch);
  1264. var sinYaw = Math.sin(halfYaw);
  1265. var cosYaw = Math.cos(halfYaw);
  1266. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1267. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1268. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1269. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1270. };
  1271. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1272. var result = new Quaternion();
  1273. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1274. return result;
  1275. };
  1276. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1277. // Produces a quaternion from Euler angles in the z-x-z orientation
  1278. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1279. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1280. var halfBeta = beta * 0.5;
  1281. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1282. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1283. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1284. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1285. };
  1286. Quaternion.Slerp = function (left, right, amount) {
  1287. var num2;
  1288. var num3;
  1289. var num = amount;
  1290. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1291. var flag = false;
  1292. if (num4 < 0) {
  1293. flag = true;
  1294. num4 = -num4;
  1295. }
  1296. if (num4 > 0.999999) {
  1297. num3 = 1 - num;
  1298. num2 = flag ? -num : num;
  1299. }
  1300. else {
  1301. var num5 = Math.acos(num4);
  1302. var num6 = (1.0 / Math.sin(num5));
  1303. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1304. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1305. }
  1306. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1307. };
  1308. return Quaternion;
  1309. })();
  1310. BABYLON.Quaternion = Quaternion;
  1311. var Matrix = (function () {
  1312. function Matrix() {
  1313. this.m = new Float32Array(16);
  1314. }
  1315. // Properties
  1316. Matrix.prototype.isIdentity = function () {
  1317. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1318. return false;
  1319. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1320. return false;
  1321. return true;
  1322. };
  1323. Matrix.prototype.determinant = function () {
  1324. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1325. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1326. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1327. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1328. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1329. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1330. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1331. };
  1332. // Methods
  1333. Matrix.prototype.toArray = function () {
  1334. return this.m;
  1335. };
  1336. Matrix.prototype.asArray = function () {
  1337. return this.toArray();
  1338. };
  1339. Matrix.prototype.invert = function () {
  1340. this.invertToRef(this);
  1341. return this;
  1342. };
  1343. Matrix.prototype.invertToRef = function (other) {
  1344. var l1 = this.m[0];
  1345. var l2 = this.m[1];
  1346. var l3 = this.m[2];
  1347. var l4 = this.m[3];
  1348. var l5 = this.m[4];
  1349. var l6 = this.m[5];
  1350. var l7 = this.m[6];
  1351. var l8 = this.m[7];
  1352. var l9 = this.m[8];
  1353. var l10 = this.m[9];
  1354. var l11 = this.m[10];
  1355. var l12 = this.m[11];
  1356. var l13 = this.m[12];
  1357. var l14 = this.m[13];
  1358. var l15 = this.m[14];
  1359. var l16 = this.m[15];
  1360. var l17 = (l11 * l16) - (l12 * l15);
  1361. var l18 = (l10 * l16) - (l12 * l14);
  1362. var l19 = (l10 * l15) - (l11 * l14);
  1363. var l20 = (l9 * l16) - (l12 * l13);
  1364. var l21 = (l9 * l15) - (l11 * l13);
  1365. var l22 = (l9 * l14) - (l10 * l13);
  1366. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1367. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1368. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1369. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1370. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1371. var l28 = (l7 * l16) - (l8 * l15);
  1372. var l29 = (l6 * l16) - (l8 * l14);
  1373. var l30 = (l6 * l15) - (l7 * l14);
  1374. var l31 = (l5 * l16) - (l8 * l13);
  1375. var l32 = (l5 * l15) - (l7 * l13);
  1376. var l33 = (l5 * l14) - (l6 * l13);
  1377. var l34 = (l7 * l12) - (l8 * l11);
  1378. var l35 = (l6 * l12) - (l8 * l10);
  1379. var l36 = (l6 * l11) - (l7 * l10);
  1380. var l37 = (l5 * l12) - (l8 * l9);
  1381. var l38 = (l5 * l11) - (l7 * l9);
  1382. var l39 = (l5 * l10) - (l6 * l9);
  1383. other.m[0] = l23 * l27;
  1384. other.m[4] = l24 * l27;
  1385. other.m[8] = l25 * l27;
  1386. other.m[12] = l26 * l27;
  1387. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1388. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1389. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1390. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1391. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1392. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1393. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1394. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1395. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1396. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1397. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1398. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1399. return this;
  1400. };
  1401. Matrix.prototype.invertToRefSIMD = function (other) {
  1402. var src = this.m;
  1403. var dest = other.m;
  1404. var row0, row1, row2, row3;
  1405. var tmp1;
  1406. var minor0, minor1, minor2, minor3;
  1407. var det;
  1408. // Load the 4 rows
  1409. var src0 = SIMD.float32x4.load(src, 0);
  1410. var src1 = SIMD.float32x4.load(src, 4);
  1411. var src2 = SIMD.float32x4.load(src, 8);
  1412. var src3 = SIMD.float32x4.load(src, 12);
  1413. // Transpose the source matrix. Sort of. Not a true transpose operation
  1414. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1415. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1416. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1417. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1418. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1419. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1420. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1421. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1422. // This is a true transposition, but it will lead to an incorrect result
  1423. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1424. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1425. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1426. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1427. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1428. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1429. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1430. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1431. // ----
  1432. tmp1 = SIMD.float32x4.mul(row2, row3);
  1433. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1434. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1435. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1436. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1437. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1438. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1439. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1440. // ----
  1441. tmp1 = SIMD.float32x4.mul(row1, row2);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1443. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1444. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1445. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1447. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1448. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1449. // ----
  1450. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1452. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1453. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1454. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1455. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1456. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1457. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1458. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. // ----
  1460. tmp1 = SIMD.float32x4.mul(row0, row1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1462. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1463. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1464. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1465. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1466. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1467. // ----
  1468. tmp1 = SIMD.float32x4.mul(row0, row3);
  1469. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1470. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1471. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1472. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1473. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1474. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1475. // ----
  1476. tmp1 = SIMD.float32x4.mul(row0, row2);
  1477. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1478. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1479. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1480. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1481. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1482. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1483. // Compute determinant
  1484. det = SIMD.float32x4.mul(row0, minor0);
  1485. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1486. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1487. tmp1 = SIMD.float32x4.reciprocal(det);
  1488. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1489. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1490. // These shuffles aren't necessary if the faulty transposition is done
  1491. // up at the top of this function.
  1492. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1493. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1494. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1495. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1496. // Compute final values by multiplying with 1/det
  1497. minor0 = SIMD.float32x4.mul(det, minor0);
  1498. minor1 = SIMD.float32x4.mul(det, minor1);
  1499. minor2 = SIMD.float32x4.mul(det, minor2);
  1500. minor3 = SIMD.float32x4.mul(det, minor3);
  1501. SIMD.float32x4.store(dest, 0, minor0);
  1502. SIMD.float32x4.store(dest, 4, minor1);
  1503. SIMD.float32x4.store(dest, 8, minor2);
  1504. SIMD.float32x4.store(dest, 12, minor3);
  1505. return this;
  1506. };
  1507. Matrix.prototype.setTranslation = function (vector3) {
  1508. this.m[12] = vector3.x;
  1509. this.m[13] = vector3.y;
  1510. this.m[14] = vector3.z;
  1511. return this;
  1512. };
  1513. Matrix.prototype.multiply = function (other) {
  1514. var result = new Matrix();
  1515. this.multiplyToRef(other, result);
  1516. return result;
  1517. };
  1518. Matrix.prototype.copyFrom = function (other) {
  1519. for (var index = 0; index < 16; index++) {
  1520. this.m[index] = other.m[index];
  1521. }
  1522. return this;
  1523. };
  1524. Matrix.prototype.copyToArray = function (array, offset) {
  1525. if (offset === void 0) { offset = 0; }
  1526. for (var index = 0; index < 16; index++) {
  1527. array[offset + index] = this.m[index];
  1528. }
  1529. return this;
  1530. };
  1531. Matrix.prototype.multiplyToRef = function (other, result) {
  1532. this.multiplyToArray(other, result.m, 0);
  1533. return this;
  1534. };
  1535. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1536. var tm0 = this.m[0];
  1537. var tm1 = this.m[1];
  1538. var tm2 = this.m[2];
  1539. var tm3 = this.m[3];
  1540. var tm4 = this.m[4];
  1541. var tm5 = this.m[5];
  1542. var tm6 = this.m[6];
  1543. var tm7 = this.m[7];
  1544. var tm8 = this.m[8];
  1545. var tm9 = this.m[9];
  1546. var tm10 = this.m[10];
  1547. var tm11 = this.m[11];
  1548. var tm12 = this.m[12];
  1549. var tm13 = this.m[13];
  1550. var tm14 = this.m[14];
  1551. var tm15 = this.m[15];
  1552. var om0 = other.m[0];
  1553. var om1 = other.m[1];
  1554. var om2 = other.m[2];
  1555. var om3 = other.m[3];
  1556. var om4 = other.m[4];
  1557. var om5 = other.m[5];
  1558. var om6 = other.m[6];
  1559. var om7 = other.m[7];
  1560. var om8 = other.m[8];
  1561. var om9 = other.m[9];
  1562. var om10 = other.m[10];
  1563. var om11 = other.m[11];
  1564. var om12 = other.m[12];
  1565. var om13 = other.m[13];
  1566. var om14 = other.m[14];
  1567. var om15 = other.m[15];
  1568. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1569. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1570. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1571. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1572. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1573. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1574. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1575. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1576. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1577. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1578. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1579. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1580. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1581. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1582. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1583. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1584. return this;
  1585. };
  1586. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1587. if (offset === void 0) { offset = 0; }
  1588. var tm = this.m;
  1589. var om = other.m;
  1590. var om0 = SIMD.float32x4.load(om, 0);
  1591. var om1 = SIMD.float32x4.load(om, 4);
  1592. var om2 = SIMD.float32x4.load(om, 8);
  1593. var om3 = SIMD.float32x4.load(om, 12);
  1594. var tm0 = SIMD.float32x4.load(tm, 0);
  1595. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1596. var tm1 = SIMD.float32x4.load(tm, 4);
  1597. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1598. var tm2 = SIMD.float32x4.load(tm, 8);
  1599. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1600. var tm3 = SIMD.float32x4.load(tm, 12);
  1601. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1602. };
  1603. Matrix.prototype.equals = function (value) {
  1604. 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]);
  1605. };
  1606. Matrix.prototype.clone = function () {
  1607. 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]);
  1608. };
  1609. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1610. translation.x = this.m[12];
  1611. translation.y = this.m[13];
  1612. translation.z = this.m[14];
  1613. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1614. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1615. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1616. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1617. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1618. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1619. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1620. rotation.x = 0;
  1621. rotation.y = 0;
  1622. rotation.z = 0;
  1623. rotation.w = 1;
  1624. return false;
  1625. }
  1626. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1627. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1628. return true;
  1629. };
  1630. // Statics
  1631. Matrix.FromArray = function (array, offset) {
  1632. var result = new Matrix();
  1633. if (!offset) {
  1634. offset = 0;
  1635. }
  1636. Matrix.FromArrayToRef(array, offset, result);
  1637. return result;
  1638. };
  1639. Matrix.FromArrayToRef = function (array, offset, result) {
  1640. for (var index = 0; index < 16; index++) {
  1641. result.m[index] = array[index + offset];
  1642. }
  1643. };
  1644. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1645. result.m[0] = initialM11;
  1646. result.m[1] = initialM12;
  1647. result.m[2] = initialM13;
  1648. result.m[3] = initialM14;
  1649. result.m[4] = initialM21;
  1650. result.m[5] = initialM22;
  1651. result.m[6] = initialM23;
  1652. result.m[7] = initialM24;
  1653. result.m[8] = initialM31;
  1654. result.m[9] = initialM32;
  1655. result.m[10] = initialM33;
  1656. result.m[11] = initialM34;
  1657. result.m[12] = initialM41;
  1658. result.m[13] = initialM42;
  1659. result.m[14] = initialM43;
  1660. result.m[15] = initialM44;
  1661. };
  1662. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1663. var result = new Matrix();
  1664. result.m[0] = initialM11;
  1665. result.m[1] = initialM12;
  1666. result.m[2] = initialM13;
  1667. result.m[3] = initialM14;
  1668. result.m[4] = initialM21;
  1669. result.m[5] = initialM22;
  1670. result.m[6] = initialM23;
  1671. result.m[7] = initialM24;
  1672. result.m[8] = initialM31;
  1673. result.m[9] = initialM32;
  1674. result.m[10] = initialM33;
  1675. result.m[11] = initialM34;
  1676. result.m[12] = initialM41;
  1677. result.m[13] = initialM42;
  1678. result.m[14] = initialM43;
  1679. result.m[15] = initialM44;
  1680. return result;
  1681. };
  1682. Matrix.Compose = function (scale, rotation, translation) {
  1683. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1684. var rotationMatrix = Matrix.Identity();
  1685. rotation.toRotationMatrix(rotationMatrix);
  1686. result = result.multiply(rotationMatrix);
  1687. result.setTranslation(translation);
  1688. return result;
  1689. };
  1690. Matrix.Identity = function () {
  1691. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1692. };
  1693. Matrix.IdentityToRef = function (result) {
  1694. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1695. };
  1696. Matrix.Zero = function () {
  1697. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1698. };
  1699. Matrix.RotationX = function (angle) {
  1700. var result = new Matrix();
  1701. Matrix.RotationXToRef(angle, result);
  1702. return result;
  1703. };
  1704. Matrix.Invert = function (source) {
  1705. var result = new Matrix();
  1706. source.invertToRef(result);
  1707. return result;
  1708. };
  1709. Matrix.RotationXToRef = function (angle, result) {
  1710. var s = Math.sin(angle);
  1711. var c = Math.cos(angle);
  1712. result.m[0] = 1.0;
  1713. result.m[15] = 1.0;
  1714. result.m[5] = c;
  1715. result.m[10] = c;
  1716. result.m[9] = -s;
  1717. result.m[6] = s;
  1718. result.m[1] = 0;
  1719. result.m[2] = 0;
  1720. result.m[3] = 0;
  1721. result.m[4] = 0;
  1722. result.m[7] = 0;
  1723. result.m[8] = 0;
  1724. result.m[11] = 0;
  1725. result.m[12] = 0;
  1726. result.m[13] = 0;
  1727. result.m[14] = 0;
  1728. };
  1729. Matrix.RotationY = function (angle) {
  1730. var result = new Matrix();
  1731. Matrix.RotationYToRef(angle, result);
  1732. return result;
  1733. };
  1734. Matrix.RotationYToRef = function (angle, result) {
  1735. var s = Math.sin(angle);
  1736. var c = Math.cos(angle);
  1737. result.m[5] = 1.0;
  1738. result.m[15] = 1.0;
  1739. result.m[0] = c;
  1740. result.m[2] = -s;
  1741. result.m[8] = s;
  1742. result.m[10] = c;
  1743. result.m[1] = 0;
  1744. result.m[3] = 0;
  1745. result.m[4] = 0;
  1746. result.m[6] = 0;
  1747. result.m[7] = 0;
  1748. result.m[9] = 0;
  1749. result.m[11] = 0;
  1750. result.m[12] = 0;
  1751. result.m[13] = 0;
  1752. result.m[14] = 0;
  1753. };
  1754. Matrix.RotationZ = function (angle) {
  1755. var result = new Matrix();
  1756. Matrix.RotationZToRef(angle, result);
  1757. return result;
  1758. };
  1759. Matrix.RotationZToRef = function (angle, result) {
  1760. var s = Math.sin(angle);
  1761. var c = Math.cos(angle);
  1762. result.m[10] = 1.0;
  1763. result.m[15] = 1.0;
  1764. result.m[0] = c;
  1765. result.m[1] = s;
  1766. result.m[4] = -s;
  1767. result.m[5] = c;
  1768. result.m[2] = 0;
  1769. result.m[3] = 0;
  1770. result.m[6] = 0;
  1771. result.m[7] = 0;
  1772. result.m[8] = 0;
  1773. result.m[9] = 0;
  1774. result.m[11] = 0;
  1775. result.m[12] = 0;
  1776. result.m[13] = 0;
  1777. result.m[14] = 0;
  1778. };
  1779. Matrix.RotationAxis = function (axis, angle) {
  1780. var s = Math.sin(-angle);
  1781. var c = Math.cos(-angle);
  1782. var c1 = 1 - c;
  1783. axis.normalize();
  1784. var result = Matrix.Zero();
  1785. result.m[0] = (axis.x * axis.x) * c1 + c;
  1786. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1787. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1788. result.m[3] = 0.0;
  1789. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1790. result.m[5] = (axis.y * axis.y) * c1 + c;
  1791. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1792. result.m[7] = 0.0;
  1793. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1794. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1795. result.m[10] = (axis.z * axis.z) * c1 + c;
  1796. result.m[11] = 0.0;
  1797. result.m[15] = 1.0;
  1798. return result;
  1799. };
  1800. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1801. var result = new Matrix();
  1802. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1803. return result;
  1804. };
  1805. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1806. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1807. this._tempQuaternion.toRotationMatrix(result);
  1808. };
  1809. Matrix.Scaling = function (x, y, z) {
  1810. var result = Matrix.Zero();
  1811. Matrix.ScalingToRef(x, y, z, result);
  1812. return result;
  1813. };
  1814. Matrix.ScalingToRef = function (x, y, z, result) {
  1815. result.m[0] = x;
  1816. result.m[1] = 0;
  1817. result.m[2] = 0;
  1818. result.m[3] = 0;
  1819. result.m[4] = 0;
  1820. result.m[5] = y;
  1821. result.m[6] = 0;
  1822. result.m[7] = 0;
  1823. result.m[8] = 0;
  1824. result.m[9] = 0;
  1825. result.m[10] = z;
  1826. result.m[11] = 0;
  1827. result.m[12] = 0;
  1828. result.m[13] = 0;
  1829. result.m[14] = 0;
  1830. result.m[15] = 1.0;
  1831. };
  1832. Matrix.Translation = function (x, y, z) {
  1833. var result = Matrix.Identity();
  1834. Matrix.TranslationToRef(x, y, z, result);
  1835. return result;
  1836. };
  1837. Matrix.TranslationToRef = function (x, y, z, result) {
  1838. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1839. };
  1840. Matrix.LookAtLH = function (eye, target, up) {
  1841. var result = Matrix.Zero();
  1842. Matrix.LookAtLHToRef(eye, target, up, result);
  1843. return result;
  1844. };
  1845. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1846. // Z axis
  1847. target.subtractToRef(eye, this._zAxis);
  1848. this._zAxis.normalize();
  1849. // X axis
  1850. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1851. this._xAxis.normalize();
  1852. // Y axis
  1853. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1854. this._yAxis.normalize();
  1855. // Eye angles
  1856. var ex = -Vector3.Dot(this._xAxis, eye);
  1857. var ey = -Vector3.Dot(this._yAxis, eye);
  1858. var ez = -Vector3.Dot(this._zAxis, eye);
  1859. 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);
  1860. };
  1861. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1862. var out = result.m;
  1863. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1864. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1865. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1866. // cc.kmVec3Subtract(f, pCenter, pEye);
  1867. var f = SIMD.float32x4.sub(center, eye);
  1868. // cc.kmVec3Normalize(f, f);
  1869. var tmp = SIMD.float32x4.mul(f, f);
  1870. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1871. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrt(tmp));
  1872. // cc.kmVec3Assign(up, pUp);
  1873. // cc.kmVec3Normalize(up, up);
  1874. tmp = SIMD.float32x4.mul(up, up);
  1875. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1876. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrt(tmp));
  1877. // cc.kmVec3Cross(s, f, up);
  1878. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  1879. // cc.kmVec3Normalize(s, s);
  1880. tmp = SIMD.float32x4.mul(s, s);
  1881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1882. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1883. // cc.kmVec3Cross(u, s, f);
  1884. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  1885. // cc.kmVec3Normalize(s, s);
  1886. tmp = SIMD.float32x4.mul(s, s);
  1887. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1888. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1889. //cc.kmMat4Identity(pOut);
  1890. //pOut.mat[0] = s.x;
  1891. //pOut.mat[4] = s.y;
  1892. //pOut.mat[8] = s.z;
  1893. //pOut.mat[1] = u.x;
  1894. //pOut.mat[5] = u.y;
  1895. //pOut.mat[9] = u.z;
  1896. //pOut.mat[2] = -f.x;
  1897. //pOut.mat[6] = -f.y;
  1898. //pOut.mat[10] = -f.z;
  1899. var zero = SIMD.float32x4.splat(0.0);
  1900. s = SIMD.float32x4.neg(s);
  1901. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1902. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1903. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1904. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1905. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1906. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1907. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1908. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1909. // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z);
  1910. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1911. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1912. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1913. var b3 = SIMD.float32x4.neg(eye);
  1914. b3 = SIMD.float32x4.withW(b3, 1.0);
  1915. // cc.kmMat4Multiply(pOut, pOut, translate);
  1916. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  1917. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  1918. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  1919. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  1920. };
  1921. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1922. var matrix = Matrix.Zero();
  1923. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1924. return matrix;
  1925. };
  1926. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1927. var hw = 2.0 / width;
  1928. var hh = 2.0 / height;
  1929. var id = 1.0 / (zfar - znear);
  1930. var nid = znear / (znear - zfar);
  1931. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1932. };
  1933. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1934. var matrix = Matrix.Zero();
  1935. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1936. return matrix;
  1937. };
  1938. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1939. result.m[0] = 2.0 / (right - left);
  1940. result.m[1] = result.m[2] = result.m[3] = 0;
  1941. result.m[5] = 2.0 / (top - bottom);
  1942. result.m[4] = result.m[6] = result.m[7] = 0;
  1943. result.m[10] = -1.0 / (znear - zfar);
  1944. result.m[8] = result.m[9] = result.m[11] = 0;
  1945. result.m[12] = (left + right) / (left - right);
  1946. result.m[13] = (top + bottom) / (bottom - top);
  1947. result.m[14] = znear / (znear - zfar);
  1948. result.m[15] = 1.0;
  1949. };
  1950. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1951. var matrix = Matrix.Zero();
  1952. matrix.m[0] = (2.0 * znear) / width;
  1953. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1954. matrix.m[5] = (2.0 * znear) / height;
  1955. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1956. matrix.m[10] = -zfar / (znear - zfar);
  1957. matrix.m[8] = matrix.m[9] = 0.0;
  1958. matrix.m[11] = 1.0;
  1959. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1960. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1961. return matrix;
  1962. };
  1963. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1964. var matrix = Matrix.Zero();
  1965. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1966. return matrix;
  1967. };
  1968. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1969. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1970. var tan = 1.0 / (Math.tan(fov * 0.5));
  1971. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1972. if (v_fixed) {
  1973. result.m[0] = tan / aspect;
  1974. }
  1975. else {
  1976. result.m[0] = tan;
  1977. }
  1978. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1979. if (v_fixed) {
  1980. result.m[5] = tan;
  1981. }
  1982. else {
  1983. result.m[5] = tan * aspect;
  1984. }
  1985. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1986. result.m[8] = result.m[9] = 0.0;
  1987. result.m[10] = -zfar / (znear - zfar);
  1988. result.m[11] = 1.0;
  1989. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1990. result.m[14] = (znear * zfar) / (znear - zfar);
  1991. };
  1992. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1993. var cw = viewport.width;
  1994. var ch = viewport.height;
  1995. var cx = viewport.x;
  1996. var cy = viewport.y;
  1997. 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);
  1998. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1999. };
  2000. Matrix.Transpose = function (matrix) {
  2001. var result = new Matrix();
  2002. result.m[0] = matrix.m[0];
  2003. result.m[1] = matrix.m[4];
  2004. result.m[2] = matrix.m[8];
  2005. result.m[3] = matrix.m[12];
  2006. result.m[4] = matrix.m[1];
  2007. result.m[5] = matrix.m[5];
  2008. result.m[6] = matrix.m[9];
  2009. result.m[7] = matrix.m[13];
  2010. result.m[8] = matrix.m[2];
  2011. result.m[9] = matrix.m[6];
  2012. result.m[10] = matrix.m[10];
  2013. result.m[11] = matrix.m[14];
  2014. result.m[12] = matrix.m[3];
  2015. result.m[13] = matrix.m[7];
  2016. result.m[14] = matrix.m[11];
  2017. result.m[15] = matrix.m[15];
  2018. return result;
  2019. };
  2020. Matrix.Reflection = function (plane) {
  2021. var matrix = new Matrix();
  2022. Matrix.ReflectionToRef(plane, matrix);
  2023. return matrix;
  2024. };
  2025. Matrix.ReflectionToRef = function (plane, result) {
  2026. plane.normalize();
  2027. var x = plane.normal.x;
  2028. var y = plane.normal.y;
  2029. var z = plane.normal.z;
  2030. var temp = -2 * x;
  2031. var temp2 = -2 * y;
  2032. var temp3 = -2 * z;
  2033. result.m[0] = (temp * x) + 1;
  2034. result.m[1] = temp2 * x;
  2035. result.m[2] = temp3 * x;
  2036. result.m[3] = 0.0;
  2037. result.m[4] = temp * y;
  2038. result.m[5] = (temp2 * y) + 1;
  2039. result.m[6] = temp3 * y;
  2040. result.m[7] = 0.0;
  2041. result.m[8] = temp * z;
  2042. result.m[9] = temp2 * z;
  2043. result.m[10] = (temp3 * z) + 1;
  2044. result.m[11] = 0.0;
  2045. result.m[12] = temp * plane.d;
  2046. result.m[13] = temp2 * plane.d;
  2047. result.m[14] = temp3 * plane.d;
  2048. result.m[15] = 1.0;
  2049. };
  2050. Matrix._tempQuaternion = new Quaternion();
  2051. Matrix._xAxis = Vector3.Zero();
  2052. Matrix._yAxis = Vector3.Zero();
  2053. Matrix._zAxis = Vector3.Zero();
  2054. return Matrix;
  2055. })();
  2056. BABYLON.Matrix = Matrix;
  2057. var Plane = (function () {
  2058. function Plane(a, b, c, d) {
  2059. this.normal = new Vector3(a, b, c);
  2060. this.d = d;
  2061. }
  2062. Plane.prototype.asArray = function () {
  2063. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2064. };
  2065. // Methods
  2066. Plane.prototype.clone = function () {
  2067. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2068. };
  2069. Plane.prototype.normalize = function () {
  2070. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2071. var magnitude = 0;
  2072. if (norm !== 0) {
  2073. magnitude = 1.0 / norm;
  2074. }
  2075. this.normal.x *= magnitude;
  2076. this.normal.y *= magnitude;
  2077. this.normal.z *= magnitude;
  2078. this.d *= magnitude;
  2079. return this;
  2080. };
  2081. Plane.prototype.transform = function (transformation) {
  2082. var transposedMatrix = Matrix.Transpose(transformation);
  2083. var x = this.normal.x;
  2084. var y = this.normal.y;
  2085. var z = this.normal.z;
  2086. var d = this.d;
  2087. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2088. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2089. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2090. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2091. return new Plane(normalX, normalY, normalZ, finalD);
  2092. };
  2093. Plane.prototype.dotCoordinate = function (point) {
  2094. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2095. };
  2096. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2097. var x1 = point2.x - point1.x;
  2098. var y1 = point2.y - point1.y;
  2099. var z1 = point2.z - point1.z;
  2100. var x2 = point3.x - point1.x;
  2101. var y2 = point3.y - point1.y;
  2102. var z2 = point3.z - point1.z;
  2103. var yz = (y1 * z2) - (z1 * y2);
  2104. var xz = (z1 * x2) - (x1 * z2);
  2105. var xy = (x1 * y2) - (y1 * x2);
  2106. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2107. var invPyth;
  2108. if (pyth !== 0) {
  2109. invPyth = 1.0 / pyth;
  2110. }
  2111. else {
  2112. invPyth = 0;
  2113. }
  2114. this.normal.x = yz * invPyth;
  2115. this.normal.y = xz * invPyth;
  2116. this.normal.z = xy * invPyth;
  2117. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2118. return this;
  2119. };
  2120. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2121. var dot = Vector3.Dot(this.normal, direction);
  2122. return (dot <= epsilon);
  2123. };
  2124. Plane.prototype.signedDistanceTo = function (point) {
  2125. return Vector3.Dot(point, this.normal) + this.d;
  2126. };
  2127. // Statics
  2128. Plane.FromArray = function (array) {
  2129. return new Plane(array[0], array[1], array[2], array[3]);
  2130. };
  2131. Plane.FromPoints = function (point1, point2, point3) {
  2132. var result = new Plane(0, 0, 0, 0);
  2133. result.copyFromPoints(point1, point2, point3);
  2134. return result;
  2135. };
  2136. Plane.FromPositionAndNormal = function (origin, normal) {
  2137. var result = new Plane(0, 0, 0, 0);
  2138. normal.normalize();
  2139. result.normal = normal;
  2140. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2141. return result;
  2142. };
  2143. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2144. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2145. return Vector3.Dot(point, normal) + d;
  2146. };
  2147. return Plane;
  2148. })();
  2149. BABYLON.Plane = Plane;
  2150. var Viewport = (function () {
  2151. function Viewport(x, y, width, height) {
  2152. this.x = x;
  2153. this.y = y;
  2154. this.width = width;
  2155. this.height = height;
  2156. }
  2157. Viewport.prototype.toGlobal = function (engine) {
  2158. var width = engine.getRenderWidth();
  2159. var height = engine.getRenderHeight();
  2160. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2161. };
  2162. return Viewport;
  2163. })();
  2164. BABYLON.Viewport = Viewport;
  2165. var Frustum = (function () {
  2166. function Frustum() {
  2167. }
  2168. Frustum.GetPlanes = function (transform) {
  2169. var frustumPlanes = [];
  2170. for (var index = 0; index < 6; index++) {
  2171. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2172. }
  2173. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2174. return frustumPlanes;
  2175. };
  2176. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2177. // Near
  2178. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2179. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2180. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2181. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2182. frustumPlanes[0].normalize();
  2183. // Far
  2184. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2185. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2186. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2187. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2188. frustumPlanes[1].normalize();
  2189. // Left
  2190. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2191. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2192. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2193. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2194. frustumPlanes[2].normalize();
  2195. // Right
  2196. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2197. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2198. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2199. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2200. frustumPlanes[3].normalize();
  2201. // Top
  2202. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2203. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2204. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2205. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2206. frustumPlanes[4].normalize();
  2207. // Bottom
  2208. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2209. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2210. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2211. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2212. frustumPlanes[5].normalize();
  2213. };
  2214. return Frustum;
  2215. })();
  2216. BABYLON.Frustum = Frustum;
  2217. var Ray = (function () {
  2218. function Ray(origin, direction, length) {
  2219. if (length === void 0) { length = Number.MAX_VALUE; }
  2220. this.origin = origin;
  2221. this.direction = direction;
  2222. this.length = length;
  2223. }
  2224. // Methods
  2225. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2226. var d = 0.0;
  2227. var maxValue = Number.MAX_VALUE;
  2228. if (Math.abs(this.direction.x) < 0.0000001) {
  2229. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2230. return false;
  2231. }
  2232. }
  2233. else {
  2234. var inv = 1.0 / this.direction.x;
  2235. var min = (minimum.x - this.origin.x) * inv;
  2236. var max = (maximum.x - this.origin.x) * inv;
  2237. if (max === -Infinity) {
  2238. max = Infinity;
  2239. }
  2240. if (min > max) {
  2241. var temp = min;
  2242. min = max;
  2243. max = temp;
  2244. }
  2245. d = Math.max(min, d);
  2246. maxValue = Math.min(max, maxValue);
  2247. if (d > maxValue) {
  2248. return false;
  2249. }
  2250. }
  2251. if (Math.abs(this.direction.y) < 0.0000001) {
  2252. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2253. return false;
  2254. }
  2255. }
  2256. else {
  2257. inv = 1.0 / this.direction.y;
  2258. min = (minimum.y - this.origin.y) * inv;
  2259. max = (maximum.y - this.origin.y) * inv;
  2260. if (max === -Infinity) {
  2261. max = Infinity;
  2262. }
  2263. if (min > max) {
  2264. temp = min;
  2265. min = max;
  2266. max = temp;
  2267. }
  2268. d = Math.max(min, d);
  2269. maxValue = Math.min(max, maxValue);
  2270. if (d > maxValue) {
  2271. return false;
  2272. }
  2273. }
  2274. if (Math.abs(this.direction.z) < 0.0000001) {
  2275. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2276. return false;
  2277. }
  2278. }
  2279. else {
  2280. inv = 1.0 / this.direction.z;
  2281. min = (minimum.z - this.origin.z) * inv;
  2282. max = (maximum.z - this.origin.z) * inv;
  2283. if (max === -Infinity) {
  2284. max = Infinity;
  2285. }
  2286. if (min > max) {
  2287. temp = min;
  2288. min = max;
  2289. max = temp;
  2290. }
  2291. d = Math.max(min, d);
  2292. maxValue = Math.min(max, maxValue);
  2293. if (d > maxValue) {
  2294. return false;
  2295. }
  2296. }
  2297. return true;
  2298. };
  2299. Ray.prototype.intersectsBox = function (box) {
  2300. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2301. };
  2302. Ray.prototype.intersectsSphere = function (sphere) {
  2303. var x = sphere.center.x - this.origin.x;
  2304. var y = sphere.center.y - this.origin.y;
  2305. var z = sphere.center.z - this.origin.z;
  2306. var pyth = (x * x) + (y * y) + (z * z);
  2307. var rr = sphere.radius * sphere.radius;
  2308. if (pyth <= rr) {
  2309. return true;
  2310. }
  2311. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2312. if (dot < 0.0) {
  2313. return false;
  2314. }
  2315. var temp = pyth - (dot * dot);
  2316. return temp <= rr;
  2317. };
  2318. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2319. if (!this._edge1) {
  2320. this._edge1 = Vector3.Zero();
  2321. this._edge2 = Vector3.Zero();
  2322. this._pvec = Vector3.Zero();
  2323. this._tvec = Vector3.Zero();
  2324. this._qvec = Vector3.Zero();
  2325. }
  2326. vertex1.subtractToRef(vertex0, this._edge1);
  2327. vertex2.subtractToRef(vertex0, this._edge2);
  2328. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2329. var det = Vector3.Dot(this._edge1, this._pvec);
  2330. if (det === 0) {
  2331. return null;
  2332. }
  2333. var invdet = 1 / det;
  2334. this.origin.subtractToRef(vertex0, this._tvec);
  2335. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2336. if (bu < 0 || bu > 1.0) {
  2337. return null;
  2338. }
  2339. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2340. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2341. if (bv < 0 || bu + bv > 1.0) {
  2342. return null;
  2343. }
  2344. //check if the distance is longer than the predefined length.
  2345. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2346. if (distance > this.length) {
  2347. return null;
  2348. }
  2349. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2350. };
  2351. // Statics
  2352. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2353. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2354. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2355. var direction = end.subtract(start);
  2356. direction.normalize();
  2357. return new Ray(start, direction);
  2358. };
  2359. /**
  2360. * 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
  2361. * transformed to the given world matrix.
  2362. * @param origin The origin point
  2363. * @param end The end point
  2364. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2365. */
  2366. Ray.CreateNewFromTo = function (origin, end, world) {
  2367. if (world === void 0) { world = Matrix.Identity(); }
  2368. var direction = end.subtract(origin);
  2369. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2370. direction.normalize();
  2371. return Ray.Transform(new Ray(origin, direction, length), world);
  2372. };
  2373. Ray.Transform = function (ray, matrix) {
  2374. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2375. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2376. return new Ray(newOrigin, newDirection, ray.length);
  2377. };
  2378. return Ray;
  2379. })();
  2380. BABYLON.Ray = Ray;
  2381. (function (Space) {
  2382. Space[Space["LOCAL"] = 0] = "LOCAL";
  2383. Space[Space["WORLD"] = 1] = "WORLD";
  2384. })(BABYLON.Space || (BABYLON.Space = {}));
  2385. var Space = BABYLON.Space;
  2386. var Axis = (function () {
  2387. function Axis() {
  2388. }
  2389. Axis.X = new Vector3(1, 0, 0);
  2390. Axis.Y = new Vector3(0, 1, 0);
  2391. Axis.Z = new Vector3(0, 0, 1);
  2392. return Axis;
  2393. })();
  2394. BABYLON.Axis = Axis;
  2395. ;
  2396. var BezierCurve = (function () {
  2397. function BezierCurve() {
  2398. }
  2399. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2400. // Extract X (which is equal to time here)
  2401. var f0 = 1 - 3 * x2 + 3 * x1;
  2402. var f1 = 3 * x2 - 6 * x1;
  2403. var f2 = 3 * x1;
  2404. var refinedT = t;
  2405. for (var i = 0; i < 5; i++) {
  2406. var refinedT2 = refinedT * refinedT;
  2407. var refinedT3 = refinedT2 * refinedT;
  2408. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2409. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2410. refinedT -= (x - t) * slope;
  2411. refinedT = Math.min(1, Math.max(0, refinedT));
  2412. }
  2413. // Resolve cubic bezier for the given x
  2414. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2415. };
  2416. return BezierCurve;
  2417. })();
  2418. BABYLON.BezierCurve = BezierCurve;
  2419. (function (Orientation) {
  2420. Orientation[Orientation["CW"] = 0] = "CW";
  2421. Orientation[Orientation["CCW"] = 1] = "CCW";
  2422. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2423. var Orientation = BABYLON.Orientation;
  2424. var Angle = (function () {
  2425. function Angle(radians) {
  2426. var _this = this;
  2427. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2428. this.radians = function () { return _this._radians; };
  2429. this._radians = radians;
  2430. if (this._radians < 0)
  2431. this._radians += (2 * Math.PI);
  2432. }
  2433. Angle.BetweenTwoPoints = function (a, b) {
  2434. var delta = b.subtract(a);
  2435. var theta = Math.atan2(delta.y, delta.x);
  2436. return new Angle(theta);
  2437. };
  2438. Angle.FromRadians = function (radians) {
  2439. return new Angle(radians);
  2440. };
  2441. Angle.FromDegrees = function (degrees) {
  2442. return new Angle(degrees * Math.PI / 180);
  2443. };
  2444. return Angle;
  2445. })();
  2446. BABYLON.Angle = Angle;
  2447. var Arc2 = (function () {
  2448. function Arc2(startPoint, midPoint, endPoint) {
  2449. this.startPoint = startPoint;
  2450. this.midPoint = midPoint;
  2451. this.endPoint = endPoint;
  2452. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2453. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2454. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2455. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2456. 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);
  2457. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2458. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2459. var a1 = this.startAngle.degrees();
  2460. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2461. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2462. // angles correction
  2463. if (a2 - a1 > +180.0)
  2464. a2 -= 360.0;
  2465. if (a2 - a1 < -180.0)
  2466. a2 += 360.0;
  2467. if (a3 - a2 > +180.0)
  2468. a3 -= 360.0;
  2469. if (a3 - a2 < -180.0)
  2470. a3 += 360.0;
  2471. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2472. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2473. }
  2474. return Arc2;
  2475. })();
  2476. BABYLON.Arc2 = Arc2;
  2477. var PathCursor = (function () {
  2478. function PathCursor(path) {
  2479. this.path = path;
  2480. this._onchange = new Array();
  2481. this.value = 0;
  2482. this.animations = new Array();
  2483. }
  2484. PathCursor.prototype.getPoint = function () {
  2485. var point = this.path.getPointAtLengthPosition(this.value);
  2486. return new Vector3(point.x, 0, point.y);
  2487. };
  2488. PathCursor.prototype.moveAhead = function (step) {
  2489. if (step === void 0) { step = 0.002; }
  2490. this.move(step);
  2491. return this;
  2492. };
  2493. PathCursor.prototype.moveBack = function (step) {
  2494. if (step === void 0) { step = 0.002; }
  2495. this.move(-step);
  2496. return this;
  2497. };
  2498. PathCursor.prototype.move = function (step) {
  2499. if (Math.abs(step) > 1) {
  2500. throw "step size should be less than 1.";
  2501. }
  2502. this.value += step;
  2503. this.ensureLimits();
  2504. this.raiseOnChange();
  2505. return this;
  2506. };
  2507. PathCursor.prototype.ensureLimits = function () {
  2508. while (this.value > 1) {
  2509. this.value -= 1;
  2510. }
  2511. while (this.value < 0) {
  2512. this.value += 1;
  2513. }
  2514. return this;
  2515. };
  2516. // used by animation engine
  2517. PathCursor.prototype.markAsDirty = function (propertyName) {
  2518. this.ensureLimits();
  2519. this.raiseOnChange();
  2520. return this;
  2521. };
  2522. PathCursor.prototype.raiseOnChange = function () {
  2523. var _this = this;
  2524. this._onchange.forEach(function (f) { return f(_this); });
  2525. return this;
  2526. };
  2527. PathCursor.prototype.onchange = function (f) {
  2528. this._onchange.push(f);
  2529. return this;
  2530. };
  2531. return PathCursor;
  2532. })();
  2533. BABYLON.PathCursor = PathCursor;
  2534. var Path2 = (function () {
  2535. function Path2(x, y) {
  2536. this._points = new Array();
  2537. this._length = 0;
  2538. this.closed = false;
  2539. this._points.push(new Vector2(x, y));
  2540. }
  2541. Path2.prototype.addLineTo = function (x, y) {
  2542. if (closed) {
  2543. BABYLON.Tools.Error("cannot add lines to closed paths");
  2544. return this;
  2545. }
  2546. var newPoint = new Vector2(x, y);
  2547. var previousPoint = this._points[this._points.length - 1];
  2548. this._points.push(newPoint);
  2549. this._length += newPoint.subtract(previousPoint).length();
  2550. return this;
  2551. };
  2552. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2553. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2554. if (closed) {
  2555. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2556. return this;
  2557. }
  2558. var startPoint = this._points[this._points.length - 1];
  2559. var midPoint = new Vector2(midX, midY);
  2560. var endPoint = new Vector2(endX, endY);
  2561. var arc = new Arc2(startPoint, midPoint, endPoint);
  2562. var increment = arc.angle.radians() / numberOfSegments;
  2563. if (arc.orientation === 0 /* CW */)
  2564. increment *= -1;
  2565. var currentAngle = arc.startAngle.radians() + increment;
  2566. for (var i = 0; i < numberOfSegments; i++) {
  2567. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2568. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2569. this.addLineTo(x, y);
  2570. currentAngle += increment;
  2571. }
  2572. return this;
  2573. };
  2574. Path2.prototype.close = function () {
  2575. this.closed = true;
  2576. return this;
  2577. };
  2578. Path2.prototype.length = function () {
  2579. var result = this._length;
  2580. if (!this.closed) {
  2581. var lastPoint = this._points[this._points.length - 1];
  2582. var firstPoint = this._points[0];
  2583. result += (firstPoint.subtract(lastPoint).length());
  2584. }
  2585. return result;
  2586. };
  2587. Path2.prototype.getPoints = function () {
  2588. return this._points;
  2589. };
  2590. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2591. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2592. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2593. return Vector2.Zero();
  2594. }
  2595. var lengthPosition = normalizedLengthPosition * this.length();
  2596. var previousOffset = 0;
  2597. for (var i = 0; i < this._points.length; i++) {
  2598. var j = (i + 1) % this._points.length;
  2599. var a = this._points[i];
  2600. var b = this._points[j];
  2601. var bToA = b.subtract(a);
  2602. var nextOffset = (bToA.length() + previousOffset);
  2603. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2604. var dir = bToA.normalize();
  2605. var localOffset = lengthPosition - previousOffset;
  2606. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2607. }
  2608. previousOffset = nextOffset;
  2609. }
  2610. BABYLON.Tools.Error("internal error");
  2611. return Vector2.Zero();
  2612. };
  2613. Path2.StartingAt = function (x, y) {
  2614. return new Path2(x, y);
  2615. };
  2616. return Path2;
  2617. })();
  2618. BABYLON.Path2 = Path2;
  2619. var Path3D = (function () {
  2620. function Path3D(path) {
  2621. this.path = path;
  2622. this._curve = new Array();
  2623. this._distances = new Array();
  2624. this._tangents = new Array();
  2625. this._normals = new Array();
  2626. this._binormals = new Array();
  2627. this._curve = path.slice(); // copy array
  2628. var l = this._curve.length;
  2629. // first and last tangents
  2630. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2631. this._tangents[0].normalize();
  2632. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2633. this._tangents[l - 1].normalize();
  2634. // normals and binormals at first point : arbitrary vector with _normalVector()
  2635. var tg0 = this._tangents[0];
  2636. var pp0 = this._normalVector(this._curve[0], tg0);
  2637. this._normals[0] = pp0;
  2638. this._normals[0].normalize();
  2639. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2640. this._normals[0].normalize();
  2641. this._distances[0] = 0;
  2642. // normals and binormals : next points
  2643. var prev; // previous vector (segment)
  2644. var cur; // current vector (segment)
  2645. var curTang; // current tangent
  2646. var prevNorm; // previous normal
  2647. var prevBinor; // previous binormal
  2648. for (var i = 1; i < l; i++) {
  2649. // tangents
  2650. prev = this._curve[i].subtract(this._curve[i - 1]);
  2651. if (i < l - 1) {
  2652. cur = this._curve[i + 1].subtract(this._curve[i]);
  2653. this._tangents[i] = prev.add(cur);
  2654. this._tangents[i].normalize();
  2655. }
  2656. this._distances[i] = this._distances[i - 1] + prev.length();
  2657. // normals and binormals
  2658. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2659. curTang = this._tangents[i];
  2660. prevNorm = this._normals[i - 1];
  2661. prevBinor = this._binormals[i - 1];
  2662. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2663. this._normals[i].normalize();
  2664. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2665. this._binormals[i].normalize();
  2666. }
  2667. }
  2668. Path3D.prototype.getCurve = function () {
  2669. return this._curve;
  2670. };
  2671. Path3D.prototype.getTangents = function () {
  2672. return this._tangents;
  2673. };
  2674. Path3D.prototype.getNormals = function () {
  2675. return this._normals;
  2676. };
  2677. Path3D.prototype.getBinormals = function () {
  2678. return this._binormals;
  2679. };
  2680. Path3D.prototype.getDistances = function () {
  2681. return this._distances;
  2682. };
  2683. // private function normalVector(v0, vt) :
  2684. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2685. Path3D.prototype._normalVector = function (v0, vt) {
  2686. var point;
  2687. if (vt.x !== 1) {
  2688. point = new Vector3(1, 0, 0);
  2689. }
  2690. else if (vt.y !== 1) {
  2691. point = new Vector3(0, 1, 0);
  2692. }
  2693. else if (vt.z !== 1) {
  2694. point = new Vector3(0, 0, 1);
  2695. }
  2696. var normal0 = Vector3.Cross(vt, point);
  2697. normal0.normalize();
  2698. return normal0;
  2699. };
  2700. return Path3D;
  2701. })();
  2702. BABYLON.Path3D = Path3D;
  2703. var Curve3 = (function () {
  2704. function Curve3(points) {
  2705. this._points = points;
  2706. }
  2707. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2708. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2709. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2710. var bez = new Array();
  2711. var step = 1 / nbPoints;
  2712. var equation = function (t, val0, val1, val2) {
  2713. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2714. return res;
  2715. };
  2716. for (var i = 0; i <= 1; i += step) {
  2717. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2718. }
  2719. return new Curve3(bez);
  2720. };
  2721. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2722. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2723. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2724. var bez = new Array();
  2725. var step = 1 / nbPoints;
  2726. var equation = function (t, val0, val1, val2, val3) {
  2727. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2728. return res;
  2729. };
  2730. for (var i = 0; i <= 1; i += step) {
  2731. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2732. }
  2733. return new Curve3(bez);
  2734. };
  2735. Curve3.prototype.getPoints = function () {
  2736. return this._points;
  2737. };
  2738. Curve3.prototype.continue = function (curve) {
  2739. var lastPoint = this._points[this._points.length - 1];
  2740. var continuedPoints = this._points.slice();
  2741. var curvePoints = curve.getPoints();
  2742. for (var i = 1; i < curvePoints.length; i++) {
  2743. continuedPoints.push(curvePoints[i].add(lastPoint));
  2744. }
  2745. return new Curve3(continuedPoints);
  2746. };
  2747. return Curve3;
  2748. })();
  2749. BABYLON.Curve3 = Curve3;
  2750. // SIMD
  2751. if (window.SIMD !== undefined) {
  2752. // Replace functions
  2753. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2754. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2755. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2756. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2757. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2758. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2759. get: function () {
  2760. return this._data[0];
  2761. },
  2762. set: function (value) {
  2763. if (!this._data) {
  2764. this._data = new Float32Array(3);
  2765. }
  2766. this._data[0] = value;
  2767. }
  2768. });
  2769. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2770. get: function () {
  2771. return this._data[1];
  2772. },
  2773. set: function (value) {
  2774. this._data[1] = value;
  2775. }
  2776. });
  2777. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2778. get: function () {
  2779. return this._data[2];
  2780. },
  2781. set: function (value) {
  2782. this._data[2] = value;
  2783. }
  2784. });
  2785. }
  2786. })(BABYLON || (BABYLON = {}));
  2787. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2788. (function (BABYLON) {
  2789. // Screenshots
  2790. var screenshotCanvas;
  2791. var cloneValue = function (source, destinationObject) {
  2792. if (!source)
  2793. return null;
  2794. if (source instanceof BABYLON.Mesh) {
  2795. return null;
  2796. }
  2797. if (source instanceof BABYLON.SubMesh) {
  2798. return source.clone(destinationObject);
  2799. }
  2800. else if (source.clone) {
  2801. return source.clone();
  2802. }
  2803. return null;
  2804. };
  2805. var Tools = (function () {
  2806. function Tools() {
  2807. }
  2808. Tools.GetFilename = function (path) {
  2809. var index = path.lastIndexOf("/");
  2810. if (index < 0)
  2811. return path;
  2812. return path.substring(index + 1);
  2813. };
  2814. Tools.GetDOMTextContent = function (element) {
  2815. var result = "";
  2816. var child = element.firstChild;
  2817. while (child) {
  2818. if (child.nodeType === 3) {
  2819. result += child.textContent;
  2820. }
  2821. child = child.nextSibling;
  2822. }
  2823. return result;
  2824. };
  2825. Tools.ToDegrees = function (angle) {
  2826. return angle * 180 / Math.PI;
  2827. };
  2828. Tools.ToRadians = function (angle) {
  2829. return angle * Math.PI / 180;
  2830. };
  2831. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2832. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2833. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2834. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2835. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2836. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2837. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2838. }
  2839. return {
  2840. minimum: minimum,
  2841. maximum: maximum
  2842. };
  2843. };
  2844. Tools.ExtractMinAndMax = function (positions, start, count) {
  2845. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2846. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2847. for (var index = start; index < start + count; index++) {
  2848. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2849. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2850. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2851. }
  2852. return {
  2853. minimum: minimum,
  2854. maximum: maximum
  2855. };
  2856. };
  2857. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2858. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2859. return undefined;
  2860. return Array.isArray(obj) ? obj : [obj];
  2861. };
  2862. // Misc.
  2863. Tools.GetPointerPrefix = function () {
  2864. var eventPrefix = "pointer";
  2865. // Check if hand.js is referenced or if the browser natively supports pointer events
  2866. if (!navigator.pointerEnabled) {
  2867. eventPrefix = "mouse";
  2868. }
  2869. return eventPrefix;
  2870. };
  2871. Tools.QueueNewFrame = function (func) {
  2872. if (window.requestAnimationFrame)
  2873. window.requestAnimationFrame(func);
  2874. else if (window.msRequestAnimationFrame)
  2875. window.msRequestAnimationFrame(func);
  2876. else if (window.webkitRequestAnimationFrame)
  2877. window.webkitRequestAnimationFrame(func);
  2878. else if (window.mozRequestAnimationFrame)
  2879. window.mozRequestAnimationFrame(func);
  2880. else if (window.oRequestAnimationFrame)
  2881. window.oRequestAnimationFrame(func);
  2882. else {
  2883. window.setTimeout(func, 16);
  2884. }
  2885. };
  2886. Tools.RequestFullscreen = function (element) {
  2887. if (element.requestFullscreen)
  2888. element.requestFullscreen();
  2889. else if (element.msRequestFullscreen)
  2890. element.msRequestFullscreen();
  2891. else if (element.webkitRequestFullscreen)
  2892. element.webkitRequestFullscreen();
  2893. else if (element.mozRequestFullScreen)
  2894. element.mozRequestFullScreen();
  2895. };
  2896. Tools.ExitFullscreen = function () {
  2897. if (document.exitFullscreen) {
  2898. document.exitFullscreen();
  2899. }
  2900. else if (document.mozCancelFullScreen) {
  2901. document.mozCancelFullScreen();
  2902. }
  2903. else if (document.webkitCancelFullScreen) {
  2904. document.webkitCancelFullScreen();
  2905. }
  2906. else if (document.msCancelFullScreen) {
  2907. document.msCancelFullScreen();
  2908. }
  2909. };
  2910. // External files
  2911. Tools.CleanUrl = function (url) {
  2912. url = url.replace(/#/mg, "%23");
  2913. return url;
  2914. };
  2915. Tools.LoadImage = function (url, onload, onerror, database) {
  2916. url = Tools.CleanUrl(url);
  2917. var img = new Image();
  2918. if (url.substr(0, 5) !== "data:")
  2919. img.crossOrigin = 'anonymous';
  2920. img.onload = function () {
  2921. onload(img);
  2922. };
  2923. img.onerror = function (err) {
  2924. onerror(img, err);
  2925. };
  2926. var noIndexedDB = function () {
  2927. img.src = url;
  2928. };
  2929. var loadFromIndexedDB = function () {
  2930. database.loadImageFromDB(url, img);
  2931. };
  2932. //ANY database to do!
  2933. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2934. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2935. }
  2936. else {
  2937. if (url.indexOf("file:") === -1) {
  2938. noIndexedDB();
  2939. }
  2940. else {
  2941. try {
  2942. var textureName = url.substring(5);
  2943. var blobURL;
  2944. try {
  2945. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2946. }
  2947. catch (ex) {
  2948. // Chrome doesn't support oneTimeOnly parameter
  2949. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2950. }
  2951. img.src = blobURL;
  2952. }
  2953. catch (e) {
  2954. Tools.Log("Error while trying to load texture: " + textureName);
  2955. img.src = null;
  2956. }
  2957. }
  2958. }
  2959. return img;
  2960. };
  2961. //ANY
  2962. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2963. url = Tools.CleanUrl(url);
  2964. var noIndexedDB = function () {
  2965. var request = new XMLHttpRequest();
  2966. var loadUrl = Tools.BaseUrl + url;
  2967. request.open('GET', loadUrl, true);
  2968. if (useArrayBuffer) {
  2969. request.responseType = "arraybuffer";
  2970. }
  2971. request.onprogress = progressCallBack;
  2972. request.onreadystatechange = function () {
  2973. if (request.readyState === 4) {
  2974. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2975. callback(!useArrayBuffer ? request.responseText : request.response);
  2976. }
  2977. else {
  2978. if (onError) {
  2979. onError();
  2980. }
  2981. else {
  2982. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2983. }
  2984. }
  2985. }
  2986. };
  2987. request.send(null);
  2988. };
  2989. var loadFromIndexedDB = function () {
  2990. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2991. };
  2992. if (url.indexOf("file:") !== -1) {
  2993. var fileName = url.substring(5);
  2994. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2995. }
  2996. else {
  2997. // Caching all files
  2998. if (database && database.enableSceneOffline) {
  2999. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3000. }
  3001. else {
  3002. noIndexedDB();
  3003. }
  3004. }
  3005. };
  3006. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3007. var reader = new FileReader();
  3008. reader.onload = function (e) {
  3009. //target doesn't have result from ts 1.3
  3010. callback(e.target['result']);
  3011. };
  3012. reader.onprogress = progressCallback;
  3013. reader.readAsDataURL(fileToLoad);
  3014. };
  3015. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3016. var reader = new FileReader();
  3017. reader.onerror = function (e) {
  3018. Tools.Log("Error while reading file: " + fileToLoad.name);
  3019. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3020. };
  3021. reader.onload = function (e) {
  3022. //target doesn't have result from ts 1.3
  3023. callback(e.target['result']);
  3024. };
  3025. reader.onprogress = progressCallBack;
  3026. if (!useArrayBuffer) {
  3027. // Asynchronous read
  3028. reader.readAsText(fileToLoad);
  3029. }
  3030. else {
  3031. reader.readAsArrayBuffer(fileToLoad);
  3032. }
  3033. };
  3034. // Misc.
  3035. Tools.Clamp = function (value, min, max) {
  3036. if (min === void 0) { min = 0; }
  3037. if (max === void 0) { max = 1; }
  3038. return Math.min(max, Math.max(min, value));
  3039. };
  3040. // Returns -1 when value is a negative number and
  3041. // +1 when value is a positive number.
  3042. Tools.Sign = function (value) {
  3043. value = +value; // convert to a number
  3044. if (value === 0 || isNaN(value))
  3045. return value;
  3046. return value > 0 ? 1 : -1;
  3047. };
  3048. Tools.Format = function (value, decimals) {
  3049. if (decimals === void 0) { decimals = 2; }
  3050. return value.toFixed(decimals);
  3051. };
  3052. Tools.CheckExtends = function (v, min, max) {
  3053. if (v.x < min.x)
  3054. min.x = v.x;
  3055. if (v.y < min.y)
  3056. min.y = v.y;
  3057. if (v.z < min.z)
  3058. min.z = v.z;
  3059. if (v.x > max.x)
  3060. max.x = v.x;
  3061. if (v.y > max.y)
  3062. max.y = v.y;
  3063. if (v.z > max.z)
  3064. max.z = v.z;
  3065. };
  3066. Tools.WithinEpsilon = function (a, b, epsilon) {
  3067. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3068. var num = a - b;
  3069. return -epsilon <= num && num <= epsilon;
  3070. };
  3071. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3072. for (var prop in source) {
  3073. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3074. continue;
  3075. }
  3076. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3077. continue;
  3078. }
  3079. var sourceValue = source[prop];
  3080. var typeOfSourceValue = typeof sourceValue;
  3081. if (typeOfSourceValue === "function") {
  3082. continue;
  3083. }
  3084. if (typeOfSourceValue === "object") {
  3085. if (sourceValue instanceof Array) {
  3086. destination[prop] = [];
  3087. if (sourceValue.length > 0) {
  3088. if (typeof sourceValue[0] == "object") {
  3089. for (var index = 0; index < sourceValue.length; index++) {
  3090. var clonedValue = cloneValue(sourceValue[index], destination);
  3091. if (destination[prop].indexOf(clonedValue) === -1) {
  3092. destination[prop].push(clonedValue);
  3093. }
  3094. }
  3095. }
  3096. else {
  3097. destination[prop] = sourceValue.slice(0);
  3098. }
  3099. }
  3100. }
  3101. else {
  3102. destination[prop] = cloneValue(sourceValue, destination);
  3103. }
  3104. }
  3105. else {
  3106. destination[prop] = sourceValue;
  3107. }
  3108. }
  3109. };
  3110. Tools.IsEmpty = function (obj) {
  3111. for (var i in obj) {
  3112. return false;
  3113. }
  3114. return true;
  3115. };
  3116. Tools.RegisterTopRootEvents = function (events) {
  3117. for (var index = 0; index < events.length; index++) {
  3118. var event = events[index];
  3119. window.addEventListener(event.name, event.handler, false);
  3120. try {
  3121. if (window.parent) {
  3122. window.parent.addEventListener(event.name, event.handler, false);
  3123. }
  3124. }
  3125. catch (e) {
  3126. }
  3127. }
  3128. };
  3129. Tools.UnregisterTopRootEvents = function (events) {
  3130. for (var index = 0; index < events.length; index++) {
  3131. var event = events[index];
  3132. window.removeEventListener(event.name, event.handler);
  3133. try {
  3134. if (window.parent) {
  3135. window.parent.removeEventListener(event.name, event.handler);
  3136. }
  3137. }
  3138. catch (e) {
  3139. }
  3140. }
  3141. };
  3142. Tools.DumpFramebuffer = function (width, height, engine) {
  3143. // Read the contents of the framebuffer
  3144. var numberOfChannelsByLine = width * 4;
  3145. var halfHeight = height / 2;
  3146. //Reading datas from WebGL
  3147. var data = engine.readPixels(0, 0, width, height);
  3148. for (var i = 0; i < halfHeight; i++) {
  3149. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3150. var currentCell = j + i * numberOfChannelsByLine;
  3151. var targetLine = height - i - 1;
  3152. var targetCell = j + targetLine * numberOfChannelsByLine;
  3153. var temp = data[currentCell];
  3154. data[currentCell] = data[targetCell];
  3155. data[targetCell] = temp;
  3156. }
  3157. }
  3158. // Create a 2D canvas to store the result
  3159. if (!screenshotCanvas) {
  3160. screenshotCanvas = document.createElement('canvas');
  3161. }
  3162. screenshotCanvas.width = width;
  3163. screenshotCanvas.height = height;
  3164. var context = screenshotCanvas.getContext('2d');
  3165. // Copy the pixels to a 2D canvas
  3166. var imageData = context.createImageData(width, height);
  3167. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3168. var castData = imageData.data;
  3169. castData.set(data);
  3170. context.putImageData(imageData, 0, 0);
  3171. var base64Image = screenshotCanvas.toDataURL();
  3172. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3173. if (("download" in document.createElement("a"))) {
  3174. var a = window.document.createElement("a");
  3175. a.href = base64Image;
  3176. var date = new Date();
  3177. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3178. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3179. window.document.body.appendChild(a);
  3180. a.addEventListener("click", function () {
  3181. a.parentElement.removeChild(a);
  3182. });
  3183. a.click();
  3184. }
  3185. else {
  3186. var newWindow = window.open("");
  3187. var img = newWindow.document.createElement("img");
  3188. img.src = base64Image;
  3189. newWindow.document.body.appendChild(img);
  3190. }
  3191. };
  3192. Tools.CreateScreenshot = function (engine, camera, size) {
  3193. var width;
  3194. var height;
  3195. var scene = camera.getScene();
  3196. var previousCamera = null;
  3197. if (scene.activeCamera !== camera) {
  3198. previousCamera = scene.activeCamera;
  3199. scene.activeCamera = camera;
  3200. }
  3201. //If a precision value is specified
  3202. if (size.precision) {
  3203. width = Math.round(engine.getRenderWidth() * size.precision);
  3204. height = Math.round(width / engine.getAspectRatio(camera));
  3205. size = { width: width, height: height };
  3206. }
  3207. else if (size.width && size.height) {
  3208. width = size.width;
  3209. height = size.height;
  3210. }
  3211. else if (size.width && !size.height) {
  3212. width = size.width;
  3213. height = Math.round(width / engine.getAspectRatio(camera));
  3214. size = { width: width, height: height };
  3215. }
  3216. else if (size.height && !size.width) {
  3217. height = size.height;
  3218. width = Math.round(height * engine.getAspectRatio(camera));
  3219. size = { width: width, height: height };
  3220. }
  3221. else if (!isNaN(size)) {
  3222. height = size;
  3223. width = size;
  3224. }
  3225. else {
  3226. Tools.Error("Invalid 'size' parameter !");
  3227. return;
  3228. }
  3229. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3230. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3231. texture.renderList = scene.meshes;
  3232. texture.onAfterRender = function () {
  3233. Tools.DumpFramebuffer(width, height, engine);
  3234. };
  3235. scene.incrementRenderId();
  3236. texture.render(true);
  3237. texture.dispose();
  3238. if (previousCamera) {
  3239. scene.activeCamera = previousCamera;
  3240. }
  3241. };
  3242. // XHR response validator for local file scenario
  3243. Tools.ValidateXHRData = function (xhr, dataType) {
  3244. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3245. if (dataType === void 0) { dataType = 7; }
  3246. try {
  3247. if (dataType & 1) {
  3248. if (xhr.responseText && xhr.responseText.length > 0) {
  3249. return true;
  3250. }
  3251. else if (dataType === 1) {
  3252. return false;
  3253. }
  3254. }
  3255. if (dataType & 2) {
  3256. // Check header width and height since there is no "TGA" magic number
  3257. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3258. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3259. return true;
  3260. }
  3261. else if (dataType === 2) {
  3262. return false;
  3263. }
  3264. }
  3265. if (dataType & 4) {
  3266. // Check for the "DDS" magic number
  3267. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3268. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3269. return true;
  3270. }
  3271. else {
  3272. return false;
  3273. }
  3274. }
  3275. }
  3276. catch (e) {
  3277. }
  3278. return false;
  3279. };
  3280. Object.defineProperty(Tools, "NoneLogLevel", {
  3281. get: function () {
  3282. return Tools._NoneLogLevel;
  3283. },
  3284. enumerable: true,
  3285. configurable: true
  3286. });
  3287. Object.defineProperty(Tools, "MessageLogLevel", {
  3288. get: function () {
  3289. return Tools._MessageLogLevel;
  3290. },
  3291. enumerable: true,
  3292. configurable: true
  3293. });
  3294. Object.defineProperty(Tools, "WarningLogLevel", {
  3295. get: function () {
  3296. return Tools._WarningLogLevel;
  3297. },
  3298. enumerable: true,
  3299. configurable: true
  3300. });
  3301. Object.defineProperty(Tools, "ErrorLogLevel", {
  3302. get: function () {
  3303. return Tools._ErrorLogLevel;
  3304. },
  3305. enumerable: true,
  3306. configurable: true
  3307. });
  3308. Object.defineProperty(Tools, "AllLogLevel", {
  3309. get: function () {
  3310. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3311. },
  3312. enumerable: true,
  3313. configurable: true
  3314. });
  3315. Tools._AddLogEntry = function (entry) {
  3316. Tools._LogCache = entry + Tools._LogCache;
  3317. if (Tools.OnNewCacheEntry) {
  3318. Tools.OnNewCacheEntry(entry);
  3319. }
  3320. };
  3321. Tools._FormatMessage = function (message) {
  3322. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3323. var date = new Date();
  3324. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3325. };
  3326. Tools._LogDisabled = function (message) {
  3327. // nothing to do
  3328. };
  3329. Tools._LogEnabled = function (message) {
  3330. var formattedMessage = Tools._FormatMessage(message);
  3331. console.log("BJS - " + formattedMessage);
  3332. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3333. Tools._AddLogEntry(entry);
  3334. };
  3335. Tools._WarnDisabled = function (message) {
  3336. // nothing to do
  3337. };
  3338. Tools._WarnEnabled = function (message) {
  3339. var formattedMessage = Tools._FormatMessage(message);
  3340. console.warn("BJS - " + formattedMessage);
  3341. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3342. Tools._AddLogEntry(entry);
  3343. };
  3344. Tools._ErrorDisabled = function (message) {
  3345. // nothing to do
  3346. };
  3347. Tools._ErrorEnabled = function (message) {
  3348. var formattedMessage = Tools._FormatMessage(message);
  3349. console.error("BJS - " + formattedMessage);
  3350. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3351. Tools._AddLogEntry(entry);
  3352. };
  3353. Object.defineProperty(Tools, "LogCache", {
  3354. get: function () {
  3355. return Tools._LogCache;
  3356. },
  3357. enumerable: true,
  3358. configurable: true
  3359. });
  3360. Object.defineProperty(Tools, "LogLevels", {
  3361. set: function (level) {
  3362. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3363. Tools.Log = Tools._LogEnabled;
  3364. }
  3365. else {
  3366. Tools.Log = Tools._LogDisabled;
  3367. }
  3368. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3369. Tools.Warn = Tools._WarnEnabled;
  3370. }
  3371. else {
  3372. Tools.Warn = Tools._WarnDisabled;
  3373. }
  3374. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3375. Tools.Error = Tools._ErrorEnabled;
  3376. }
  3377. else {
  3378. Tools.Error = Tools._ErrorDisabled;
  3379. }
  3380. },
  3381. enumerable: true,
  3382. configurable: true
  3383. });
  3384. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3385. get: function () {
  3386. return Tools._PerformanceNoneLogLevel;
  3387. },
  3388. enumerable: true,
  3389. configurable: true
  3390. });
  3391. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3392. get: function () {
  3393. return Tools._PerformanceUserMarkLogLevel;
  3394. },
  3395. enumerable: true,
  3396. configurable: true
  3397. });
  3398. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3399. get: function () {
  3400. return Tools._PerformanceConsoleLogLevel;
  3401. },
  3402. enumerable: true,
  3403. configurable: true
  3404. });
  3405. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3406. set: function (level) {
  3407. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3408. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3409. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3410. return;
  3411. }
  3412. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3413. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3414. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3415. return;
  3416. }
  3417. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3418. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3419. },
  3420. enumerable: true,
  3421. configurable: true
  3422. });
  3423. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3424. };
  3425. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3426. };
  3427. Tools._StartUserMark = function (counterName, condition) {
  3428. if (condition === void 0) { condition = true; }
  3429. if (!condition || !Tools._performance.mark) {
  3430. return;
  3431. }
  3432. Tools._performance.mark(counterName + "-Begin");
  3433. };
  3434. Tools._EndUserMark = function (counterName, condition) {
  3435. if (condition === void 0) { condition = true; }
  3436. if (!condition || !Tools._performance.mark) {
  3437. return;
  3438. }
  3439. Tools._performance.mark(counterName + "-End");
  3440. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3441. };
  3442. Tools._StartPerformanceConsole = function (counterName, condition) {
  3443. if (condition === void 0) { condition = true; }
  3444. if (!condition) {
  3445. return;
  3446. }
  3447. Tools._StartUserMark(counterName, condition);
  3448. if (console.time) {
  3449. console.time(counterName);
  3450. }
  3451. };
  3452. Tools._EndPerformanceConsole = function (counterName, condition) {
  3453. if (condition === void 0) { condition = true; }
  3454. if (!condition) {
  3455. return;
  3456. }
  3457. Tools._EndUserMark(counterName, condition);
  3458. if (console.time) {
  3459. console.timeEnd(counterName);
  3460. }
  3461. };
  3462. Object.defineProperty(Tools, "Now", {
  3463. get: function () {
  3464. if (window.performance && window.performance.now) {
  3465. return window.performance.now();
  3466. }
  3467. return new Date().getTime();
  3468. },
  3469. enumerable: true,
  3470. configurable: true
  3471. });
  3472. // Deprecated
  3473. Tools.GetFps = function () {
  3474. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3475. return 0;
  3476. };
  3477. Tools.BaseUrl = "";
  3478. Tools.GetExponantOfTwo = function (value, max) {
  3479. var count = 1;
  3480. do {
  3481. count *= 2;
  3482. } while (count < value);
  3483. if (count > max)
  3484. count = max;
  3485. return count;
  3486. };
  3487. // Logs
  3488. Tools._NoneLogLevel = 0;
  3489. Tools._MessageLogLevel = 1;
  3490. Tools._WarningLogLevel = 2;
  3491. Tools._ErrorLogLevel = 4;
  3492. Tools._LogCache = "";
  3493. Tools.Log = Tools._LogEnabled;
  3494. Tools.Warn = Tools._WarnEnabled;
  3495. Tools.Error = Tools._ErrorEnabled;
  3496. // Performances
  3497. Tools._PerformanceNoneLogLevel = 0;
  3498. Tools._PerformanceUserMarkLogLevel = 1;
  3499. Tools._PerformanceConsoleLogLevel = 2;
  3500. Tools._performance = window.performance;
  3501. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3502. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3503. return Tools;
  3504. })();
  3505. BABYLON.Tools = Tools;
  3506. /**
  3507. * An implementation of a loop for asynchronous functions.
  3508. */
  3509. var AsyncLoop = (function () {
  3510. /**
  3511. * Constroctor.
  3512. * @param iterations the number of iterations.
  3513. * @param _fn the function to run each iteration
  3514. * @param _successCallback the callback that will be called upon succesful execution
  3515. * @param offset starting offset.
  3516. */
  3517. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3518. if (offset === void 0) { offset = 0; }
  3519. this.iterations = iterations;
  3520. this._fn = _fn;
  3521. this._successCallback = _successCallback;
  3522. this.index = offset - 1;
  3523. this._done = false;
  3524. }
  3525. /**
  3526. * Execute the next iteration. Must be called after the last iteration was finished.
  3527. */
  3528. AsyncLoop.prototype.executeNext = function () {
  3529. if (!this._done) {
  3530. if (this.index + 1 < this.iterations) {
  3531. ++this.index;
  3532. this._fn(this);
  3533. }
  3534. else {
  3535. this.breakLoop();
  3536. }
  3537. }
  3538. };
  3539. /**
  3540. * Break the loop and run the success callback.
  3541. */
  3542. AsyncLoop.prototype.breakLoop = function () {
  3543. this._done = true;
  3544. this._successCallback();
  3545. };
  3546. /**
  3547. * Helper function
  3548. */
  3549. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3550. if (offset === void 0) { offset = 0; }
  3551. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3552. loop.executeNext();
  3553. return loop;
  3554. };
  3555. /**
  3556. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3557. * @param iterations total number of iterations
  3558. * @param syncedIterations number of synchronous iterations in each async iteration.
  3559. * @param fn the function to call each iteration.
  3560. * @param callback a success call back that will be called when iterating stops.
  3561. * @param breakFunction a break condition (optional)
  3562. * @param timeout timeout settings for the setTimeout function. default - 0.
  3563. * @constructor
  3564. */
  3565. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3566. if (timeout === void 0) { timeout = 0; }
  3567. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3568. if (breakFunction && breakFunction())
  3569. loop.breakLoop();
  3570. else {
  3571. setTimeout(function () {
  3572. for (var i = 0; i < syncedIterations; ++i) {
  3573. var iteration = (loop.index * syncedIterations) + i;
  3574. if (iteration >= iterations)
  3575. break;
  3576. fn(iteration);
  3577. if (breakFunction && breakFunction()) {
  3578. loop.breakLoop();
  3579. break;
  3580. }
  3581. }
  3582. loop.executeNext();
  3583. }, timeout);
  3584. }
  3585. }, callback);
  3586. };
  3587. return AsyncLoop;
  3588. })();
  3589. BABYLON.AsyncLoop = AsyncLoop;
  3590. })(BABYLON || (BABYLON = {}));
  3591. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3592. (function (BABYLON) {
  3593. var _DepthCullingState = (function () {
  3594. function _DepthCullingState() {
  3595. this._isDepthTestDirty = false;
  3596. this._isDepthMaskDirty = false;
  3597. this._isDepthFuncDirty = false;
  3598. this._isCullFaceDirty = false;
  3599. this._isCullDirty = false;
  3600. }
  3601. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3602. get: function () {
  3603. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3604. },
  3605. enumerable: true,
  3606. configurable: true
  3607. });
  3608. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3609. get: function () {
  3610. return this._cullFace;
  3611. },
  3612. set: function (value) {
  3613. if (this._cullFace === value) {
  3614. return;
  3615. }
  3616. this._cullFace = value;
  3617. this._isCullFaceDirty = true;
  3618. },
  3619. enumerable: true,
  3620. configurable: true
  3621. });
  3622. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3623. get: function () {
  3624. return this._cull;
  3625. },
  3626. set: function (value) {
  3627. if (this._cull === value) {
  3628. return;
  3629. }
  3630. this._cull = value;
  3631. this._isCullDirty = true;
  3632. },
  3633. enumerable: true,
  3634. configurable: true
  3635. });
  3636. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3637. get: function () {
  3638. return this._depthFunc;
  3639. },
  3640. set: function (value) {
  3641. if (this._depthFunc === value) {
  3642. return;
  3643. }
  3644. this._depthFunc = value;
  3645. this._isDepthFuncDirty = true;
  3646. },
  3647. enumerable: true,
  3648. configurable: true
  3649. });
  3650. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3651. get: function () {
  3652. return this._depthMask;
  3653. },
  3654. set: function (value) {
  3655. if (this._depthMask === value) {
  3656. return;
  3657. }
  3658. this._depthMask = value;
  3659. this._isDepthMaskDirty = true;
  3660. },
  3661. enumerable: true,
  3662. configurable: true
  3663. });
  3664. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3665. get: function () {
  3666. return this._depthTest;
  3667. },
  3668. set: function (value) {
  3669. if (this._depthTest === value) {
  3670. return;
  3671. }
  3672. this._depthTest = value;
  3673. this._isDepthTestDirty = true;
  3674. },
  3675. enumerable: true,
  3676. configurable: true
  3677. });
  3678. _DepthCullingState.prototype.reset = function () {
  3679. this._depthMask = true;
  3680. this._depthTest = true;
  3681. this._depthFunc = null;
  3682. this._cull = null;
  3683. this._cullFace = null;
  3684. this._isDepthTestDirty = true;
  3685. this._isDepthMaskDirty = true;
  3686. this._isDepthFuncDirty = false;
  3687. this._isCullFaceDirty = false;
  3688. this._isCullDirty = false;
  3689. };
  3690. _DepthCullingState.prototype.apply = function (gl) {
  3691. if (!this.isDirty) {
  3692. return;
  3693. }
  3694. // Cull
  3695. if (this._isCullDirty) {
  3696. if (this.cull) {
  3697. gl.enable(gl.CULL_FACE);
  3698. }
  3699. else {
  3700. gl.disable(gl.CULL_FACE);
  3701. }
  3702. this._isCullDirty = false;
  3703. }
  3704. // Cull face
  3705. if (this._isCullFaceDirty) {
  3706. gl.cullFace(this.cullFace);
  3707. this._isCullFaceDirty = false;
  3708. }
  3709. // Depth mask
  3710. if (this._isDepthMaskDirty) {
  3711. gl.depthMask(this.depthMask);
  3712. this._isDepthMaskDirty = false;
  3713. }
  3714. // Depth test
  3715. if (this._isDepthTestDirty) {
  3716. if (this.depthTest) {
  3717. gl.enable(gl.DEPTH_TEST);
  3718. }
  3719. else {
  3720. gl.disable(gl.DEPTH_TEST);
  3721. }
  3722. this._isDepthTestDirty = false;
  3723. }
  3724. // Depth func
  3725. if (this._isDepthFuncDirty) {
  3726. gl.depthFunc(this.depthFunc);
  3727. this._isDepthFuncDirty = false;
  3728. }
  3729. };
  3730. return _DepthCullingState;
  3731. })();
  3732. BABYLON._DepthCullingState = _DepthCullingState;
  3733. var _AlphaState = (function () {
  3734. function _AlphaState() {
  3735. this._isAlphaBlendDirty = false;
  3736. this._isBlendFunctionParametersDirty = false;
  3737. this._alphaBlend = false;
  3738. this._blendFunctionParameters = new Array(4);
  3739. }
  3740. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3741. get: function () {
  3742. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3743. },
  3744. enumerable: true,
  3745. configurable: true
  3746. });
  3747. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3748. get: function () {
  3749. return this._alphaBlend;
  3750. },
  3751. set: function (value) {
  3752. if (this._alphaBlend === value) {
  3753. return;
  3754. }
  3755. this._alphaBlend = value;
  3756. this._isAlphaBlendDirty = true;
  3757. },
  3758. enumerable: true,
  3759. configurable: true
  3760. });
  3761. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3762. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3763. return;
  3764. }
  3765. this._blendFunctionParameters[0] = value0;
  3766. this._blendFunctionParameters[1] = value1;
  3767. this._blendFunctionParameters[2] = value2;
  3768. this._blendFunctionParameters[3] = value3;
  3769. this._isBlendFunctionParametersDirty = true;
  3770. };
  3771. _AlphaState.prototype.reset = function () {
  3772. this._alphaBlend = false;
  3773. this._blendFunctionParameters[0] = null;
  3774. this._blendFunctionParameters[1] = null;
  3775. this._blendFunctionParameters[2] = null;
  3776. this._blendFunctionParameters[3] = null;
  3777. this._isAlphaBlendDirty = true;
  3778. this._isBlendFunctionParametersDirty = false;
  3779. };
  3780. _AlphaState.prototype.apply = function (gl) {
  3781. if (!this.isDirty) {
  3782. return;
  3783. }
  3784. // Alpha blend
  3785. if (this._isAlphaBlendDirty) {
  3786. if (this._alphaBlend) {
  3787. gl.enable(gl.BLEND);
  3788. }
  3789. else {
  3790. gl.disable(gl.BLEND);
  3791. }
  3792. this._isAlphaBlendDirty = false;
  3793. }
  3794. // Alpha function
  3795. if (this._isBlendFunctionParametersDirty) {
  3796. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3797. this._isBlendFunctionParametersDirty = false;
  3798. }
  3799. };
  3800. return _AlphaState;
  3801. })();
  3802. BABYLON._AlphaState = _AlphaState;
  3803. var compileShader = function (gl, source, type, defines) {
  3804. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3805. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3806. gl.compileShader(shader);
  3807. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3808. throw new Error(gl.getShaderInfoLog(shader));
  3809. }
  3810. return shader;
  3811. };
  3812. var getWebGLTextureType = function (gl, type) {
  3813. var textureType = gl.UNSIGNED_BYTE;
  3814. if (type === Engine.TEXTURETYPE_FLOAT)
  3815. textureType = gl.FLOAT;
  3816. return textureType;
  3817. };
  3818. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3819. var magFilter = gl.NEAREST;
  3820. var minFilter = gl.NEAREST;
  3821. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3822. magFilter = gl.LINEAR;
  3823. if (generateMipMaps) {
  3824. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3825. }
  3826. else {
  3827. minFilter = gl.LINEAR;
  3828. }
  3829. }
  3830. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3831. magFilter = gl.LINEAR;
  3832. if (generateMipMaps) {
  3833. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3834. }
  3835. else {
  3836. minFilter = gl.LINEAR;
  3837. }
  3838. }
  3839. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3840. magFilter = gl.NEAREST;
  3841. if (generateMipMaps) {
  3842. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3843. }
  3844. else {
  3845. minFilter = gl.NEAREST;
  3846. }
  3847. }
  3848. return {
  3849. min: minFilter,
  3850. mag: magFilter
  3851. };
  3852. };
  3853. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3854. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3855. var engine = scene.getEngine();
  3856. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3857. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3858. gl.bindTexture(gl.TEXTURE_2D, texture);
  3859. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3860. processFunction(potWidth, potHeight);
  3861. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3862. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3863. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3864. if (!noMipmap && !isCompressed) {
  3865. gl.generateMipmap(gl.TEXTURE_2D);
  3866. }
  3867. gl.bindTexture(gl.TEXTURE_2D, null);
  3868. engine._activeTexturesCache = [];
  3869. texture._baseWidth = width;
  3870. texture._baseHeight = height;
  3871. texture._width = potWidth;
  3872. texture._height = potHeight;
  3873. texture.isReady = true;
  3874. texture.samplingMode = samplingMode;
  3875. scene._removePendingData(texture);
  3876. };
  3877. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3878. var onload = function () {
  3879. loadedImages[index] = img;
  3880. loadedImages._internalCount++;
  3881. scene._removePendingData(img);
  3882. if (loadedImages._internalCount === 6) {
  3883. onfinish(loadedImages);
  3884. }
  3885. };
  3886. var onerror = function () {
  3887. scene._removePendingData(img);
  3888. };
  3889. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3890. scene._addPendingData(img);
  3891. };
  3892. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3893. var loadedImages = [];
  3894. loadedImages._internalCount = 0;
  3895. for (var index = 0; index < 6; index++) {
  3896. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3897. }
  3898. };
  3899. var EngineCapabilities = (function () {
  3900. function EngineCapabilities() {
  3901. }
  3902. return EngineCapabilities;
  3903. })();
  3904. BABYLON.EngineCapabilities = EngineCapabilities;
  3905. /**
  3906. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3907. */
  3908. var Engine = (function () {
  3909. /**
  3910. * @constructor
  3911. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3912. * @param {boolean} [antialias] - enable antialias
  3913. * @param options - further options to be sent to the getContext function
  3914. */
  3915. function Engine(canvas, antialias, options) {
  3916. var _this = this;
  3917. // Public members
  3918. this.isFullscreen = false;
  3919. this.isPointerLock = false;
  3920. this.cullBackFaces = true;
  3921. this.renderEvenInBackground = true;
  3922. this.scenes = new Array();
  3923. this._windowIsBackground = false;
  3924. this._loadingDivBackgroundColor = "black";
  3925. this._drawCalls = 0;
  3926. this._renderingQueueLaunched = false;
  3927. this._activeRenderLoops = [];
  3928. // FPS
  3929. this.fpsRange = 60;
  3930. this.previousFramesDuration = [];
  3931. this.fps = 60;
  3932. this.deltaTime = 0;
  3933. // States
  3934. this._depthCullingState = new _DepthCullingState();
  3935. this._alphaState = new _AlphaState();
  3936. this._alphaMode = Engine.ALPHA_DISABLE;
  3937. // Cache
  3938. this._loadedTexturesCache = new Array();
  3939. this._activeTexturesCache = new Array();
  3940. this._compiledEffects = {};
  3941. this._uintIndicesCurrentlySet = false;
  3942. this._renderingCanvas = canvas;
  3943. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3944. options = options || {};
  3945. options.antialias = antialias;
  3946. try {
  3947. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3948. }
  3949. catch (e) {
  3950. throw new Error("WebGL not supported");
  3951. }
  3952. if (!this._gl) {
  3953. throw new Error("WebGL not supported");
  3954. }
  3955. this._onBlur = function () {
  3956. _this._windowIsBackground = true;
  3957. };
  3958. this._onFocus = function () {
  3959. _this._windowIsBackground = false;
  3960. };
  3961. window.addEventListener("blur", this._onBlur);
  3962. window.addEventListener("focus", this._onFocus);
  3963. // Textures
  3964. this._workingCanvas = document.createElement("canvas");
  3965. this._workingContext = this._workingCanvas.getContext("2d");
  3966. // Viewport
  3967. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3968. this.resize();
  3969. // Caps
  3970. this._caps = new EngineCapabilities();
  3971. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3972. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3973. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3974. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3975. // Infos
  3976. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3977. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3978. if (rendererInfo != null) {
  3979. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3980. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3981. }
  3982. if (!this._glVendor) {
  3983. this._glVendor = "Unknown vendor";
  3984. }
  3985. if (!this._glRenderer) {
  3986. this._glRenderer = "Unknown renderer";
  3987. }
  3988. // Extensions
  3989. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3990. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3991. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3992. 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');
  3993. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3994. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3995. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3996. // Depth buffer
  3997. this.setDepthBuffer(true);
  3998. this.setDepthFunctionToLessOrEqual();
  3999. this.setDepthWrite(true);
  4000. // Fullscreen
  4001. this._onFullscreenChange = function () {
  4002. if (document.fullscreen !== undefined) {
  4003. _this.isFullscreen = document.fullscreen;
  4004. }
  4005. else if (document.mozFullScreen !== undefined) {
  4006. _this.isFullscreen = document.mozFullScreen;
  4007. }
  4008. else if (document.webkitIsFullScreen !== undefined) {
  4009. _this.isFullscreen = document.webkitIsFullScreen;
  4010. }
  4011. else if (document.msIsFullScreen !== undefined) {
  4012. _this.isFullscreen = document.msIsFullScreen;
  4013. }
  4014. // Pointer lock
  4015. if (_this.isFullscreen && _this._pointerLockRequested) {
  4016. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4017. if (canvas.requestPointerLock) {
  4018. canvas.requestPointerLock();
  4019. }
  4020. }
  4021. };
  4022. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4023. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4024. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4025. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4026. // Pointer lock
  4027. this._onPointerLockChange = function () {
  4028. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4029. };
  4030. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4031. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4032. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4033. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4034. if (!Engine.audioEngine) {
  4035. Engine.audioEngine = new BABYLON.AudioEngine();
  4036. }
  4037. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4038. }
  4039. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4040. get: function () {
  4041. return Engine._ALPHA_DISABLE;
  4042. },
  4043. enumerable: true,
  4044. configurable: true
  4045. });
  4046. Object.defineProperty(Engine, "ALPHA_ADD", {
  4047. get: function () {
  4048. return Engine._ALPHA_ADD;
  4049. },
  4050. enumerable: true,
  4051. configurable: true
  4052. });
  4053. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4054. get: function () {
  4055. return Engine._ALPHA_COMBINE;
  4056. },
  4057. enumerable: true,
  4058. configurable: true
  4059. });
  4060. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4061. get: function () {
  4062. return Engine._DELAYLOADSTATE_NONE;
  4063. },
  4064. enumerable: true,
  4065. configurable: true
  4066. });
  4067. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4068. get: function () {
  4069. return Engine._DELAYLOADSTATE_LOADED;
  4070. },
  4071. enumerable: true,
  4072. configurable: true
  4073. });
  4074. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4075. get: function () {
  4076. return Engine._DELAYLOADSTATE_LOADING;
  4077. },
  4078. enumerable: true,
  4079. configurable: true
  4080. });
  4081. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4082. get: function () {
  4083. return Engine._DELAYLOADSTATE_NOTLOADED;
  4084. },
  4085. enumerable: true,
  4086. configurable: true
  4087. });
  4088. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4089. get: function () {
  4090. return Engine._TEXTUREFORMAT_ALPHA;
  4091. },
  4092. enumerable: true,
  4093. configurable: true
  4094. });
  4095. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4096. get: function () {
  4097. return Engine._TEXTUREFORMAT_LUMINANCE;
  4098. },
  4099. enumerable: true,
  4100. configurable: true
  4101. });
  4102. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4103. get: function () {
  4104. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4105. },
  4106. enumerable: true,
  4107. configurable: true
  4108. });
  4109. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4110. get: function () {
  4111. return Engine._TEXTUREFORMAT_RGB;
  4112. },
  4113. enumerable: true,
  4114. configurable: true
  4115. });
  4116. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4117. get: function () {
  4118. return Engine._TEXTUREFORMAT_RGBA;
  4119. },
  4120. enumerable: true,
  4121. configurable: true
  4122. });
  4123. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4124. get: function () {
  4125. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4126. },
  4127. enumerable: true,
  4128. configurable: true
  4129. });
  4130. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4131. get: function () {
  4132. return Engine._TEXTURETYPE_FLOAT;
  4133. },
  4134. enumerable: true,
  4135. configurable: true
  4136. });
  4137. Object.defineProperty(Engine, "Version", {
  4138. get: function () {
  4139. return "2.1.0 alpha";
  4140. },
  4141. enumerable: true,
  4142. configurable: true
  4143. });
  4144. Engine.prototype.getGlInfo = function () {
  4145. return {
  4146. vendor: this._glVendor,
  4147. renderer: this._glRenderer,
  4148. version: this._glVersion
  4149. };
  4150. };
  4151. Engine.prototype.getAspectRatio = function (camera) {
  4152. var viewport = camera.viewport;
  4153. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4154. };
  4155. Engine.prototype.getRenderWidth = function () {
  4156. if (this._currentRenderTarget) {
  4157. return this._currentRenderTarget._width;
  4158. }
  4159. return this._renderingCanvas.width;
  4160. };
  4161. Engine.prototype.getRenderHeight = function () {
  4162. if (this._currentRenderTarget) {
  4163. return this._currentRenderTarget._height;
  4164. }
  4165. return this._renderingCanvas.height;
  4166. };
  4167. Engine.prototype.getRenderingCanvas = function () {
  4168. return this._renderingCanvas;
  4169. };
  4170. Engine.prototype.getRenderingCanvasClientRect = function () {
  4171. return this._renderingCanvas.getBoundingClientRect();
  4172. };
  4173. Engine.prototype.setHardwareScalingLevel = function (level) {
  4174. this._hardwareScalingLevel = level;
  4175. this.resize();
  4176. };
  4177. Engine.prototype.getHardwareScalingLevel = function () {
  4178. return this._hardwareScalingLevel;
  4179. };
  4180. Engine.prototype.getLoadedTexturesCache = function () {
  4181. return this._loadedTexturesCache;
  4182. };
  4183. Engine.prototype.getCaps = function () {
  4184. return this._caps;
  4185. };
  4186. Object.defineProperty(Engine.prototype, "drawCalls", {
  4187. get: function () {
  4188. return this._drawCalls;
  4189. },
  4190. enumerable: true,
  4191. configurable: true
  4192. });
  4193. // Methods
  4194. Engine.prototype.resetDrawCalls = function () {
  4195. this._drawCalls = 0;
  4196. };
  4197. Engine.prototype.setDepthFunctionToGreater = function () {
  4198. this._depthCullingState.depthFunc = this._gl.GREATER;
  4199. };
  4200. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4201. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4202. };
  4203. Engine.prototype.setDepthFunctionToLess = function () {
  4204. this._depthCullingState.depthFunc = this._gl.LESS;
  4205. };
  4206. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4207. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4208. };
  4209. /**
  4210. * stop executing a render loop function and remove it from the execution array
  4211. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4212. */
  4213. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4214. if (!renderFunction) {
  4215. this._activeRenderLoops = [];
  4216. return;
  4217. }
  4218. var index = this._activeRenderLoops.indexOf(renderFunction);
  4219. if (index >= 0) {
  4220. this._activeRenderLoops.splice(index, 1);
  4221. }
  4222. };
  4223. Engine.prototype._renderLoop = function () {
  4224. var _this = this;
  4225. var shouldRender = true;
  4226. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4227. shouldRender = false;
  4228. }
  4229. if (shouldRender) {
  4230. // Start new frame
  4231. this.beginFrame();
  4232. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4233. var renderFunction = this._activeRenderLoops[index];
  4234. renderFunction();
  4235. }
  4236. // Present
  4237. this.endFrame();
  4238. }
  4239. if (this._activeRenderLoops.length > 0) {
  4240. // Register new frame
  4241. BABYLON.Tools.QueueNewFrame(function () {
  4242. _this._renderLoop();
  4243. });
  4244. }
  4245. else {
  4246. this._renderingQueueLaunched = false;
  4247. }
  4248. };
  4249. /**
  4250. * Register and execute a render loop. The engine can have more than one render function.
  4251. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4252. * @example
  4253. * engine.runRenderLoop(function () {
  4254. * scene.render()
  4255. * })
  4256. */
  4257. Engine.prototype.runRenderLoop = function (renderFunction) {
  4258. var _this = this;
  4259. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4260. return;
  4261. }
  4262. this._activeRenderLoops.push(renderFunction);
  4263. if (!this._renderingQueueLaunched) {
  4264. this._renderingQueueLaunched = true;
  4265. BABYLON.Tools.QueueNewFrame(function () {
  4266. _this._renderLoop();
  4267. });
  4268. }
  4269. };
  4270. /**
  4271. * Toggle full screen mode.
  4272. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4273. */
  4274. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4275. if (this.isFullscreen) {
  4276. BABYLON.Tools.ExitFullscreen();
  4277. }
  4278. else {
  4279. this._pointerLockRequested = requestPointerLock;
  4280. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4281. }
  4282. };
  4283. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4284. this.applyStates();
  4285. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4286. if (this._depthCullingState.depthMask) {
  4287. this._gl.clearDepth(1.0);
  4288. }
  4289. var mode = 0;
  4290. if (backBuffer)
  4291. mode |= this._gl.COLOR_BUFFER_BIT;
  4292. if (depthStencil && this._depthCullingState.depthMask)
  4293. mode |= this._gl.DEPTH_BUFFER_BIT;
  4294. this._gl.clear(mode);
  4295. };
  4296. /**
  4297. * Set the WebGL's viewport
  4298. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4299. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4300. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4301. */
  4302. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4303. var width = requiredWidth || this._renderingCanvas.width;
  4304. var height = requiredHeight || this._renderingCanvas.height;
  4305. var x = viewport.x || 0;
  4306. var y = viewport.y || 0;
  4307. this._cachedViewport = viewport;
  4308. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4309. };
  4310. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4311. this._cachedViewport = null;
  4312. this._gl.viewport(x, y, width, height);
  4313. };
  4314. Engine.prototype.beginFrame = function () {
  4315. this._measureFps();
  4316. };
  4317. Engine.prototype.endFrame = function () {
  4318. //this.flushFramebuffer();
  4319. };
  4320. /**
  4321. * resize the view according to the canvas' size.
  4322. * @example
  4323. * window.addEventListener("resize", function () {
  4324. * engine.resize();
  4325. * });
  4326. */
  4327. Engine.prototype.resize = function () {
  4328. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4329. };
  4330. /**
  4331. * force a specific size of the canvas
  4332. * @param {number} width - the new canvas' width
  4333. * @param {number} height - the new canvas' height
  4334. */
  4335. Engine.prototype.setSize = function (width, height) {
  4336. this._renderingCanvas.width = width;
  4337. this._renderingCanvas.height = height;
  4338. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4339. };
  4340. Engine.prototype.bindFramebuffer = function (texture) {
  4341. this._currentRenderTarget = texture;
  4342. var gl = this._gl;
  4343. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4344. this._gl.viewport(0, 0, texture._width, texture._height);
  4345. this.wipeCaches();
  4346. };
  4347. Engine.prototype.unBindFramebuffer = function (texture) {
  4348. this._currentRenderTarget = null;
  4349. if (texture.generateMipMaps) {
  4350. var gl = this._gl;
  4351. gl.bindTexture(gl.TEXTURE_2D, texture);
  4352. gl.generateMipmap(gl.TEXTURE_2D);
  4353. gl.bindTexture(gl.TEXTURE_2D, null);
  4354. }
  4355. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4356. };
  4357. Engine.prototype.flushFramebuffer = function () {
  4358. this._gl.flush();
  4359. };
  4360. Engine.prototype.restoreDefaultFramebuffer = function () {
  4361. this._currentRenderTarget = null;
  4362. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4363. this.setViewport(this._cachedViewport);
  4364. this.wipeCaches();
  4365. };
  4366. // VBOs
  4367. Engine.prototype._resetVertexBufferBinding = function () {
  4368. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4369. this._cachedVertexBuffers = null;
  4370. };
  4371. Engine.prototype.createVertexBuffer = function (vertices) {
  4372. var vbo = this._gl.createBuffer();
  4373. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4374. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4375. this._resetVertexBufferBinding();
  4376. vbo.references = 1;
  4377. return vbo;
  4378. };
  4379. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4380. var vbo = this._gl.createBuffer();
  4381. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4382. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4383. this._resetVertexBufferBinding();
  4384. vbo.references = 1;
  4385. return vbo;
  4386. };
  4387. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4388. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4389. if (offset === undefined) {
  4390. offset = 0;
  4391. }
  4392. if (vertices instanceof Float32Array) {
  4393. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4394. }
  4395. else {
  4396. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4397. }
  4398. this._resetVertexBufferBinding();
  4399. };
  4400. Engine.prototype._resetIndexBufferBinding = function () {
  4401. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4402. this._cachedIndexBuffer = null;
  4403. };
  4404. Engine.prototype.createIndexBuffer = function (indices) {
  4405. var vbo = this._gl.createBuffer();
  4406. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4407. // Check for 32 bits indices
  4408. var arrayBuffer;
  4409. var need32Bits = false;
  4410. if (this._caps.uintIndices) {
  4411. for (var index = 0; index < indices.length; index++) {
  4412. if (indices[index] > 65535) {
  4413. need32Bits = true;
  4414. break;
  4415. }
  4416. }
  4417. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4418. }
  4419. else {
  4420. arrayBuffer = new Uint16Array(indices);
  4421. }
  4422. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4423. this._resetIndexBufferBinding();
  4424. vbo.references = 1;
  4425. vbo.is32Bits = need32Bits;
  4426. return vbo;
  4427. };
  4428. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4429. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4430. this._cachedVertexBuffers = vertexBuffer;
  4431. this._cachedEffectForVertexBuffers = effect;
  4432. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4433. var offset = 0;
  4434. for (var index = 0; index < vertexDeclaration.length; index++) {
  4435. var order = effect.getAttributeLocation(index);
  4436. if (order >= 0) {
  4437. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4438. }
  4439. offset += vertexDeclaration[index] * 4;
  4440. }
  4441. }
  4442. if (this._cachedIndexBuffer !== indexBuffer) {
  4443. this._cachedIndexBuffer = indexBuffer;
  4444. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4445. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4446. }
  4447. };
  4448. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4449. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4450. this._cachedVertexBuffers = vertexBuffers;
  4451. this._cachedEffectForVertexBuffers = effect;
  4452. var attributes = effect.getAttributesNames();
  4453. for (var index = 0; index < attributes.length; index++) {
  4454. var order = effect.getAttributeLocation(index);
  4455. if (order >= 0) {
  4456. var vertexBuffer = vertexBuffers[attributes[index]];
  4457. if (!vertexBuffer) {
  4458. continue;
  4459. }
  4460. var stride = vertexBuffer.getStrideSize();
  4461. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4462. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4463. }
  4464. }
  4465. }
  4466. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4467. this._cachedIndexBuffer = indexBuffer;
  4468. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4469. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4470. }
  4471. };
  4472. Engine.prototype._releaseBuffer = function (buffer) {
  4473. buffer.references--;
  4474. if (buffer.references === 0) {
  4475. this._gl.deleteBuffer(buffer);
  4476. return true;
  4477. }
  4478. return false;
  4479. };
  4480. Engine.prototype.createInstancesBuffer = function (capacity) {
  4481. var buffer = this._gl.createBuffer();
  4482. buffer.capacity = capacity;
  4483. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4484. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4485. return buffer;
  4486. };
  4487. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4488. this._gl.deleteBuffer(buffer);
  4489. };
  4490. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4491. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4492. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4493. for (var index = 0; index < 4; index++) {
  4494. var offsetLocation = offsetLocations[index];
  4495. this._gl.enableVertexAttribArray(offsetLocation);
  4496. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4497. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4498. }
  4499. };
  4500. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4501. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4502. for (var index = 0; index < 4; index++) {
  4503. var offsetLocation = offsetLocations[index];
  4504. this._gl.disableVertexAttribArray(offsetLocation);
  4505. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4506. }
  4507. };
  4508. Engine.prototype.applyStates = function () {
  4509. this._depthCullingState.apply(this._gl);
  4510. this._alphaState.apply(this._gl);
  4511. };
  4512. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4513. // Apply states
  4514. this.applyStates();
  4515. this._drawCalls++;
  4516. // Render
  4517. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4518. if (instancesCount) {
  4519. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4520. return;
  4521. }
  4522. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4523. };
  4524. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4525. // Apply states
  4526. this.applyStates();
  4527. this._drawCalls++;
  4528. if (instancesCount) {
  4529. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4530. return;
  4531. }
  4532. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4533. };
  4534. // Shaders
  4535. Engine.prototype._releaseEffect = function (effect) {
  4536. if (this._compiledEffects[effect._key]) {
  4537. delete this._compiledEffects[effect._key];
  4538. if (effect.getProgram()) {
  4539. this._gl.deleteProgram(effect.getProgram());
  4540. }
  4541. }
  4542. };
  4543. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4544. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4545. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4546. var name = vertex + "+" + fragment + "@" + defines;
  4547. if (this._compiledEffects[name]) {
  4548. return this._compiledEffects[name];
  4549. }
  4550. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4551. effect._key = name;
  4552. this._compiledEffects[name] = effect;
  4553. return effect;
  4554. };
  4555. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4556. if (uniformsNames === void 0) { uniformsNames = []; }
  4557. if (samplers === void 0) { samplers = []; }
  4558. if (defines === void 0) { defines = ""; }
  4559. return this.createEffect({
  4560. vertex: "particles",
  4561. fragmentElement: fragmentName
  4562. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4563. };
  4564. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4565. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4566. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4567. var shaderProgram = this._gl.createProgram();
  4568. this._gl.attachShader(shaderProgram, vertexShader);
  4569. this._gl.attachShader(shaderProgram, fragmentShader);
  4570. this._gl.linkProgram(shaderProgram);
  4571. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4572. if (!linked) {
  4573. var error = this._gl.getProgramInfoLog(shaderProgram);
  4574. if (error) {
  4575. throw new Error(error);
  4576. }
  4577. }
  4578. this._gl.deleteShader(vertexShader);
  4579. this._gl.deleteShader(fragmentShader);
  4580. return shaderProgram;
  4581. };
  4582. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4583. var results = [];
  4584. for (var index = 0; index < uniformsNames.length; index++) {
  4585. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4586. }
  4587. return results;
  4588. };
  4589. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4590. var results = [];
  4591. for (var index = 0; index < attributesNames.length; index++) {
  4592. try {
  4593. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4594. }
  4595. catch (e) {
  4596. results.push(-1);
  4597. }
  4598. }
  4599. return results;
  4600. };
  4601. Engine.prototype.enableEffect = function (effect) {
  4602. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4603. if (effect && effect.onBind) {
  4604. effect.onBind(effect);
  4605. }
  4606. return;
  4607. }
  4608. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4609. // Use program
  4610. this._gl.useProgram(effect.getProgram());
  4611. for (var i in this._vertexAttribArrays) {
  4612. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4613. continue;
  4614. }
  4615. this._vertexAttribArrays[i] = false;
  4616. this._gl.disableVertexAttribArray(i);
  4617. }
  4618. var attributesCount = effect.getAttributesCount();
  4619. for (var index = 0; index < attributesCount; index++) {
  4620. // Attributes
  4621. var order = effect.getAttributeLocation(index);
  4622. if (order >= 0) {
  4623. this._vertexAttribArrays[order] = true;
  4624. this._gl.enableVertexAttribArray(order);
  4625. }
  4626. }
  4627. this._currentEffect = effect;
  4628. if (effect.onBind) {
  4629. effect.onBind(effect);
  4630. }
  4631. };
  4632. Engine.prototype.setArray = function (uniform, array) {
  4633. if (!uniform)
  4634. return;
  4635. this._gl.uniform1fv(uniform, array);
  4636. };
  4637. Engine.prototype.setArray2 = function (uniform, array) {
  4638. if (!uniform || array.length % 2 !== 0)
  4639. return;
  4640. this._gl.uniform2fv(uniform, array);
  4641. };
  4642. Engine.prototype.setArray3 = function (uniform, array) {
  4643. if (!uniform || array.length % 3 !== 0)
  4644. return;
  4645. this._gl.uniform3fv(uniform, array);
  4646. };
  4647. Engine.prototype.setArray4 = function (uniform, array) {
  4648. if (!uniform || array.length % 4 !== 0)
  4649. return;
  4650. this._gl.uniform4fv(uniform, array);
  4651. };
  4652. Engine.prototype.setMatrices = function (uniform, matrices) {
  4653. if (!uniform)
  4654. return;
  4655. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4656. };
  4657. Engine.prototype.setMatrix = function (uniform, matrix) {
  4658. if (!uniform)
  4659. return;
  4660. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4661. };
  4662. Engine.prototype.setFloat = function (uniform, value) {
  4663. if (!uniform)
  4664. return;
  4665. this._gl.uniform1f(uniform, value);
  4666. };
  4667. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4668. if (!uniform)
  4669. return;
  4670. this._gl.uniform2f(uniform, x, y);
  4671. };
  4672. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4673. if (!uniform)
  4674. return;
  4675. this._gl.uniform3f(uniform, x, y, z);
  4676. };
  4677. Engine.prototype.setBool = function (uniform, bool) {
  4678. if (!uniform)
  4679. return;
  4680. this._gl.uniform1i(uniform, bool);
  4681. };
  4682. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4683. if (!uniform)
  4684. return;
  4685. this._gl.uniform4f(uniform, x, y, z, w);
  4686. };
  4687. Engine.prototype.setColor3 = function (uniform, color3) {
  4688. if (!uniform)
  4689. return;
  4690. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4691. };
  4692. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4693. if (!uniform)
  4694. return;
  4695. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4696. };
  4697. // States
  4698. Engine.prototype.setState = function (culling, force) {
  4699. // Culling
  4700. if (this._depthCullingState.cull !== culling || force) {
  4701. if (culling) {
  4702. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4703. this._depthCullingState.cull = true;
  4704. }
  4705. else {
  4706. this._depthCullingState.cull = false;
  4707. }
  4708. }
  4709. };
  4710. Engine.prototype.setDepthBuffer = function (enable) {
  4711. this._depthCullingState.depthTest = enable;
  4712. };
  4713. Engine.prototype.getDepthWrite = function () {
  4714. return this._depthCullingState.depthMask;
  4715. };
  4716. Engine.prototype.setDepthWrite = function (enable) {
  4717. this._depthCullingState.depthMask = enable;
  4718. };
  4719. Engine.prototype.setColorWrite = function (enable) {
  4720. this._gl.colorMask(enable, enable, enable, enable);
  4721. };
  4722. Engine.prototype.setAlphaMode = function (mode) {
  4723. switch (mode) {
  4724. case Engine.ALPHA_DISABLE:
  4725. this.setDepthWrite(true);
  4726. this._alphaState.alphaBlend = false;
  4727. break;
  4728. case Engine.ALPHA_COMBINE:
  4729. this.setDepthWrite(false);
  4730. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4731. this._alphaState.alphaBlend = true;
  4732. break;
  4733. case Engine.ALPHA_ADD:
  4734. this.setDepthWrite(false);
  4735. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4736. this._alphaState.alphaBlend = true;
  4737. break;
  4738. }
  4739. this._alphaMode = mode;
  4740. };
  4741. Engine.prototype.getAlphaMode = function () {
  4742. return this._alphaMode;
  4743. };
  4744. Engine.prototype.setAlphaTesting = function (enable) {
  4745. this._alphaTest = enable;
  4746. };
  4747. Engine.prototype.getAlphaTesting = function () {
  4748. return this._alphaTest;
  4749. };
  4750. // Textures
  4751. Engine.prototype.wipeCaches = function () {
  4752. this._activeTexturesCache = [];
  4753. this._currentEffect = null;
  4754. this._depthCullingState.reset();
  4755. this._alphaState.reset();
  4756. this._cachedVertexBuffers = null;
  4757. this._cachedIndexBuffer = null;
  4758. this._cachedEffectForVertexBuffers = null;
  4759. };
  4760. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4761. var gl = this._gl;
  4762. gl.bindTexture(gl.TEXTURE_2D, texture);
  4763. var magFilter = gl.NEAREST;
  4764. var minFilter = gl.NEAREST;
  4765. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4766. magFilter = gl.LINEAR;
  4767. minFilter = gl.LINEAR;
  4768. }
  4769. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4770. magFilter = gl.LINEAR;
  4771. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4772. }
  4773. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4774. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4775. gl.bindTexture(gl.TEXTURE_2D, null);
  4776. texture.samplingMode = samplingMode;
  4777. };
  4778. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4779. var _this = this;
  4780. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4781. if (onLoad === void 0) { onLoad = null; }
  4782. if (onError === void 0) { onError = null; }
  4783. if (buffer === void 0) { buffer = null; }
  4784. var texture = this._gl.createTexture();
  4785. var extension;
  4786. var fromData = false;
  4787. if (url.substr(0, 5) === "data:") {
  4788. fromData = true;
  4789. }
  4790. if (!fromData)
  4791. extension = url.substr(url.length - 4, 4).toLowerCase();
  4792. else {
  4793. var oldUrl = url;
  4794. fromData = oldUrl.split(':');
  4795. url = oldUrl;
  4796. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4797. }
  4798. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4799. var isTGA = (extension === ".tga");
  4800. scene._addPendingData(texture);
  4801. texture.url = url;
  4802. texture.noMipmap = noMipmap;
  4803. texture.references = 1;
  4804. this._loadedTexturesCache.push(texture);
  4805. var onerror = function () {
  4806. scene._removePendingData(texture);
  4807. if (onError) {
  4808. onError();
  4809. }
  4810. };
  4811. if (isTGA) {
  4812. var callback = function (arrayBuffer) {
  4813. var data = new Uint8Array(arrayBuffer);
  4814. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4815. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4816. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4817. if (onLoad) {
  4818. onLoad();
  4819. }
  4820. }, samplingMode);
  4821. };
  4822. if (!(fromData instanceof Array))
  4823. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4824. callback(arrayBuffer);
  4825. }, onerror, scene.database, true);
  4826. else
  4827. callback(buffer);
  4828. }
  4829. else if (isDDS) {
  4830. callback = function (data) {
  4831. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4832. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4833. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4834. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4835. if (onLoad) {
  4836. onLoad();
  4837. }
  4838. }, samplingMode);
  4839. };
  4840. if (!(fromData instanceof Array))
  4841. BABYLON.Tools.LoadFile(url, function (data) {
  4842. callback(data);
  4843. }, onerror, scene.database, true);
  4844. else
  4845. callback(buffer);
  4846. }
  4847. else {
  4848. var onload = function (img) {
  4849. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4850. var isPot = (img.width === potWidth && img.height === potHeight);
  4851. if (!isPot) {
  4852. _this._workingCanvas.width = potWidth;
  4853. _this._workingCanvas.height = potHeight;
  4854. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4855. _this._workingContext.imageSmoothingEnabled = false;
  4856. _this._workingContext.mozImageSmoothingEnabled = false;
  4857. _this._workingContext.oImageSmoothingEnabled = false;
  4858. _this._workingContext.webkitImageSmoothingEnabled = false;
  4859. _this._workingContext.msImageSmoothingEnabled = false;
  4860. }
  4861. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4862. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4863. _this._workingContext.imageSmoothingEnabled = true;
  4864. _this._workingContext.mozImageSmoothingEnabled = true;
  4865. _this._workingContext.oImageSmoothingEnabled = true;
  4866. _this._workingContext.webkitImageSmoothingEnabled = true;
  4867. _this._workingContext.msImageSmoothingEnabled = true;
  4868. }
  4869. }
  4870. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4871. if (onLoad) {
  4872. onLoad();
  4873. }
  4874. }, samplingMode);
  4875. };
  4876. if (!(fromData instanceof Array))
  4877. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4878. else
  4879. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4880. }
  4881. return texture;
  4882. };
  4883. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4884. var texture = this._gl.createTexture();
  4885. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4886. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4887. // Format
  4888. var internalFormat = this._gl.RGBA;
  4889. switch (format) {
  4890. case Engine.TEXTUREFORMAT_ALPHA:
  4891. internalFormat = this._gl.ALPHA;
  4892. break;
  4893. case Engine.TEXTUREFORMAT_LUMINANCE:
  4894. internalFormat = this._gl.LUMINANCE;
  4895. break;
  4896. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4897. internalFormat = this._gl.LUMINANCE_ALPHA;
  4898. break;
  4899. case Engine.TEXTUREFORMAT_RGB:
  4900. internalFormat = this._gl.RGB;
  4901. break;
  4902. case Engine.TEXTUREFORMAT_RGBA:
  4903. internalFormat = this._gl.RGBA;
  4904. break;
  4905. }
  4906. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4907. if (generateMipMaps) {
  4908. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4909. }
  4910. // Filters
  4911. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4914. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4915. this._activeTexturesCache = [];
  4916. texture._baseWidth = width;
  4917. texture._baseHeight = height;
  4918. texture._width = width;
  4919. texture._height = height;
  4920. texture.isReady = true;
  4921. texture.references = 1;
  4922. texture.samplingMode = samplingMode;
  4923. this._loadedTexturesCache.push(texture);
  4924. return texture;
  4925. };
  4926. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4927. var texture = this._gl.createTexture();
  4928. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4929. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4930. this._activeTexturesCache = [];
  4931. texture._baseWidth = width;
  4932. texture._baseHeight = height;
  4933. texture._width = width;
  4934. texture._height = height;
  4935. texture.isReady = false;
  4936. texture.generateMipMaps = generateMipMaps;
  4937. texture.references = 1;
  4938. texture.samplingMode = samplingMode;
  4939. this.updateTextureSamplingMode(samplingMode, texture);
  4940. this._loadedTexturesCache.push(texture);
  4941. return texture;
  4942. };
  4943. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  4944. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  4945. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4946. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4947. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4948. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4949. };
  4950. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4951. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4952. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4953. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4954. if (texture.generateMipMaps) {
  4955. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4956. }
  4957. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4958. this._activeTexturesCache = [];
  4959. texture.isReady = true;
  4960. };
  4961. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4962. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4963. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4964. // Scale the video if it is a NPOT using the current working canvas
  4965. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4966. if (!texture._workingCanvas) {
  4967. texture._workingCanvas = document.createElement("canvas");
  4968. texture._workingContext = texture._workingCanvas.getContext("2d");
  4969. texture._workingCanvas.width = texture._width;
  4970. texture._workingCanvas.height = texture._height;
  4971. }
  4972. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4973. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4974. }
  4975. else {
  4976. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4977. }
  4978. if (texture.generateMipMaps) {
  4979. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4980. }
  4981. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4982. this._activeTexturesCache = [];
  4983. texture.isReady = true;
  4984. };
  4985. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4986. // old version had a "generateMipMaps" arg instead of options.
  4987. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4988. // in the same way, generateDepthBuffer is defaulted to true
  4989. var generateMipMaps = false;
  4990. var generateDepthBuffer = true;
  4991. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4992. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4993. if (options !== undefined) {
  4994. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4995. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4996. type = options.type === undefined ? type : options.type;
  4997. if (options.samplingMode !== undefined) {
  4998. samplingMode = options.samplingMode;
  4999. }
  5000. if (type === Engine.TEXTURETYPE_FLOAT) {
  5001. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5002. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5003. }
  5004. }
  5005. var gl = this._gl;
  5006. var texture = gl.createTexture();
  5007. gl.bindTexture(gl.TEXTURE_2D, texture);
  5008. var width = size.width || size;
  5009. var height = size.height || size;
  5010. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5011. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5012. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5013. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5014. }
  5015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5017. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5018. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5019. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5020. var depthBuffer;
  5021. // Create the depth buffer
  5022. if (generateDepthBuffer) {
  5023. depthBuffer = gl.createRenderbuffer();
  5024. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5025. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5026. }
  5027. // Create the framebuffer
  5028. var framebuffer = gl.createFramebuffer();
  5029. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5031. if (generateDepthBuffer) {
  5032. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5033. }
  5034. // Unbind
  5035. gl.bindTexture(gl.TEXTURE_2D, null);
  5036. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5037. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5038. texture._framebuffer = framebuffer;
  5039. if (generateDepthBuffer) {
  5040. texture._depthBuffer = depthBuffer;
  5041. }
  5042. texture._width = width;
  5043. texture._height = height;
  5044. texture.isReady = true;
  5045. texture.generateMipMaps = generateMipMaps;
  5046. texture.references = 1;
  5047. texture.samplingMode = samplingMode;
  5048. this._activeTexturesCache = [];
  5049. this._loadedTexturesCache.push(texture);
  5050. return texture;
  5051. };
  5052. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5053. var _this = this;
  5054. var gl = this._gl;
  5055. var texture = gl.createTexture();
  5056. texture.isCube = true;
  5057. texture.url = rootUrl;
  5058. texture.references = 1;
  5059. this._loadedTexturesCache.push(texture);
  5060. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5061. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5062. if (isDDS) {
  5063. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5064. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5065. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5066. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5067. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5068. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5069. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5070. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5071. }
  5072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5073. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5076. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5077. _this._activeTexturesCache = [];
  5078. texture._width = info.width;
  5079. texture._height = info.height;
  5080. texture.isReady = true;
  5081. }, null, null, true);
  5082. }
  5083. else {
  5084. cascadeLoad(rootUrl, scene, function (imgs) {
  5085. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5086. var height = width;
  5087. _this._workingCanvas.width = width;
  5088. _this._workingCanvas.height = height;
  5089. var faces = [
  5090. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5091. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5092. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5093. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5094. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5095. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5096. ];
  5097. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5098. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5099. for (var index = 0; index < faces.length; index++) {
  5100. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5101. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5102. }
  5103. if (!noMipmap) {
  5104. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5105. }
  5106. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5107. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5108. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5109. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5110. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5111. _this._activeTexturesCache = [];
  5112. texture._width = width;
  5113. texture._height = height;
  5114. texture.isReady = true;
  5115. }, extensions);
  5116. }
  5117. return texture;
  5118. };
  5119. Engine.prototype._releaseTexture = function (texture) {
  5120. var gl = this._gl;
  5121. if (texture._framebuffer) {
  5122. gl.deleteFramebuffer(texture._framebuffer);
  5123. }
  5124. if (texture._depthBuffer) {
  5125. gl.deleteRenderbuffer(texture._depthBuffer);
  5126. }
  5127. gl.deleteTexture(texture);
  5128. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5129. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5130. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5131. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5132. this._activeTexturesCache[channel] = null;
  5133. }
  5134. var index = this._loadedTexturesCache.indexOf(texture);
  5135. if (index !== -1) {
  5136. this._loadedTexturesCache.splice(index, 1);
  5137. }
  5138. };
  5139. Engine.prototype.bindSamplers = function (effect) {
  5140. this._gl.useProgram(effect.getProgram());
  5141. var samplers = effect.getSamplers();
  5142. for (var index = 0; index < samplers.length; index++) {
  5143. var uniform = effect.getUniform(samplers[index]);
  5144. this._gl.uniform1i(uniform, index);
  5145. }
  5146. this._currentEffect = null;
  5147. };
  5148. Engine.prototype._bindTexture = function (channel, texture) {
  5149. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5150. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5151. this._activeTexturesCache[channel] = null;
  5152. };
  5153. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5154. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5155. };
  5156. Engine.prototype.setTexture = function (channel, texture) {
  5157. if (channel < 0) {
  5158. return;
  5159. }
  5160. // Not ready?
  5161. if (!texture || !texture.isReady()) {
  5162. if (this._activeTexturesCache[channel] != null) {
  5163. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5164. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5165. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5166. this._activeTexturesCache[channel] = null;
  5167. }
  5168. return;
  5169. }
  5170. // Video
  5171. if (texture instanceof BABYLON.VideoTexture) {
  5172. if (texture.update()) {
  5173. this._activeTexturesCache[channel] = null;
  5174. }
  5175. }
  5176. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5177. texture.delayLoad();
  5178. return;
  5179. }
  5180. if (this._activeTexturesCache[channel] === texture) {
  5181. return;
  5182. }
  5183. this._activeTexturesCache[channel] = texture;
  5184. var internalTexture = texture.getInternalTexture();
  5185. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5186. if (internalTexture.isCube) {
  5187. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5188. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5189. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5190. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5191. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5192. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5193. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5194. }
  5195. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5196. }
  5197. else {
  5198. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5199. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5200. internalTexture._cachedWrapU = texture.wrapU;
  5201. switch (texture.wrapU) {
  5202. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5203. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5204. break;
  5205. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5206. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5207. break;
  5208. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5210. break;
  5211. }
  5212. }
  5213. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5214. internalTexture._cachedWrapV = texture.wrapV;
  5215. switch (texture.wrapV) {
  5216. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5217. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5218. break;
  5219. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5220. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5221. break;
  5222. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5223. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5224. break;
  5225. }
  5226. }
  5227. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5228. }
  5229. };
  5230. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5231. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5232. var value = texture.anisotropicFilteringLevel;
  5233. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5234. value = 1;
  5235. }
  5236. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5237. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5238. texture._cachedAnisotropicFilteringLevel = value;
  5239. }
  5240. };
  5241. Engine.prototype.readPixels = function (x, y, width, height) {
  5242. var data = new Uint8Array(height * width * 4);
  5243. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5244. return data;
  5245. };
  5246. // Dispose
  5247. Engine.prototype.dispose = function () {
  5248. this.hideLoadingUI();
  5249. this.stopRenderLoop();
  5250. while (this.scenes.length) {
  5251. this.scenes[0].dispose();
  5252. }
  5253. // Release audio engine
  5254. Engine.audioEngine.dispose();
  5255. for (var name in this._compiledEffects) {
  5256. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5257. }
  5258. for (var i in this._vertexAttribArrays) {
  5259. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5260. continue;
  5261. }
  5262. this._gl.disableVertexAttribArray(i);
  5263. }
  5264. // Events
  5265. window.removeEventListener("blur", this._onBlur);
  5266. window.removeEventListener("focus", this._onFocus);
  5267. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5268. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5269. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5270. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5271. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5272. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5273. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5274. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5275. };
  5276. // Loading screen
  5277. Engine.prototype.displayLoadingUI = function () {
  5278. var _this = this;
  5279. this._loadingDiv = document.createElement("div");
  5280. this._loadingDiv.style.opacity = "0";
  5281. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5282. // Loading text
  5283. this._loadingTextDiv = document.createElement("div");
  5284. this._loadingTextDiv.style.position = "absolute";
  5285. this._loadingTextDiv.style.left = "0";
  5286. this._loadingTextDiv.style.top = "50%";
  5287. this._loadingTextDiv.style.marginTop = "80px";
  5288. this._loadingTextDiv.style.width = "100%";
  5289. this._loadingTextDiv.style.height = "20px";
  5290. this._loadingTextDiv.style.fontFamily = "Arial";
  5291. this._loadingTextDiv.style.fontSize = "14px";
  5292. this._loadingTextDiv.style.color = "white";
  5293. this._loadingTextDiv.style.textAlign = "center";
  5294. this._loadingTextDiv.innerHTML = "Loading";
  5295. this._loadingDiv.appendChild(this._loadingTextDiv);
  5296. // Loading img
  5297. var imgBack = new Image();
  5298. 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==";
  5299. imgBack.style.position = "absolute";
  5300. imgBack.style.left = "50%";
  5301. imgBack.style.top = "50%";
  5302. imgBack.style.marginLeft = "-50px";
  5303. imgBack.style.marginTop = "-50px";
  5304. imgBack.style.transition = "transform 1.0s ease";
  5305. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5306. var deg = 360;
  5307. var onTransitionEnd = function () {
  5308. deg += 360;
  5309. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5310. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5311. };
  5312. imgBack.addEventListener("transitionend", onTransitionEnd);
  5313. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5314. this._loadingDiv.appendChild(imgBack);
  5315. // front image
  5316. var imgFront = new Image();
  5317. 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=";
  5318. imgFront.style.position = "absolute";
  5319. imgFront.style.left = "50%";
  5320. imgFront.style.top = "50%";
  5321. imgFront.style.marginLeft = "-50px";
  5322. imgFront.style.marginTop = "-50px";
  5323. this._loadingDiv.appendChild(imgFront);
  5324. // Resize
  5325. this._resizeLoadingUI = function () {
  5326. var canvasRect = _this.getRenderingCanvasClientRect();
  5327. _this._loadingDiv.style.position = "absolute";
  5328. _this._loadingDiv.style.left = canvasRect.left + "px";
  5329. _this._loadingDiv.style.top = canvasRect.top + "px";
  5330. _this._loadingDiv.style.width = canvasRect.width + "px";
  5331. _this._loadingDiv.style.height = canvasRect.height + "px";
  5332. };
  5333. this._resizeLoadingUI();
  5334. window.addEventListener("resize", this._resizeLoadingUI);
  5335. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5336. document.body.appendChild(this._loadingDiv);
  5337. setTimeout(function () {
  5338. _this._loadingDiv.style.opacity = "1";
  5339. imgBack.style.transform = "rotateZ(360deg)";
  5340. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5341. }, 0);
  5342. };
  5343. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5344. set: function (text) {
  5345. if (!this._loadingDiv) {
  5346. return;
  5347. }
  5348. this._loadingTextDiv.innerHTML = text;
  5349. },
  5350. enumerable: true,
  5351. configurable: true
  5352. });
  5353. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5354. get: function () {
  5355. return this._loadingDivBackgroundColor;
  5356. },
  5357. set: function (color) {
  5358. this._loadingDivBackgroundColor = color;
  5359. if (!this._loadingDiv) {
  5360. return;
  5361. }
  5362. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5363. },
  5364. enumerable: true,
  5365. configurable: true
  5366. });
  5367. Engine.prototype.hideLoadingUI = function () {
  5368. var _this = this;
  5369. if (!this._loadingDiv) {
  5370. return;
  5371. }
  5372. var onTransitionEnd = function () {
  5373. if (!_this._loadingDiv) {
  5374. return;
  5375. }
  5376. document.body.removeChild(_this._loadingDiv);
  5377. window.removeEventListener("resize", _this._resizeLoadingUI);
  5378. _this._loadingDiv = null;
  5379. };
  5380. this._loadingDiv.style.opacity = "0";
  5381. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5382. };
  5383. // FPS
  5384. Engine.prototype.getFps = function () {
  5385. return this.fps;
  5386. };
  5387. Engine.prototype.getDeltaTime = function () {
  5388. return this.deltaTime;
  5389. };
  5390. Engine.prototype._measureFps = function () {
  5391. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5392. var length = this.previousFramesDuration.length;
  5393. if (length >= 2) {
  5394. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5395. }
  5396. if (length >= this.fpsRange) {
  5397. if (length > this.fpsRange) {
  5398. this.previousFramesDuration.splice(0, 1);
  5399. length = this.previousFramesDuration.length;
  5400. }
  5401. var sum = 0;
  5402. for (var id = 0; id < length - 1; id++) {
  5403. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5404. }
  5405. this.fps = 1000.0 / (sum / (length - 1));
  5406. }
  5407. };
  5408. // Statics
  5409. Engine.isSupported = function () {
  5410. try {
  5411. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5412. if (navigator.isCocoonJS) {
  5413. return true;
  5414. }
  5415. var tempcanvas = document.createElement("canvas");
  5416. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5417. return gl != null && !!window.WebGLRenderingContext;
  5418. }
  5419. catch (e) {
  5420. return false;
  5421. }
  5422. };
  5423. // Const statics
  5424. Engine._ALPHA_DISABLE = 0;
  5425. Engine._ALPHA_ADD = 1;
  5426. Engine._ALPHA_COMBINE = 2;
  5427. Engine._DELAYLOADSTATE_NONE = 0;
  5428. Engine._DELAYLOADSTATE_LOADED = 1;
  5429. Engine._DELAYLOADSTATE_LOADING = 2;
  5430. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5431. Engine._TEXTUREFORMAT_ALPHA = 0;
  5432. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5433. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5434. Engine._TEXTUREFORMAT_RGB = 4;
  5435. Engine._TEXTUREFORMAT_RGBA = 4;
  5436. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5437. Engine._TEXTURETYPE_FLOAT = 1;
  5438. // Updatable statics so stick with vars here
  5439. Engine.Epsilon = 0.001;
  5440. Engine.CollisionsEpsilon = 0.001;
  5441. Engine.ShadersRepository = "Babylon/Shaders/";
  5442. return Engine;
  5443. })();
  5444. BABYLON.Engine = Engine;
  5445. })(BABYLON || (BABYLON = {}));
  5446. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5447. (function (BABYLON) {
  5448. /**
  5449. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5450. */
  5451. var Node = (function () {
  5452. /**
  5453. * @constructor
  5454. * @param {string} name - the name and id to be given to this node
  5455. * @param {BABYLON.Scene} the scene this node will be added to
  5456. */
  5457. function Node(name, scene) {
  5458. this.state = "";
  5459. this.animations = new Array();
  5460. this._childrenFlag = -1;
  5461. this._isEnabled = true;
  5462. this._isReady = true;
  5463. this._currentRenderId = -1;
  5464. this._parentRenderId = -1;
  5465. this.name = name;
  5466. this.id = name;
  5467. this._scene = scene;
  5468. this._initCache();
  5469. }
  5470. Node.prototype.getScene = function () {
  5471. return this._scene;
  5472. };
  5473. Node.prototype.getEngine = function () {
  5474. return this._scene.getEngine();
  5475. };
  5476. // override it in derived class
  5477. Node.prototype.getWorldMatrix = function () {
  5478. return BABYLON.Matrix.Identity();
  5479. };
  5480. // override it in derived class if you add new variables to the cache
  5481. // and call the parent class method
  5482. Node.prototype._initCache = function () {
  5483. this._cache = {};
  5484. this._cache.parent = undefined;
  5485. };
  5486. Node.prototype.updateCache = function (force) {
  5487. if (!force && this.isSynchronized())
  5488. return;
  5489. this._cache.parent = this.parent;
  5490. this._updateCache();
  5491. };
  5492. // override it in derived class if you add new variables to the cache
  5493. // and call the parent class method if !ignoreParentClass
  5494. Node.prototype._updateCache = function (ignoreParentClass) {
  5495. };
  5496. // override it in derived class if you add new variables to the cache
  5497. Node.prototype._isSynchronized = function () {
  5498. return true;
  5499. };
  5500. Node.prototype.isSynchronizedWithParent = function () {
  5501. if (!this.parent) {
  5502. return true;
  5503. }
  5504. if (this._parentRenderId !== this.parent._currentRenderId) {
  5505. return false;
  5506. }
  5507. this._parentRenderId = this.parent._currentRenderId;
  5508. return this.parent._currentRenderId <= this._currentRenderId && this.parent.isSynchronized();
  5509. };
  5510. Node.prototype.isSynchronized = function (updateCache) {
  5511. var check = this.hasNewParent();
  5512. check = check || !this.isSynchronizedWithParent();
  5513. check = check || !this._isSynchronized();
  5514. if (updateCache)
  5515. this.updateCache(true);
  5516. return !check;
  5517. };
  5518. Node.prototype.hasNewParent = function (update) {
  5519. if (this._cache.parent === this.parent)
  5520. return false;
  5521. if (update)
  5522. this._cache.parent = this.parent;
  5523. return true;
  5524. };
  5525. /**
  5526. * Is this node ready to be used/rendered
  5527. * @return {boolean} is it ready
  5528. */
  5529. Node.prototype.isReady = function () {
  5530. return this._isReady;
  5531. };
  5532. /**
  5533. * Is this node enabled.
  5534. * If the node has a parent and is enabled, the parent will be inspected as well.
  5535. * @return {boolean} whether this node (and its parent) is enabled.
  5536. * @see setEnabled
  5537. */
  5538. Node.prototype.isEnabled = function () {
  5539. if (!this._isEnabled) {
  5540. return false;
  5541. }
  5542. if (this.parent) {
  5543. return this.parent.isEnabled();
  5544. }
  5545. return true;
  5546. };
  5547. /**
  5548. * Set the enabled state of this node.
  5549. * @param {boolean} value - the new enabled state
  5550. * @see isEnabled
  5551. */
  5552. Node.prototype.setEnabled = function (value) {
  5553. this._isEnabled = value;
  5554. };
  5555. /**
  5556. * Is this node a descendant of the given node.
  5557. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5558. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5559. * @see parent
  5560. */
  5561. Node.prototype.isDescendantOf = function (ancestor) {
  5562. if (this.parent) {
  5563. if (this.parent === ancestor) {
  5564. return true;
  5565. }
  5566. return this.parent.isDescendantOf(ancestor);
  5567. }
  5568. return false;
  5569. };
  5570. Node.prototype._getDescendants = function (list, results) {
  5571. for (var index = 0; index < list.length; index++) {
  5572. var item = list[index];
  5573. if (item.isDescendantOf(this)) {
  5574. results.push(item);
  5575. }
  5576. }
  5577. };
  5578. /**
  5579. * Will return all nodes that have this node as parent.
  5580. * @return {BABYLON.Node[]} all children nodes of all types.
  5581. */
  5582. Node.prototype.getDescendants = function () {
  5583. var results = [];
  5584. this._getDescendants(this._scene.meshes, results);
  5585. this._getDescendants(this._scene.lights, results);
  5586. this._getDescendants(this._scene.cameras, results);
  5587. return results;
  5588. };
  5589. Node.prototype._setReady = function (state) {
  5590. if (state == this._isReady) {
  5591. return;
  5592. }
  5593. if (!state) {
  5594. this._isReady = false;
  5595. return;
  5596. }
  5597. this._isReady = true;
  5598. if (this.onReady) {
  5599. this.onReady(this);
  5600. }
  5601. };
  5602. return Node;
  5603. })();
  5604. BABYLON.Node = Node;
  5605. })(BABYLON || (BABYLON = {}));
  5606. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5607. (function (BABYLON) {
  5608. var BoundingSphere = (function () {
  5609. function BoundingSphere(minimum, maximum) {
  5610. this.minimum = minimum;
  5611. this.maximum = maximum;
  5612. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5613. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5614. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5615. this.radius = distance * 0.5;
  5616. this.centerWorld = BABYLON.Vector3.Zero();
  5617. this._update(BABYLON.Matrix.Identity());
  5618. }
  5619. // Methods
  5620. BoundingSphere.prototype._update = function (world) {
  5621. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5622. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5623. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5624. };
  5625. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5626. for (var i = 0; i < 6; i++) {
  5627. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5628. return false;
  5629. }
  5630. return true;
  5631. };
  5632. BoundingSphere.prototype.intersectsPoint = function (point) {
  5633. var x = this.centerWorld.x - point.x;
  5634. var y = this.centerWorld.y - point.y;
  5635. var z = this.centerWorld.z - point.z;
  5636. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5637. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5638. return false;
  5639. return true;
  5640. };
  5641. // Statics
  5642. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5643. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5644. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5645. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5646. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5647. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5648. return false;
  5649. return true;
  5650. };
  5651. return BoundingSphere;
  5652. })();
  5653. BABYLON.BoundingSphere = BoundingSphere;
  5654. })(BABYLON || (BABYLON = {}));
  5655. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5656. (function (BABYLON) {
  5657. var BoundingBox = (function () {
  5658. function BoundingBox(minimum, maximum) {
  5659. this.minimum = minimum;
  5660. this.maximum = maximum;
  5661. this.vectors = new Array();
  5662. this.vectorsWorld = new Array();
  5663. // Bounding vectors
  5664. this.vectors.push(this.minimum.clone());
  5665. this.vectors.push(this.maximum.clone());
  5666. this.vectors.push(this.minimum.clone());
  5667. this.vectors[2].x = this.maximum.x;
  5668. this.vectors.push(this.minimum.clone());
  5669. this.vectors[3].y = this.maximum.y;
  5670. this.vectors.push(this.minimum.clone());
  5671. this.vectors[4].z = this.maximum.z;
  5672. this.vectors.push(this.maximum.clone());
  5673. this.vectors[5].z = this.minimum.z;
  5674. this.vectors.push(this.maximum.clone());
  5675. this.vectors[6].x = this.minimum.x;
  5676. this.vectors.push(this.maximum.clone());
  5677. this.vectors[7].y = this.minimum.y;
  5678. // OBB
  5679. this.center = this.maximum.add(this.minimum).scale(0.5);
  5680. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5681. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5682. for (var index = 0; index < this.vectors.length; index++) {
  5683. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5684. }
  5685. this.minimumWorld = BABYLON.Vector3.Zero();
  5686. this.maximumWorld = BABYLON.Vector3.Zero();
  5687. this._update(BABYLON.Matrix.Identity());
  5688. }
  5689. // Methods
  5690. BoundingBox.prototype.getWorldMatrix = function () {
  5691. return this._worldMatrix;
  5692. };
  5693. BoundingBox.prototype._update = function (world) {
  5694. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5695. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5696. for (var index = 0; index < this.vectors.length; index++) {
  5697. var v = this.vectorsWorld[index];
  5698. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5699. if (v.x < this.minimumWorld.x)
  5700. this.minimumWorld.x = v.x;
  5701. if (v.y < this.minimumWorld.y)
  5702. this.minimumWorld.y = v.y;
  5703. if (v.z < this.minimumWorld.z)
  5704. this.minimumWorld.z = v.z;
  5705. if (v.x > this.maximumWorld.x)
  5706. this.maximumWorld.x = v.x;
  5707. if (v.y > this.maximumWorld.y)
  5708. this.maximumWorld.y = v.y;
  5709. if (v.z > this.maximumWorld.z)
  5710. this.maximumWorld.z = v.z;
  5711. }
  5712. // OBB
  5713. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5714. this.center.scaleInPlace(0.5);
  5715. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5716. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5717. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5718. this._worldMatrix = world;
  5719. };
  5720. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5721. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5722. };
  5723. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5724. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5725. };
  5726. BoundingBox.prototype.intersectsPoint = function (point) {
  5727. var delta = BABYLON.Engine.Epsilon;
  5728. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5729. return false;
  5730. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5731. return false;
  5732. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5733. return false;
  5734. return true;
  5735. };
  5736. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5737. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5738. };
  5739. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5740. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5741. return false;
  5742. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5743. return false;
  5744. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5745. return false;
  5746. return true;
  5747. };
  5748. // Statics
  5749. BoundingBox.Intersects = function (box0, box1) {
  5750. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5751. return false;
  5752. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5753. return false;
  5754. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5755. return false;
  5756. return true;
  5757. };
  5758. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5759. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5760. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5761. return (num <= (sphereRadius * sphereRadius));
  5762. };
  5763. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5764. for (var p = 0; p < 6; p++) {
  5765. for (var i = 0; i < 8; i++) {
  5766. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5767. return false;
  5768. }
  5769. }
  5770. }
  5771. return true;
  5772. };
  5773. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5774. for (var p = 0; p < 6; p++) {
  5775. var inCount = 8;
  5776. for (var i = 0; i < 8; i++) {
  5777. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5778. --inCount;
  5779. }
  5780. else {
  5781. break;
  5782. }
  5783. }
  5784. if (inCount === 0)
  5785. return false;
  5786. }
  5787. return true;
  5788. };
  5789. return BoundingBox;
  5790. })();
  5791. BABYLON.BoundingBox = BoundingBox;
  5792. })(BABYLON || (BABYLON = {}));
  5793. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5794. (function (BABYLON) {
  5795. var computeBoxExtents = function (axis, box) {
  5796. var p = BABYLON.Vector3.Dot(box.center, axis);
  5797. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5798. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5799. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5800. var r = r0 + r1 + r2;
  5801. return {
  5802. min: p - r,
  5803. max: p + r
  5804. };
  5805. };
  5806. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5807. var axisOverlap = function (axis, box0, box1) {
  5808. var result0 = computeBoxExtents(axis, box0);
  5809. var result1 = computeBoxExtents(axis, box1);
  5810. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5811. };
  5812. var BoundingInfo = (function () {
  5813. function BoundingInfo(minimum, maximum) {
  5814. this.minimum = minimum;
  5815. this.maximum = maximum;
  5816. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5817. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5818. }
  5819. // Methods
  5820. BoundingInfo.prototype._update = function (world) {
  5821. this.boundingBox._update(world);
  5822. this.boundingSphere._update(world);
  5823. };
  5824. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5825. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5826. return false;
  5827. return this.boundingBox.isInFrustum(frustumPlanes);
  5828. };
  5829. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5830. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5831. };
  5832. BoundingInfo.prototype._checkCollision = function (collider) {
  5833. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5834. };
  5835. BoundingInfo.prototype.intersectsPoint = function (point) {
  5836. if (!this.boundingSphere.centerWorld) {
  5837. return false;
  5838. }
  5839. if (!this.boundingSphere.intersectsPoint(point)) {
  5840. return false;
  5841. }
  5842. if (!this.boundingBox.intersectsPoint(point)) {
  5843. return false;
  5844. }
  5845. return true;
  5846. };
  5847. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5848. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5849. return false;
  5850. }
  5851. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5852. return false;
  5853. }
  5854. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5855. return false;
  5856. }
  5857. if (!precise) {
  5858. return true;
  5859. }
  5860. var box0 = this.boundingBox;
  5861. var box1 = boundingInfo.boundingBox;
  5862. if (!axisOverlap(box0.directions[0], box0, box1))
  5863. return false;
  5864. if (!axisOverlap(box0.directions[1], box0, box1))
  5865. return false;
  5866. if (!axisOverlap(box0.directions[2], box0, box1))
  5867. return false;
  5868. if (!axisOverlap(box1.directions[0], box0, box1))
  5869. return false;
  5870. if (!axisOverlap(box1.directions[1], box0, box1))
  5871. return false;
  5872. if (!axisOverlap(box1.directions[2], box0, box1))
  5873. return false;
  5874. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5875. return false;
  5876. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5877. return false;
  5878. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5879. return false;
  5880. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5881. return false;
  5882. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5883. return false;
  5884. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5885. return false;
  5886. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5887. return false;
  5888. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5889. return false;
  5890. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5891. return false;
  5892. return true;
  5893. };
  5894. return BoundingInfo;
  5895. })();
  5896. BABYLON.BoundingInfo = BoundingInfo;
  5897. })(BABYLON || (BABYLON = {}));
  5898. //# sourceMappingURL=babylon.boundingInfo.js.map
  5899. var BABYLON;
  5900. (function (BABYLON) {
  5901. var Light = (function (_super) {
  5902. __extends(Light, _super);
  5903. function Light(name, scene) {
  5904. _super.call(this, name, scene);
  5905. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5906. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5907. this.intensity = 1.0;
  5908. this.range = Number.MAX_VALUE;
  5909. this.includeOnlyWithLayerMask = 0;
  5910. this.includedOnlyMeshes = new Array();
  5911. this.excludedMeshes = new Array();
  5912. this._excludedMeshesIds = new Array();
  5913. this._includedOnlyMeshesIds = new Array();
  5914. scene.addLight(this);
  5915. }
  5916. Light.prototype.getShadowGenerator = function () {
  5917. return this._shadowGenerator;
  5918. };
  5919. Light.prototype.getAbsolutePosition = function () {
  5920. return BABYLON.Vector3.Zero();
  5921. };
  5922. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5923. };
  5924. Light.prototype._getWorldMatrix = function () {
  5925. return BABYLON.Matrix.Identity();
  5926. };
  5927. Light.prototype.canAffectMesh = function (mesh) {
  5928. if (!mesh) {
  5929. return true;
  5930. }
  5931. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5932. return false;
  5933. }
  5934. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5935. return false;
  5936. }
  5937. if (this.includeOnlyWithLayerMask !== 0 && this.includeOnlyWithLayerMask !== mesh.layerMask) {
  5938. return false;
  5939. }
  5940. return true;
  5941. };
  5942. Light.prototype.getWorldMatrix = function () {
  5943. this._currentRenderId = this.getScene().getRenderId();
  5944. var worldMatrix = this._getWorldMatrix();
  5945. if (this.parent && this.parent.getWorldMatrix) {
  5946. if (!this._parentedWorldMatrix) {
  5947. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5948. }
  5949. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5950. return this._parentedWorldMatrix;
  5951. }
  5952. return worldMatrix;
  5953. };
  5954. Light.prototype.dispose = function () {
  5955. if (this._shadowGenerator) {
  5956. this._shadowGenerator.dispose();
  5957. this._shadowGenerator = null;
  5958. }
  5959. // Remove from scene
  5960. this.getScene().removeLight(this);
  5961. };
  5962. return Light;
  5963. })(BABYLON.Node);
  5964. BABYLON.Light = Light;
  5965. })(BABYLON || (BABYLON = {}));
  5966. //# sourceMappingURL=babylon.light.js.map
  5967. var BABYLON;
  5968. (function (BABYLON) {
  5969. var PointLight = (function (_super) {
  5970. __extends(PointLight, _super);
  5971. function PointLight(name, position, scene) {
  5972. _super.call(this, name, scene);
  5973. this.position = position;
  5974. }
  5975. PointLight.prototype.getAbsolutePosition = function () {
  5976. return this._transformedPosition ? this._transformedPosition : this.position;
  5977. };
  5978. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5979. if (this.parent && this.parent.getWorldMatrix) {
  5980. if (!this._transformedPosition) {
  5981. this._transformedPosition = BABYLON.Vector3.Zero();
  5982. }
  5983. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5984. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5985. return;
  5986. }
  5987. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5988. };
  5989. PointLight.prototype.getShadowGenerator = function () {
  5990. return null;
  5991. };
  5992. PointLight.prototype._getWorldMatrix = function () {
  5993. if (!this._worldMatrix) {
  5994. this._worldMatrix = BABYLON.Matrix.Identity();
  5995. }
  5996. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5997. return this._worldMatrix;
  5998. };
  5999. return PointLight;
  6000. })(BABYLON.Light);
  6001. BABYLON.PointLight = PointLight;
  6002. })(BABYLON || (BABYLON = {}));
  6003. //# sourceMappingURL=babylon.pointLight.js.map
  6004. var BABYLON;
  6005. (function (BABYLON) {
  6006. var SpotLight = (function (_super) {
  6007. __extends(SpotLight, _super);
  6008. function SpotLight(name, position, direction, angle, exponent, scene) {
  6009. _super.call(this, name, scene);
  6010. this.position = position;
  6011. this.direction = direction;
  6012. this.angle = angle;
  6013. this.exponent = exponent;
  6014. }
  6015. SpotLight.prototype.getAbsolutePosition = function () {
  6016. return this.transformedPosition ? this.transformedPosition : this.position;
  6017. };
  6018. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6019. var activeCamera = this.getScene().activeCamera;
  6020. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6021. };
  6022. SpotLight.prototype.supportsVSM = function () {
  6023. return true;
  6024. };
  6025. SpotLight.prototype.needRefreshPerFrame = function () {
  6026. return false;
  6027. };
  6028. SpotLight.prototype.setDirectionToTarget = function (target) {
  6029. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6030. return this.direction;
  6031. };
  6032. SpotLight.prototype.computeTransformedPosition = function () {
  6033. if (this.parent && this.parent.getWorldMatrix) {
  6034. if (!this.transformedPosition) {
  6035. this.transformedPosition = BABYLON.Vector3.Zero();
  6036. }
  6037. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6038. return true;
  6039. }
  6040. return false;
  6041. };
  6042. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6043. var normalizeDirection;
  6044. if (this.parent && this.parent.getWorldMatrix) {
  6045. if (!this._transformedDirection) {
  6046. this._transformedDirection = BABYLON.Vector3.Zero();
  6047. }
  6048. this.computeTransformedPosition();
  6049. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6050. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6051. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6052. }
  6053. else {
  6054. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6055. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6056. }
  6057. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6058. };
  6059. SpotLight.prototype._getWorldMatrix = function () {
  6060. if (!this._worldMatrix) {
  6061. this._worldMatrix = BABYLON.Matrix.Identity();
  6062. }
  6063. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6064. return this._worldMatrix;
  6065. };
  6066. return SpotLight;
  6067. })(BABYLON.Light);
  6068. BABYLON.SpotLight = SpotLight;
  6069. })(BABYLON || (BABYLON = {}));
  6070. //# sourceMappingURL=babylon.spotLight.js.map
  6071. var BABYLON;
  6072. (function (BABYLON) {
  6073. var DirectionalLight = (function (_super) {
  6074. __extends(DirectionalLight, _super);
  6075. function DirectionalLight(name, direction, scene) {
  6076. _super.call(this, name, scene);
  6077. this.direction = direction;
  6078. this.shadowOrthoScale = 0.5;
  6079. this.position = direction.scale(-1);
  6080. }
  6081. DirectionalLight.prototype.getAbsolutePosition = function () {
  6082. return this.transformedPosition ? this.transformedPosition : this.position;
  6083. };
  6084. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6085. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6086. return this.direction;
  6087. };
  6088. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6089. var orthoLeft = Number.MAX_VALUE;
  6090. var orthoRight = Number.MIN_VALUE;
  6091. var orthoTop = Number.MIN_VALUE;
  6092. var orthoBottom = Number.MAX_VALUE;
  6093. var tempVector3 = BABYLON.Vector3.Zero();
  6094. var activeCamera = this.getScene().activeCamera;
  6095. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6096. var mesh = renderList[meshIndex];
  6097. if (!mesh) {
  6098. continue;
  6099. }
  6100. var boundingInfo = mesh.getBoundingInfo();
  6101. if (!boundingInfo) {
  6102. continue;
  6103. }
  6104. var boundingBox = boundingInfo.boundingBox;
  6105. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6106. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6107. if (tempVector3.x < orthoLeft)
  6108. orthoLeft = tempVector3.x;
  6109. if (tempVector3.y < orthoBottom)
  6110. orthoBottom = tempVector3.y;
  6111. if (tempVector3.x > orthoRight)
  6112. orthoRight = tempVector3.x;
  6113. if (tempVector3.y > orthoTop)
  6114. orthoTop = tempVector3.y;
  6115. }
  6116. }
  6117. var xOffset = orthoRight - orthoLeft;
  6118. var yOffset = orthoTop - orthoBottom;
  6119. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6120. };
  6121. DirectionalLight.prototype.supportsVSM = function () {
  6122. return true;
  6123. };
  6124. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6125. return true;
  6126. };
  6127. DirectionalLight.prototype.computeTransformedPosition = function () {
  6128. if (this.parent && this.parent.getWorldMatrix) {
  6129. if (!this.transformedPosition) {
  6130. this.transformedPosition = BABYLON.Vector3.Zero();
  6131. }
  6132. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6133. return true;
  6134. }
  6135. return false;
  6136. };
  6137. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6138. if (this.parent && this.parent.getWorldMatrix) {
  6139. if (!this._transformedDirection) {
  6140. this._transformedDirection = BABYLON.Vector3.Zero();
  6141. }
  6142. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6143. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6144. return;
  6145. }
  6146. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6147. };
  6148. DirectionalLight.prototype._getWorldMatrix = function () {
  6149. if (!this._worldMatrix) {
  6150. this._worldMatrix = BABYLON.Matrix.Identity();
  6151. }
  6152. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6153. return this._worldMatrix;
  6154. };
  6155. return DirectionalLight;
  6156. })(BABYLON.Light);
  6157. BABYLON.DirectionalLight = DirectionalLight;
  6158. })(BABYLON || (BABYLON = {}));
  6159. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6160. (function (BABYLON) {
  6161. var ShadowGenerator = (function () {
  6162. function ShadowGenerator(mapSize, light) {
  6163. var _this = this;
  6164. // Members
  6165. this._filter = ShadowGenerator.FILTER_NONE;
  6166. this.blurScale = 2;
  6167. this._blurBoxOffset = 0;
  6168. this._bias = 0.00005;
  6169. this._darkness = 0;
  6170. this._transparencyShadow = false;
  6171. this._viewMatrix = BABYLON.Matrix.Zero();
  6172. this._projectionMatrix = BABYLON.Matrix.Zero();
  6173. this._transformMatrix = BABYLON.Matrix.Zero();
  6174. this._worldViewProjection = BABYLON.Matrix.Zero();
  6175. this._light = light;
  6176. this._scene = light.getScene();
  6177. this._mapSize = mapSize;
  6178. light._shadowGenerator = this;
  6179. // Render target
  6180. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6181. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6182. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6183. this._shadowMap.anisotropicFilteringLevel = 1;
  6184. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6185. this._shadowMap.renderParticles = false;
  6186. this._shadowMap.onAfterUnbind = function () {
  6187. if (!_this.useBlurVarianceShadowMap) {
  6188. return;
  6189. }
  6190. if (!_this._shadowMap2) {
  6191. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6192. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6193. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6194. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6195. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6196. _this._downSamplePostprocess.onApply = function (effect) {
  6197. effect.setTexture("textureSampler", _this._shadowMap);
  6198. };
  6199. _this.blurBoxOffset = 1;
  6200. }
  6201. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6202. };
  6203. // Custom render function
  6204. var renderSubMesh = function (subMesh) {
  6205. var mesh = subMesh.getRenderingMesh();
  6206. var scene = _this._scene;
  6207. var engine = scene.getEngine();
  6208. // Culling
  6209. engine.setState(subMesh.getMaterial().backFaceCulling);
  6210. // Managing instances
  6211. var batch = mesh._getInstancesRenderList(subMesh._id);
  6212. if (batch.mustReturn) {
  6213. return;
  6214. }
  6215. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6216. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6217. engine.enableEffect(_this._effect);
  6218. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6219. var material = subMesh.getMaterial();
  6220. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6221. // Alpha test
  6222. if (material && material.needAlphaTesting()) {
  6223. var alphaTexture = material.getAlphaTestTexture();
  6224. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6225. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6226. }
  6227. // Bones
  6228. if (mesh.useBones) {
  6229. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6230. }
  6231. // Draw
  6232. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6233. }
  6234. else {
  6235. // Need to reset refresh rate of the shadowMap
  6236. _this._shadowMap.resetRefreshCounter();
  6237. }
  6238. };
  6239. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6240. var index;
  6241. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6242. renderSubMesh(opaqueSubMeshes.data[index]);
  6243. }
  6244. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6245. renderSubMesh(alphaTestSubMeshes.data[index]);
  6246. }
  6247. if (_this._transparencyShadow) {
  6248. for (index = 0; index < transparentSubMeshes.length; index++) {
  6249. renderSubMesh(transparentSubMeshes.data[index]);
  6250. }
  6251. }
  6252. };
  6253. this._shadowMap.onClear = function (engine) {
  6254. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6255. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6256. }
  6257. else {
  6258. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6259. }
  6260. };
  6261. }
  6262. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6263. // Static
  6264. get: function () {
  6265. return ShadowGenerator._FILTER_NONE;
  6266. },
  6267. enumerable: true,
  6268. configurable: true
  6269. });
  6270. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6271. get: function () {
  6272. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6273. },
  6274. enumerable: true,
  6275. configurable: true
  6276. });
  6277. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6278. get: function () {
  6279. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6280. },
  6281. enumerable: true,
  6282. configurable: true
  6283. });
  6284. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6285. get: function () {
  6286. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6287. },
  6288. enumerable: true,
  6289. configurable: true
  6290. });
  6291. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6292. get: function () {
  6293. return this._bias;
  6294. },
  6295. set: function (bias) {
  6296. this._bias = bias;
  6297. },
  6298. enumerable: true,
  6299. configurable: true
  6300. });
  6301. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6302. get: function () {
  6303. return this._blurBoxOffset;
  6304. },
  6305. set: function (value) {
  6306. var _this = this;
  6307. if (this._blurBoxOffset === value) {
  6308. return;
  6309. }
  6310. this._blurBoxOffset = value;
  6311. if (this._boxBlurPostprocess) {
  6312. this._boxBlurPostprocess.dispose();
  6313. }
  6314. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  6315. this._boxBlurPostprocess.onApply = function (effect) {
  6316. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6317. };
  6318. },
  6319. enumerable: true,
  6320. configurable: true
  6321. });
  6322. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6323. get: function () {
  6324. return this._filter;
  6325. },
  6326. set: function (value) {
  6327. if (this._filter === value) {
  6328. return;
  6329. }
  6330. this._filter = value;
  6331. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6332. this._shadowMap.anisotropicFilteringLevel = 16;
  6333. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6334. }
  6335. else {
  6336. this._shadowMap.anisotropicFilteringLevel = 1;
  6337. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6338. }
  6339. },
  6340. enumerable: true,
  6341. configurable: true
  6342. });
  6343. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6344. get: function () {
  6345. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6346. },
  6347. set: function (value) {
  6348. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6354. get: function () {
  6355. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6356. },
  6357. set: function (value) {
  6358. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6364. get: function () {
  6365. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6366. },
  6367. set: function (value) {
  6368. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6369. },
  6370. enumerable: true,
  6371. configurable: true
  6372. });
  6373. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6374. var defines = [];
  6375. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6376. defines.push("#define VSM");
  6377. }
  6378. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6379. var mesh = subMesh.getMesh();
  6380. var material = subMesh.getMaterial();
  6381. // Alpha test
  6382. if (material && material.needAlphaTesting()) {
  6383. defines.push("#define ALPHATEST");
  6384. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6385. attribs.push(BABYLON.VertexBuffer.UVKind);
  6386. defines.push("#define UV1");
  6387. }
  6388. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6389. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6390. defines.push("#define UV2");
  6391. }
  6392. }
  6393. // Bones
  6394. if (mesh.useBones) {
  6395. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6396. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6397. defines.push("#define BONES");
  6398. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6399. }
  6400. // Instances
  6401. if (useInstances) {
  6402. defines.push("#define INSTANCES");
  6403. attribs.push("world0");
  6404. attribs.push("world1");
  6405. attribs.push("world2");
  6406. attribs.push("world3");
  6407. }
  6408. // Get correct effect
  6409. var join = defines.join("\n");
  6410. if (this._cachedDefines !== join) {
  6411. this._cachedDefines = join;
  6412. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6413. }
  6414. return this._effect.isReady();
  6415. };
  6416. ShadowGenerator.prototype.getShadowMap = function () {
  6417. return this._shadowMap;
  6418. };
  6419. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6420. if (this._shadowMap2) {
  6421. return this._shadowMap2;
  6422. }
  6423. return this._shadowMap;
  6424. };
  6425. ShadowGenerator.prototype.getLight = function () {
  6426. return this._light;
  6427. };
  6428. // Methods
  6429. ShadowGenerator.prototype.getTransformMatrix = function () {
  6430. var scene = this._scene;
  6431. if (this._currentRenderID === scene.getRenderId()) {
  6432. return this._transformMatrix;
  6433. }
  6434. this._currentRenderID = scene.getRenderId();
  6435. var lightPosition = this._light.position;
  6436. var lightDirection = this._light.direction;
  6437. if (this._light.computeTransformedPosition()) {
  6438. lightPosition = this._light.transformedPosition;
  6439. }
  6440. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6441. this._cachedPosition = lightPosition.clone();
  6442. this._cachedDirection = lightDirection.clone();
  6443. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6444. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6445. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6446. }
  6447. return this._transformMatrix;
  6448. };
  6449. ShadowGenerator.prototype.getDarkness = function () {
  6450. return this._darkness;
  6451. };
  6452. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6453. if (darkness >= 1.0)
  6454. this._darkness = 1.0;
  6455. else if (darkness <= 0.0)
  6456. this._darkness = 0.0;
  6457. else
  6458. this._darkness = darkness;
  6459. };
  6460. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6461. this._transparencyShadow = hasShadow;
  6462. };
  6463. ShadowGenerator.prototype._packHalf = function (depth) {
  6464. var scale = depth * 255.0;
  6465. var fract = scale - Math.floor(scale);
  6466. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6467. };
  6468. ShadowGenerator.prototype.dispose = function () {
  6469. this._shadowMap.dispose();
  6470. if (this._shadowMap2) {
  6471. this._shadowMap2.dispose();
  6472. }
  6473. if (this._downSamplePostprocess) {
  6474. this._downSamplePostprocess.dispose();
  6475. }
  6476. if (this._boxBlurPostprocess) {
  6477. this._boxBlurPostprocess.dispose();
  6478. }
  6479. };
  6480. ShadowGenerator._FILTER_NONE = 0;
  6481. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6482. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6483. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6484. return ShadowGenerator;
  6485. })();
  6486. BABYLON.ShadowGenerator = ShadowGenerator;
  6487. })(BABYLON || (BABYLON = {}));
  6488. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6489. var BABYLON;
  6490. (function (BABYLON) {
  6491. var HemisphericLight = (function (_super) {
  6492. __extends(HemisphericLight, _super);
  6493. function HemisphericLight(name, direction, scene) {
  6494. _super.call(this, name, scene);
  6495. this.direction = direction;
  6496. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6497. }
  6498. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6499. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6500. return this.direction;
  6501. };
  6502. HemisphericLight.prototype.getShadowGenerator = function () {
  6503. return null;
  6504. };
  6505. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6506. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6507. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6508. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6509. };
  6510. HemisphericLight.prototype._getWorldMatrix = function () {
  6511. if (!this._worldMatrix) {
  6512. this._worldMatrix = BABYLON.Matrix.Identity();
  6513. }
  6514. return this._worldMatrix;
  6515. };
  6516. return HemisphericLight;
  6517. })(BABYLON.Light);
  6518. BABYLON.HemisphericLight = HemisphericLight;
  6519. })(BABYLON || (BABYLON = {}));
  6520. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6521. (function (BABYLON) {
  6522. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6523. if (boxMin.x > sphereCenter.x + sphereRadius)
  6524. return false;
  6525. if (sphereCenter.x - sphereRadius > boxMax.x)
  6526. return false;
  6527. if (boxMin.y > sphereCenter.y + sphereRadius)
  6528. return false;
  6529. if (sphereCenter.y - sphereRadius > boxMax.y)
  6530. return false;
  6531. if (boxMin.z > sphereCenter.z + sphereRadius)
  6532. return false;
  6533. if (sphereCenter.z - sphereRadius > boxMax.z)
  6534. return false;
  6535. return true;
  6536. };
  6537. var getLowestRoot = function (a, b, c, maxR) {
  6538. var determinant = b * b - 4.0 * a * c;
  6539. var result = { root: 0, found: false };
  6540. if (determinant < 0)
  6541. return result;
  6542. var sqrtD = Math.sqrt(determinant);
  6543. var r1 = (-b - sqrtD) / (2.0 * a);
  6544. var r2 = (-b + sqrtD) / (2.0 * a);
  6545. if (r1 > r2) {
  6546. var temp = r2;
  6547. r2 = r1;
  6548. r1 = temp;
  6549. }
  6550. if (r1 > 0 && r1 < maxR) {
  6551. result.root = r1;
  6552. result.found = true;
  6553. return result;
  6554. }
  6555. if (r2 > 0 && r2 < maxR) {
  6556. result.root = r2;
  6557. result.found = true;
  6558. return result;
  6559. }
  6560. return result;
  6561. };
  6562. var Collider = (function () {
  6563. function Collider() {
  6564. this.radius = new BABYLON.Vector3(1, 1, 1);
  6565. this.retry = 0;
  6566. this.basePointWorld = BABYLON.Vector3.Zero();
  6567. this.velocityWorld = BABYLON.Vector3.Zero();
  6568. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6569. this._collisionPoint = BABYLON.Vector3.Zero();
  6570. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6571. this._tempVector = BABYLON.Vector3.Zero();
  6572. this._tempVector2 = BABYLON.Vector3.Zero();
  6573. this._tempVector3 = BABYLON.Vector3.Zero();
  6574. this._tempVector4 = BABYLON.Vector3.Zero();
  6575. this._edge = BABYLON.Vector3.Zero();
  6576. this._baseToVertex = BABYLON.Vector3.Zero();
  6577. this._destinationPoint = BABYLON.Vector3.Zero();
  6578. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6579. this._displacementVector = BABYLON.Vector3.Zero();
  6580. }
  6581. // Methods
  6582. Collider.prototype._initialize = function (source, dir, e) {
  6583. this.velocity = dir;
  6584. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6585. this.basePoint = source;
  6586. source.multiplyToRef(this.radius, this.basePointWorld);
  6587. dir.multiplyToRef(this.radius, this.velocityWorld);
  6588. this.velocityWorldLength = this.velocityWorld.length();
  6589. this.epsilon = e;
  6590. this.collisionFound = false;
  6591. };
  6592. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6593. pa.subtractToRef(point, this._tempVector);
  6594. pb.subtractToRef(point, this._tempVector2);
  6595. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6596. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6597. if (d < 0)
  6598. return false;
  6599. pc.subtractToRef(point, this._tempVector3);
  6600. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6601. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6602. if (d < 0)
  6603. return false;
  6604. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6605. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6606. return d >= 0;
  6607. };
  6608. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6609. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6610. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6611. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6612. return false;
  6613. }
  6614. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6615. return false;
  6616. return true;
  6617. };
  6618. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6619. var t0;
  6620. var embeddedInPlane = false;
  6621. if (!subMesh._trianglePlanes) {
  6622. subMesh._trianglePlanes = [];
  6623. }
  6624. if (!subMesh._trianglePlanes[faceIndex]) {
  6625. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6626. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6627. }
  6628. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6629. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6630. return;
  6631. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6632. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6633. if (normalDotVelocity == 0) {
  6634. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6635. return;
  6636. embeddedInPlane = true;
  6637. t0 = 0;
  6638. }
  6639. else {
  6640. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6641. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6642. if (t0 > t1) {
  6643. var temp = t1;
  6644. t1 = t0;
  6645. t0 = temp;
  6646. }
  6647. if (t0 > 1.0 || t1 < 0.0)
  6648. return;
  6649. if (t0 < 0)
  6650. t0 = 0;
  6651. if (t0 > 1.0)
  6652. t0 = 1.0;
  6653. }
  6654. this._collisionPoint.copyFromFloats(0, 0, 0);
  6655. var found = false;
  6656. var t = 1.0;
  6657. if (!embeddedInPlane) {
  6658. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6659. this.velocity.scaleToRef(t0, this._tempVector);
  6660. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6661. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6662. found = true;
  6663. t = t0;
  6664. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6665. }
  6666. }
  6667. if (!found) {
  6668. var velocitySquaredLength = this.velocity.lengthSquared();
  6669. var a = velocitySquaredLength;
  6670. this.basePoint.subtractToRef(p1, this._tempVector);
  6671. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6672. var c = this._tempVector.lengthSquared() - 1.0;
  6673. var lowestRoot = getLowestRoot(a, b, c, t);
  6674. if (lowestRoot.found) {
  6675. t = lowestRoot.root;
  6676. found = true;
  6677. this._collisionPoint.copyFrom(p1);
  6678. }
  6679. this.basePoint.subtractToRef(p2, this._tempVector);
  6680. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6681. c = this._tempVector.lengthSquared() - 1.0;
  6682. lowestRoot = getLowestRoot(a, b, c, t);
  6683. if (lowestRoot.found) {
  6684. t = lowestRoot.root;
  6685. found = true;
  6686. this._collisionPoint.copyFrom(p2);
  6687. }
  6688. this.basePoint.subtractToRef(p3, this._tempVector);
  6689. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6690. c = this._tempVector.lengthSquared() - 1.0;
  6691. lowestRoot = getLowestRoot(a, b, c, t);
  6692. if (lowestRoot.found) {
  6693. t = lowestRoot.root;
  6694. found = true;
  6695. this._collisionPoint.copyFrom(p3);
  6696. }
  6697. p2.subtractToRef(p1, this._edge);
  6698. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6699. var edgeSquaredLength = this._edge.lengthSquared();
  6700. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6701. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6702. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6703. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6704. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6705. lowestRoot = getLowestRoot(a, b, c, t);
  6706. if (lowestRoot.found) {
  6707. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6708. if (f >= 0.0 && f <= 1.0) {
  6709. t = lowestRoot.root;
  6710. found = true;
  6711. this._edge.scaleInPlace(f);
  6712. p1.addToRef(this._edge, this._collisionPoint);
  6713. }
  6714. }
  6715. p3.subtractToRef(p2, this._edge);
  6716. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6717. edgeSquaredLength = this._edge.lengthSquared();
  6718. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6719. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6720. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6721. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6722. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6723. lowestRoot = getLowestRoot(a, b, c, t);
  6724. if (lowestRoot.found) {
  6725. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6726. if (f >= 0.0 && f <= 1.0) {
  6727. t = lowestRoot.root;
  6728. found = true;
  6729. this._edge.scaleInPlace(f);
  6730. p2.addToRef(this._edge, this._collisionPoint);
  6731. }
  6732. }
  6733. p1.subtractToRef(p3, this._edge);
  6734. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6735. edgeSquaredLength = this._edge.lengthSquared();
  6736. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6737. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6738. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6739. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6740. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6741. lowestRoot = getLowestRoot(a, b, c, t);
  6742. if (lowestRoot.found) {
  6743. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6744. if (f >= 0.0 && f <= 1.0) {
  6745. t = lowestRoot.root;
  6746. found = true;
  6747. this._edge.scaleInPlace(f);
  6748. p3.addToRef(this._edge, this._collisionPoint);
  6749. }
  6750. }
  6751. }
  6752. if (found) {
  6753. var distToCollision = t * this.velocity.length();
  6754. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6755. if (!this.intersectionPoint) {
  6756. this.intersectionPoint = this._collisionPoint.clone();
  6757. }
  6758. else {
  6759. this.intersectionPoint.copyFrom(this._collisionPoint);
  6760. }
  6761. this.nearestDistance = distToCollision;
  6762. this.collisionFound = true;
  6763. this.collidedMesh = subMesh.getMesh();
  6764. }
  6765. }
  6766. };
  6767. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6768. for (var i = indexStart; i < indexEnd; i += 3) {
  6769. var p1 = pts[indices[i] - decal];
  6770. var p2 = pts[indices[i + 1] - decal];
  6771. var p3 = pts[indices[i + 2] - decal];
  6772. this._testTriangle(i, subMesh, p3, p2, p1);
  6773. }
  6774. };
  6775. Collider.prototype._getResponse = function (pos, vel) {
  6776. pos.addToRef(vel, this._destinationPoint);
  6777. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6778. this.basePoint.addToRef(vel, pos);
  6779. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6780. this._slidePlaneNormal.normalize();
  6781. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6782. pos.addInPlace(this._displacementVector);
  6783. this.intersectionPoint.addInPlace(this._displacementVector);
  6784. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6785. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6786. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6787. };
  6788. return Collider;
  6789. })();
  6790. BABYLON.Collider = Collider;
  6791. })(BABYLON || (BABYLON = {}));
  6792. //# sourceMappingURL=babylon.collider.js.map
  6793. var BABYLON;
  6794. (function (BABYLON) {
  6795. var Camera = (function (_super) {
  6796. __extends(Camera, _super);
  6797. function Camera(name, position, scene) {
  6798. _super.call(this, name, scene);
  6799. this.position = position;
  6800. // Members
  6801. this.upVector = BABYLON.Vector3.Up();
  6802. this.orthoLeft = null;
  6803. this.orthoRight = null;
  6804. this.orthoBottom = null;
  6805. this.orthoTop = null;
  6806. this.fov = 0.8;
  6807. this.minZ = 1.0;
  6808. this.maxZ = 10000.0;
  6809. this.inertia = 0.9;
  6810. this.mode = Camera.PERSPECTIVE_CAMERA;
  6811. this.isIntermediate = false;
  6812. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6813. this.subCameras = [];
  6814. this.layerMask = 0xFFFFFFFF;
  6815. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6816. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6817. this._projectionMatrix = new BABYLON.Matrix();
  6818. this._postProcesses = new Array();
  6819. this._postProcessesTakenIndices = [];
  6820. this._activeMeshes = new BABYLON.SmartArray(256);
  6821. scene.addCamera(this);
  6822. if (!scene.activeCamera) {
  6823. scene.activeCamera = this;
  6824. }
  6825. }
  6826. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6827. get: function () {
  6828. return Camera._PERSPECTIVE_CAMERA;
  6829. },
  6830. enumerable: true,
  6831. configurable: true
  6832. });
  6833. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6834. get: function () {
  6835. return Camera._ORTHOGRAPHIC_CAMERA;
  6836. },
  6837. enumerable: true,
  6838. configurable: true
  6839. });
  6840. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6841. get: function () {
  6842. return Camera._FOVMODE_VERTICAL_FIXED;
  6843. },
  6844. enumerable: true,
  6845. configurable: true
  6846. });
  6847. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6848. get: function () {
  6849. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6850. },
  6851. enumerable: true,
  6852. configurable: true
  6853. });
  6854. Camera.prototype.getActiveMeshes = function () {
  6855. return this._activeMeshes;
  6856. };
  6857. Camera.prototype.isActiveMesh = function (mesh) {
  6858. return (this._activeMeshes.indexOf(mesh) !== -1);
  6859. };
  6860. //Cache
  6861. Camera.prototype._initCache = function () {
  6862. _super.prototype._initCache.call(this);
  6863. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6864. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6865. this._cache.mode = undefined;
  6866. this._cache.minZ = undefined;
  6867. this._cache.maxZ = undefined;
  6868. this._cache.fov = undefined;
  6869. this._cache.aspectRatio = undefined;
  6870. this._cache.orthoLeft = undefined;
  6871. this._cache.orthoRight = undefined;
  6872. this._cache.orthoBottom = undefined;
  6873. this._cache.orthoTop = undefined;
  6874. this._cache.renderWidth = undefined;
  6875. this._cache.renderHeight = undefined;
  6876. };
  6877. Camera.prototype._updateCache = function (ignoreParentClass) {
  6878. if (!ignoreParentClass) {
  6879. _super.prototype._updateCache.call(this);
  6880. }
  6881. var engine = this.getEngine();
  6882. this._cache.position.copyFrom(this.position);
  6883. this._cache.upVector.copyFrom(this.upVector);
  6884. this._cache.mode = this.mode;
  6885. this._cache.minZ = this.minZ;
  6886. this._cache.maxZ = this.maxZ;
  6887. this._cache.fov = this.fov;
  6888. this._cache.aspectRatio = engine.getAspectRatio(this);
  6889. this._cache.orthoLeft = this.orthoLeft;
  6890. this._cache.orthoRight = this.orthoRight;
  6891. this._cache.orthoBottom = this.orthoBottom;
  6892. this._cache.orthoTop = this.orthoTop;
  6893. this._cache.renderWidth = engine.getRenderWidth();
  6894. this._cache.renderHeight = engine.getRenderHeight();
  6895. };
  6896. Camera.prototype._updateFromScene = function () {
  6897. this.updateCache();
  6898. this._update();
  6899. };
  6900. // Synchronized
  6901. Camera.prototype._isSynchronized = function () {
  6902. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6903. };
  6904. Camera.prototype._isSynchronizedViewMatrix = function () {
  6905. if (!_super.prototype._isSynchronized.call(this))
  6906. return false;
  6907. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6908. };
  6909. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6910. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6911. if (!check) {
  6912. return false;
  6913. }
  6914. var engine = this.getEngine();
  6915. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6916. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6917. }
  6918. else {
  6919. 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();
  6920. }
  6921. return check;
  6922. };
  6923. // Controls
  6924. Camera.prototype.attachControl = function (element) {
  6925. };
  6926. Camera.prototype.detachControl = function (element) {
  6927. };
  6928. Camera.prototype._update = function () {
  6929. };
  6930. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6931. if (insertAt === void 0) { insertAt = null; }
  6932. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6933. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6934. return 0;
  6935. }
  6936. if (insertAt == null || insertAt < 0) {
  6937. this._postProcesses.push(postProcess);
  6938. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6939. return this._postProcesses.length - 1;
  6940. }
  6941. var add = 0;
  6942. if (this._postProcesses[insertAt]) {
  6943. var start = this._postProcesses.length - 1;
  6944. for (var i = start; i >= insertAt + 1; --i) {
  6945. this._postProcesses[i + 1] = this._postProcesses[i];
  6946. }
  6947. add = 1;
  6948. }
  6949. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6950. if (this._postProcessesTakenIndices[i] < insertAt) {
  6951. continue;
  6952. }
  6953. start = this._postProcessesTakenIndices.length - 1;
  6954. for (var j = start; j >= i; --j) {
  6955. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6956. }
  6957. this._postProcessesTakenIndices[i] = insertAt;
  6958. break;
  6959. }
  6960. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6961. this._postProcessesTakenIndices.push(insertAt);
  6962. }
  6963. var result = insertAt + add;
  6964. this._postProcesses[result] = postProcess;
  6965. return result;
  6966. };
  6967. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6968. if (atIndices === void 0) { atIndices = null; }
  6969. var result = [];
  6970. if (!atIndices) {
  6971. var length = this._postProcesses.length;
  6972. for (var i = 0; i < length; i++) {
  6973. if (this._postProcesses[i] !== postProcess) {
  6974. continue;
  6975. }
  6976. delete this._postProcesses[i];
  6977. var index = this._postProcessesTakenIndices.indexOf(i);
  6978. this._postProcessesTakenIndices.splice(index, 1);
  6979. }
  6980. }
  6981. else {
  6982. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6983. for (i = 0; i < atIndices.length; i++) {
  6984. var foundPostProcess = this._postProcesses[atIndices[i]];
  6985. if (foundPostProcess !== postProcess) {
  6986. result.push(i);
  6987. continue;
  6988. }
  6989. delete this._postProcesses[atIndices[i]];
  6990. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6991. this._postProcessesTakenIndices.splice(index, 1);
  6992. }
  6993. }
  6994. return result;
  6995. };
  6996. Camera.prototype.getWorldMatrix = function () {
  6997. if (!this._worldMatrix) {
  6998. this._worldMatrix = BABYLON.Matrix.Identity();
  6999. }
  7000. var viewMatrix = this.getViewMatrix();
  7001. viewMatrix.invertToRef(this._worldMatrix);
  7002. return this._worldMatrix;
  7003. };
  7004. Camera.prototype._getViewMatrix = function () {
  7005. return BABYLON.Matrix.Identity();
  7006. };
  7007. Camera.prototype.getViewMatrix = function () {
  7008. this._computedViewMatrix = this._computeViewMatrix();
  7009. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  7010. return this._computedViewMatrix;
  7011. }
  7012. if (!this._worldMatrix) {
  7013. this._worldMatrix = BABYLON.Matrix.Identity();
  7014. }
  7015. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7016. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7017. this._computedViewMatrix.invert();
  7018. this._currentRenderId = this.getScene().getRenderId();
  7019. return this._computedViewMatrix;
  7020. };
  7021. Camera.prototype._computeViewMatrix = function (force) {
  7022. if (!force && this._isSynchronizedViewMatrix()) {
  7023. return this._computedViewMatrix;
  7024. }
  7025. this._computedViewMatrix = this._getViewMatrix();
  7026. if (!this.parent || !this.parent.getWorldMatrix) {
  7027. this._currentRenderId = this.getScene().getRenderId();
  7028. }
  7029. return this._computedViewMatrix;
  7030. };
  7031. Camera.prototype.getProjectionMatrix = function (force) {
  7032. if (!force && this._isSynchronizedProjectionMatrix()) {
  7033. return this._projectionMatrix;
  7034. }
  7035. var engine = this.getEngine();
  7036. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7037. if (this.minZ <= 0) {
  7038. this.minZ = 0.1;
  7039. }
  7040. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7041. return this._projectionMatrix;
  7042. }
  7043. var halfWidth = engine.getRenderWidth() / 2.0;
  7044. var halfHeight = engine.getRenderHeight() / 2.0;
  7045. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7046. return this._projectionMatrix;
  7047. };
  7048. Camera.prototype.dispose = function () {
  7049. // Remove from scene
  7050. this.getScene().removeCamera(this);
  7051. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7052. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7053. }
  7054. };
  7055. // Statics
  7056. Camera._PERSPECTIVE_CAMERA = 0;
  7057. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7058. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7059. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7060. return Camera;
  7061. })(BABYLON.Node);
  7062. BABYLON.Camera = Camera;
  7063. })(BABYLON || (BABYLON = {}));
  7064. //# sourceMappingURL=babylon.camera.js.map
  7065. var BABYLON;
  7066. (function (BABYLON) {
  7067. var TargetCamera = (function (_super) {
  7068. __extends(TargetCamera, _super);
  7069. function TargetCamera(name, position, scene) {
  7070. _super.call(this, name, position, scene);
  7071. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7072. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7073. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7074. this.speed = 2.0;
  7075. this.noRotationConstraint = false;
  7076. this.lockedTarget = null;
  7077. this._currentTarget = BABYLON.Vector3.Zero();
  7078. this._viewMatrix = BABYLON.Matrix.Zero();
  7079. this._camMatrix = BABYLON.Matrix.Zero();
  7080. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7081. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7082. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7083. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7084. this._lookAtTemp = BABYLON.Matrix.Zero();
  7085. this._tempMatrix = BABYLON.Matrix.Zero();
  7086. }
  7087. TargetCamera.prototype._getLockedTargetPosition = function () {
  7088. if (!this.lockedTarget) {
  7089. return null;
  7090. }
  7091. return this.lockedTarget.position || this.lockedTarget;
  7092. };
  7093. // Cache
  7094. TargetCamera.prototype._initCache = function () {
  7095. _super.prototype._initCache.call(this);
  7096. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7097. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7098. };
  7099. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7100. if (!ignoreParentClass) {
  7101. _super.prototype._updateCache.call(this);
  7102. }
  7103. var lockedTargetPosition = this._getLockedTargetPosition();
  7104. if (!lockedTargetPosition) {
  7105. this._cache.lockedTarget = null;
  7106. }
  7107. else {
  7108. if (!this._cache.lockedTarget) {
  7109. this._cache.lockedTarget = lockedTargetPosition.clone();
  7110. }
  7111. else {
  7112. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7113. }
  7114. }
  7115. this._cache.rotation.copyFrom(this.rotation);
  7116. };
  7117. // Synchronized
  7118. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7119. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7120. return false;
  7121. }
  7122. var lockedTargetPosition = this._getLockedTargetPosition();
  7123. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7124. };
  7125. // Methods
  7126. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7127. var engine = this.getEngine();
  7128. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7129. };
  7130. // Target
  7131. TargetCamera.prototype.setTarget = function (target) {
  7132. this.upVector.normalize();
  7133. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7134. this._camMatrix.invert();
  7135. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7136. var vDir = target.subtract(this.position);
  7137. if (vDir.x >= 0.0) {
  7138. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7139. }
  7140. else {
  7141. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7142. }
  7143. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7144. if (isNaN(this.rotation.x)) {
  7145. this.rotation.x = 0;
  7146. }
  7147. if (isNaN(this.rotation.y)) {
  7148. this.rotation.y = 0;
  7149. }
  7150. if (isNaN(this.rotation.z)) {
  7151. this.rotation.z = 0;
  7152. }
  7153. };
  7154. TargetCamera.prototype.getTarget = function () {
  7155. return this._currentTarget;
  7156. };
  7157. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7158. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7159. };
  7160. TargetCamera.prototype._updatePosition = function () {
  7161. this.position.addInPlace(this.cameraDirection);
  7162. };
  7163. TargetCamera.prototype._update = function () {
  7164. var needToMove = this._decideIfNeedsToMove();
  7165. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7166. // Move
  7167. if (needToMove) {
  7168. this._updatePosition();
  7169. }
  7170. // Rotate
  7171. if (needToRotate) {
  7172. this.rotation.x += this.cameraRotation.x;
  7173. this.rotation.y += this.cameraRotation.y;
  7174. if (!this.noRotationConstraint) {
  7175. var limit = (Math.PI / 2) * 0.95;
  7176. if (this.rotation.x > limit)
  7177. this.rotation.x = limit;
  7178. if (this.rotation.x < -limit)
  7179. this.rotation.x = -limit;
  7180. }
  7181. }
  7182. // Inertia
  7183. if (needToMove) {
  7184. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7185. this.cameraDirection.x = 0;
  7186. }
  7187. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7188. this.cameraDirection.y = 0;
  7189. }
  7190. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7191. this.cameraDirection.z = 0;
  7192. }
  7193. this.cameraDirection.scaleInPlace(this.inertia);
  7194. }
  7195. if (needToRotate) {
  7196. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7197. this.cameraRotation.x = 0;
  7198. }
  7199. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7200. this.cameraRotation.y = 0;
  7201. }
  7202. this.cameraRotation.scaleInPlace(this.inertia);
  7203. }
  7204. };
  7205. TargetCamera.prototype._getViewMatrix = function () {
  7206. if (!this.lockedTarget) {
  7207. // Compute
  7208. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7209. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7210. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7211. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7212. this._lookAtTemp.invert();
  7213. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7214. }
  7215. else {
  7216. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7217. }
  7218. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7219. // Computing target and final matrix
  7220. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7221. }
  7222. else {
  7223. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7224. }
  7225. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7226. return this._viewMatrix;
  7227. };
  7228. return TargetCamera;
  7229. })(BABYLON.Camera);
  7230. BABYLON.TargetCamera = TargetCamera;
  7231. })(BABYLON || (BABYLON = {}));
  7232. //# sourceMappingURL=babylon.targetCamera.js.map
  7233. var BABYLON;
  7234. (function (BABYLON) {
  7235. var FollowCamera = (function (_super) {
  7236. __extends(FollowCamera, _super);
  7237. function FollowCamera(name, position, scene) {
  7238. _super.call(this, name, position, scene);
  7239. this.radius = 12;
  7240. this.rotationOffset = 0;
  7241. this.heightOffset = 4;
  7242. this.cameraAcceleration = 0.05;
  7243. this.maxCameraSpeed = 20;
  7244. }
  7245. FollowCamera.prototype.getRadians = function (degrees) {
  7246. return degrees * Math.PI / 180;
  7247. };
  7248. FollowCamera.prototype.follow = function (cameraTarget) {
  7249. if (!cameraTarget)
  7250. return;
  7251. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7252. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7253. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7254. var dx = targetX - this.position.x;
  7255. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7256. var dz = (targetZ) - this.position.z;
  7257. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7258. var vy = dy * this.cameraAcceleration;
  7259. var vz = dz * this.cameraAcceleration * 2;
  7260. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7261. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7262. }
  7263. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7264. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7265. }
  7266. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7267. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7268. }
  7269. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7270. this.setTarget(cameraTarget.position);
  7271. };
  7272. FollowCamera.prototype._update = function () {
  7273. _super.prototype._update.call(this);
  7274. this.follow(this.target);
  7275. };
  7276. return FollowCamera;
  7277. })(BABYLON.TargetCamera);
  7278. BABYLON.FollowCamera = FollowCamera;
  7279. })(BABYLON || (BABYLON = {}));
  7280. //# sourceMappingURL=babylon.followCamera.js.map
  7281. var BABYLON;
  7282. (function (BABYLON) {
  7283. var FreeCamera = (function (_super) {
  7284. __extends(FreeCamera, _super);
  7285. function FreeCamera(name, position, scene) {
  7286. _super.call(this, name, position, scene);
  7287. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7288. this.keysUp = [38];
  7289. this.keysDown = [40];
  7290. this.keysLeft = [37];
  7291. this.keysRight = [39];
  7292. this.checkCollisions = false;
  7293. this.applyGravity = false;
  7294. this.angularSensibility = 2000.0;
  7295. this._keys = [];
  7296. this._collider = new BABYLON.Collider();
  7297. this._needMoveForGravity = true;
  7298. this._oldPosition = BABYLON.Vector3.Zero();
  7299. this._diffPosition = BABYLON.Vector3.Zero();
  7300. this._newPosition = BABYLON.Vector3.Zero();
  7301. }
  7302. // Controls
  7303. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7304. var _this = this;
  7305. var previousPosition;
  7306. var engine = this.getEngine();
  7307. if (this._attachedElement) {
  7308. return;
  7309. }
  7310. this._attachedElement = element;
  7311. if (this._onMouseDown === undefined) {
  7312. this._onMouseDown = function (evt) {
  7313. previousPosition = {
  7314. x: evt.clientX,
  7315. y: evt.clientY
  7316. };
  7317. if (!noPreventDefault) {
  7318. evt.preventDefault();
  7319. }
  7320. };
  7321. this._onMouseUp = function (evt) {
  7322. previousPosition = null;
  7323. if (!noPreventDefault) {
  7324. evt.preventDefault();
  7325. }
  7326. };
  7327. this._onMouseOut = function (evt) {
  7328. previousPosition = null;
  7329. _this._keys = [];
  7330. if (!noPreventDefault) {
  7331. evt.preventDefault();
  7332. }
  7333. };
  7334. this._onMouseMove = function (evt) {
  7335. if (!previousPosition && !engine.isPointerLock) {
  7336. return;
  7337. }
  7338. var offsetX;
  7339. var offsetY;
  7340. if (!engine.isPointerLock) {
  7341. offsetX = evt.clientX - previousPosition.x;
  7342. offsetY = evt.clientY - previousPosition.y;
  7343. }
  7344. else {
  7345. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7346. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7347. }
  7348. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7349. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7350. previousPosition = {
  7351. x: evt.clientX,
  7352. y: evt.clientY
  7353. };
  7354. if (!noPreventDefault) {
  7355. evt.preventDefault();
  7356. }
  7357. };
  7358. this._onKeyDown = function (evt) {
  7359. 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) {
  7360. var index = _this._keys.indexOf(evt.keyCode);
  7361. if (index === -1) {
  7362. _this._keys.push(evt.keyCode);
  7363. }
  7364. if (!noPreventDefault) {
  7365. evt.preventDefault();
  7366. }
  7367. }
  7368. };
  7369. this._onKeyUp = function (evt) {
  7370. 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) {
  7371. var index = _this._keys.indexOf(evt.keyCode);
  7372. if (index >= 0) {
  7373. _this._keys.splice(index, 1);
  7374. }
  7375. if (!noPreventDefault) {
  7376. evt.preventDefault();
  7377. }
  7378. }
  7379. };
  7380. this._onLostFocus = function () {
  7381. _this._keys = [];
  7382. };
  7383. this._reset = function () {
  7384. _this._keys = [];
  7385. previousPosition = null;
  7386. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7387. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7388. };
  7389. }
  7390. element.addEventListener("mousedown", this._onMouseDown, false);
  7391. element.addEventListener("mouseup", this._onMouseUp, false);
  7392. element.addEventListener("mouseout", this._onMouseOut, false);
  7393. element.addEventListener("mousemove", this._onMouseMove, false);
  7394. BABYLON.Tools.RegisterTopRootEvents([
  7395. { name: "keydown", handler: this._onKeyDown },
  7396. { name: "keyup", handler: this._onKeyUp },
  7397. { name: "blur", handler: this._onLostFocus }
  7398. ]);
  7399. };
  7400. FreeCamera.prototype.detachControl = function (element) {
  7401. if (this._attachedElement != element) {
  7402. return;
  7403. }
  7404. element.removeEventListener("mousedown", this._onMouseDown);
  7405. element.removeEventListener("mouseup", this._onMouseUp);
  7406. element.removeEventListener("mouseout", this._onMouseOut);
  7407. element.removeEventListener("mousemove", this._onMouseMove);
  7408. BABYLON.Tools.UnregisterTopRootEvents([
  7409. { name: "keydown", handler: this._onKeyDown },
  7410. { name: "keyup", handler: this._onKeyUp },
  7411. { name: "blur", handler: this._onLostFocus }
  7412. ]);
  7413. this._attachedElement = null;
  7414. if (this._reset) {
  7415. this._reset();
  7416. }
  7417. };
  7418. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7419. var globalPosition;
  7420. if (this.parent) {
  7421. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7422. }
  7423. else {
  7424. globalPosition = this.position;
  7425. }
  7426. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7427. this._collider.radius = this.ellipsoid;
  7428. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7429. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7430. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7431. this.position.addInPlace(this._diffPosition);
  7432. if (this.onCollide) {
  7433. this.onCollide(this._collider.collidedMesh);
  7434. }
  7435. }
  7436. };
  7437. FreeCamera.prototype._checkInputs = function () {
  7438. if (!this._localDirection) {
  7439. this._localDirection = BABYLON.Vector3.Zero();
  7440. this._transformedDirection = BABYLON.Vector3.Zero();
  7441. }
  7442. for (var index = 0; index < this._keys.length; index++) {
  7443. var keyCode = this._keys[index];
  7444. var speed = this._computeLocalCameraSpeed();
  7445. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7446. this._localDirection.copyFromFloats(-speed, 0, 0);
  7447. }
  7448. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7449. this._localDirection.copyFromFloats(0, 0, speed);
  7450. }
  7451. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7452. this._localDirection.copyFromFloats(speed, 0, 0);
  7453. }
  7454. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7455. this._localDirection.copyFromFloats(0, 0, -speed);
  7456. }
  7457. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7458. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7459. this.cameraDirection.addInPlace(this._transformedDirection);
  7460. }
  7461. };
  7462. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7463. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7464. };
  7465. FreeCamera.prototype._updatePosition = function () {
  7466. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7467. this._collideWithWorld(this.cameraDirection);
  7468. if (this.applyGravity) {
  7469. var oldPosition = this.position;
  7470. this._collideWithWorld(this.getScene().gravity);
  7471. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7472. }
  7473. }
  7474. else {
  7475. this.position.addInPlace(this.cameraDirection);
  7476. }
  7477. };
  7478. FreeCamera.prototype._update = function () {
  7479. this._checkInputs();
  7480. _super.prototype._update.call(this);
  7481. };
  7482. return FreeCamera;
  7483. })(BABYLON.TargetCamera);
  7484. BABYLON.FreeCamera = FreeCamera;
  7485. })(BABYLON || (BABYLON = {}));
  7486. //# sourceMappingURL=babylon.freeCamera.js.map
  7487. var BABYLON;
  7488. (function (BABYLON) {
  7489. // We're mainly based on the logic defined into the FreeCamera code
  7490. var TouchCamera = (function (_super) {
  7491. __extends(TouchCamera, _super);
  7492. function TouchCamera(name, position, scene) {
  7493. _super.call(this, name, position, scene);
  7494. this._offsetX = null;
  7495. this._offsetY = null;
  7496. this._pointerCount = 0;
  7497. this._pointerPressed = [];
  7498. this.angularSensibility = 200000.0;
  7499. this.moveSensibility = 500.0;
  7500. }
  7501. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7502. var _this = this;
  7503. var previousPosition;
  7504. if (this._attachedCanvas) {
  7505. return;
  7506. }
  7507. this._attachedCanvas = canvas;
  7508. if (this._onPointerDown === undefined) {
  7509. this._onPointerDown = function (evt) {
  7510. if (!noPreventDefault) {
  7511. evt.preventDefault();
  7512. }
  7513. _this._pointerPressed.push(evt.pointerId);
  7514. if (_this._pointerPressed.length !== 1) {
  7515. return;
  7516. }
  7517. previousPosition = {
  7518. x: evt.clientX,
  7519. y: evt.clientY
  7520. };
  7521. };
  7522. this._onPointerUp = function (evt) {
  7523. if (!noPreventDefault) {
  7524. evt.preventDefault();
  7525. }
  7526. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7527. if (index === -1) {
  7528. return;
  7529. }
  7530. _this._pointerPressed.splice(index, 1);
  7531. if (index != 0) {
  7532. return;
  7533. }
  7534. previousPosition = null;
  7535. _this._offsetX = null;
  7536. _this._offsetY = null;
  7537. };
  7538. this._onPointerMove = function (evt) {
  7539. if (!noPreventDefault) {
  7540. evt.preventDefault();
  7541. }
  7542. if (!previousPosition) {
  7543. return;
  7544. }
  7545. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7546. if (index != 0) {
  7547. return;
  7548. }
  7549. _this._offsetX = evt.clientX - previousPosition.x;
  7550. _this._offsetY = -(evt.clientY - previousPosition.y);
  7551. };
  7552. this._onLostFocus = function () {
  7553. _this._offsetX = null;
  7554. _this._offsetY = null;
  7555. };
  7556. }
  7557. canvas.addEventListener("pointerdown", this._onPointerDown);
  7558. canvas.addEventListener("pointerup", this._onPointerUp);
  7559. canvas.addEventListener("pointerout", this._onPointerUp);
  7560. canvas.addEventListener("pointermove", this._onPointerMove);
  7561. BABYLON.Tools.RegisterTopRootEvents([
  7562. { name: "blur", handler: this._onLostFocus }
  7563. ]);
  7564. };
  7565. TouchCamera.prototype.detachControl = function (canvas) {
  7566. if (this._attachedCanvas != canvas) {
  7567. return;
  7568. }
  7569. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7570. canvas.removeEventListener("pointerup", this._onPointerUp);
  7571. canvas.removeEventListener("pointerout", this._onPointerUp);
  7572. canvas.removeEventListener("pointermove", this._onPointerMove);
  7573. BABYLON.Tools.UnregisterTopRootEvents([
  7574. { name: "blur", handler: this._onLostFocus }
  7575. ]);
  7576. this._attachedCanvas = null;
  7577. };
  7578. TouchCamera.prototype._checkInputs = function () {
  7579. if (!this._offsetX) {
  7580. return;
  7581. }
  7582. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7583. if (this._pointerPressed.length > 1) {
  7584. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7585. }
  7586. else {
  7587. var speed = this._computeLocalCameraSpeed();
  7588. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7589. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7590. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7591. }
  7592. };
  7593. return TouchCamera;
  7594. })(BABYLON.FreeCamera);
  7595. BABYLON.TouchCamera = TouchCamera;
  7596. })(BABYLON || (BABYLON = {}));
  7597. //# sourceMappingURL=babylon.touchCamera.js.map
  7598. var BABYLON;
  7599. (function (BABYLON) {
  7600. // We're mainly based on the logic defined into the FreeCamera code
  7601. var DeviceOrientationCamera = (function (_super) {
  7602. __extends(DeviceOrientationCamera, _super);
  7603. function DeviceOrientationCamera(name, position, scene) {
  7604. var _this = this;
  7605. _super.call(this, name, position, scene);
  7606. this._offsetX = null;
  7607. this._offsetY = null;
  7608. this._orientationGamma = 0;
  7609. this._orientationBeta = 0;
  7610. this._initialOrientationGamma = 0;
  7611. this._initialOrientationBeta = 0;
  7612. this.angularSensibility = 10000.0;
  7613. this.moveSensibility = 50.0;
  7614. window.addEventListener("resize", function () {
  7615. _this._initialOrientationGamma = null;
  7616. }, false);
  7617. }
  7618. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7619. var _this = this;
  7620. if (this._attachedCanvas) {
  7621. return;
  7622. }
  7623. this._attachedCanvas = canvas;
  7624. if (!this._orientationChanged) {
  7625. this._orientationChanged = function (evt) {
  7626. if (!_this._initialOrientationGamma) {
  7627. _this._initialOrientationGamma = evt.gamma;
  7628. _this._initialOrientationBeta = evt.beta;
  7629. }
  7630. _this._orientationGamma = evt.gamma;
  7631. _this._orientationBeta = evt.beta;
  7632. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7633. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7634. };
  7635. }
  7636. window.addEventListener("deviceorientation", this._orientationChanged);
  7637. };
  7638. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7639. if (this._attachedCanvas != canvas) {
  7640. return;
  7641. }
  7642. window.removeEventListener("deviceorientation", this._orientationChanged);
  7643. this._attachedCanvas = null;
  7644. this._orientationGamma = 0;
  7645. this._orientationBeta = 0;
  7646. this._initialOrientationGamma = 0;
  7647. this._initialOrientationBeta = 0;
  7648. };
  7649. DeviceOrientationCamera.prototype._checkInputs = function () {
  7650. if (!this._offsetX) {
  7651. return;
  7652. }
  7653. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7654. var speed = this._computeLocalCameraSpeed();
  7655. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7656. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7657. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7658. };
  7659. return DeviceOrientationCamera;
  7660. })(BABYLON.FreeCamera);
  7661. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7662. })(BABYLON || (BABYLON = {}));
  7663. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7664. var BABYLON;
  7665. (function (BABYLON) {
  7666. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7667. var ArcRotateCamera = (function (_super) {
  7668. __extends(ArcRotateCamera, _super);
  7669. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7670. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7671. this.alpha = alpha;
  7672. this.beta = beta;
  7673. this.radius = radius;
  7674. this.target = target;
  7675. this.inertialAlphaOffset = 0;
  7676. this.inertialBetaOffset = 0;
  7677. this.inertialRadiusOffset = 0;
  7678. this.lowerAlphaLimit = null;
  7679. this.upperAlphaLimit = null;
  7680. this.lowerBetaLimit = 0.01;
  7681. this.upperBetaLimit = Math.PI;
  7682. this.lowerRadiusLimit = null;
  7683. this.upperRadiusLimit = null;
  7684. this.angularSensibility = 1000.0;
  7685. this.wheelPrecision = 3.0;
  7686. this.pinchPrecision = 2.0;
  7687. this.keysUp = [38];
  7688. this.keysDown = [40];
  7689. this.keysLeft = [37];
  7690. this.keysRight = [39];
  7691. this.zoomOnFactor = 1;
  7692. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7693. this._keys = [];
  7694. this._viewMatrix = new BABYLON.Matrix();
  7695. this.checkCollisions = false;
  7696. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7697. this._collider = new BABYLON.Collider();
  7698. this._previousPosition = BABYLON.Vector3.Zero();
  7699. this._collisionVelocity = BABYLON.Vector3.Zero();
  7700. this._newPosition = BABYLON.Vector3.Zero();
  7701. if (!this.target) {
  7702. this.target = BABYLON.Vector3.Zero();
  7703. }
  7704. this.getViewMatrix();
  7705. }
  7706. ArcRotateCamera.prototype._getTargetPosition = function () {
  7707. return this.target.position || this.target;
  7708. };
  7709. // Cache
  7710. ArcRotateCamera.prototype._initCache = function () {
  7711. _super.prototype._initCache.call(this);
  7712. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7713. this._cache.alpha = undefined;
  7714. this._cache.beta = undefined;
  7715. this._cache.radius = undefined;
  7716. this._cache.targetScreenOffset = undefined;
  7717. };
  7718. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7719. if (!ignoreParentClass) {
  7720. _super.prototype._updateCache.call(this);
  7721. }
  7722. this._cache.target.copyFrom(this._getTargetPosition());
  7723. this._cache.alpha = this.alpha;
  7724. this._cache.beta = this.beta;
  7725. this._cache.radius = this.radius;
  7726. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7727. };
  7728. // Synchronized
  7729. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7730. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7731. return false;
  7732. 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);
  7733. };
  7734. // Methods
  7735. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7736. var _this = this;
  7737. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7738. var previousPinchDistance = 0;
  7739. var pointers = new BABYLON.SmartCollection();
  7740. if (this._attachedElement) {
  7741. return;
  7742. }
  7743. this._attachedElement = element;
  7744. var engine = this.getEngine();
  7745. if (this._onPointerDown === undefined) {
  7746. this._onPointerDown = function (evt) {
  7747. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7748. cacheSoloPointer = pointers.item(evt.pointerId);
  7749. if (!noPreventDefault) {
  7750. evt.preventDefault();
  7751. }
  7752. };
  7753. this._onPointerUp = function (evt) {
  7754. cacheSoloPointer = null;
  7755. previousPinchDistance = 0;
  7756. pointers.remove(evt.pointerId);
  7757. if (!noPreventDefault) {
  7758. evt.preventDefault();
  7759. }
  7760. };
  7761. this._onPointerMove = function (evt) {
  7762. if (!noPreventDefault) {
  7763. evt.preventDefault();
  7764. }
  7765. switch (pointers.count) {
  7766. case 1:
  7767. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7768. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7769. var offsetX = evt.clientX - cacheSoloPointer.x;
  7770. var offsetY = evt.clientY - cacheSoloPointer.y;
  7771. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7772. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7773. //pointers.item(evt.pointerId).x = evt.clientX;
  7774. //pointers.item(evt.pointerId).y = evt.clientY;
  7775. cacheSoloPointer.x = evt.clientX;
  7776. cacheSoloPointer.y = evt.clientY;
  7777. break;
  7778. case 2:
  7779. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7780. pointers.item(evt.pointerId).x = evt.clientX;
  7781. pointers.item(evt.pointerId).y = evt.clientY;
  7782. var direction = 1;
  7783. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7784. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7785. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7786. if (previousPinchDistance === 0) {
  7787. previousPinchDistance = pinchSquaredDistance;
  7788. return;
  7789. }
  7790. if (pinchSquaredDistance !== previousPinchDistance) {
  7791. if (pinchSquaredDistance > previousPinchDistance) {
  7792. direction = -1;
  7793. }
  7794. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7795. previousPinchDistance = pinchSquaredDistance;
  7796. }
  7797. break;
  7798. default:
  7799. if (pointers.item(evt.pointerId)) {
  7800. pointers.item(evt.pointerId).x = evt.clientX;
  7801. pointers.item(evt.pointerId).y = evt.clientY;
  7802. }
  7803. }
  7804. };
  7805. this._onMouseMove = function (evt) {
  7806. if (!engine.isPointerLock) {
  7807. return;
  7808. }
  7809. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7810. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7811. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7812. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7813. if (!noPreventDefault) {
  7814. evt.preventDefault();
  7815. }
  7816. };
  7817. this._wheel = function (event) {
  7818. var delta = 0;
  7819. if (event.wheelDelta) {
  7820. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7821. }
  7822. else if (event.detail) {
  7823. delta = -event.detail / _this.wheelPrecision;
  7824. }
  7825. if (delta)
  7826. _this.inertialRadiusOffset += delta;
  7827. if (event.preventDefault) {
  7828. if (!noPreventDefault) {
  7829. event.preventDefault();
  7830. }
  7831. }
  7832. };
  7833. this._onKeyDown = function (evt) {
  7834. 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) {
  7835. var index = _this._keys.indexOf(evt.keyCode);
  7836. if (index === -1) {
  7837. _this._keys.push(evt.keyCode);
  7838. }
  7839. if (evt.preventDefault) {
  7840. if (!noPreventDefault) {
  7841. evt.preventDefault();
  7842. }
  7843. }
  7844. }
  7845. };
  7846. this._onKeyUp = function (evt) {
  7847. 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) {
  7848. var index = _this._keys.indexOf(evt.keyCode);
  7849. if (index >= 0) {
  7850. _this._keys.splice(index, 1);
  7851. }
  7852. if (evt.preventDefault) {
  7853. if (!noPreventDefault) {
  7854. evt.preventDefault();
  7855. }
  7856. }
  7857. }
  7858. };
  7859. this._onLostFocus = function () {
  7860. _this._keys = [];
  7861. pointers.empty();
  7862. previousPinchDistance = 0;
  7863. cacheSoloPointer = null;
  7864. };
  7865. this._onGestureStart = function (e) {
  7866. if (window.MSGesture === undefined) {
  7867. return;
  7868. }
  7869. if (!_this._MSGestureHandler) {
  7870. _this._MSGestureHandler = new MSGesture();
  7871. _this._MSGestureHandler.target = element;
  7872. }
  7873. _this._MSGestureHandler.addPointer(e.pointerId);
  7874. };
  7875. this._onGesture = function (e) {
  7876. _this.radius *= e.scale;
  7877. if (e.preventDefault) {
  7878. if (!noPreventDefault) {
  7879. e.stopPropagation();
  7880. e.preventDefault();
  7881. }
  7882. }
  7883. };
  7884. this._reset = function () {
  7885. _this._keys = [];
  7886. _this.inertialAlphaOffset = 0;
  7887. _this.inertialBetaOffset = 0;
  7888. _this.inertialRadiusOffset = 0;
  7889. pointers.empty();
  7890. previousPinchDistance = 0;
  7891. cacheSoloPointer = null;
  7892. };
  7893. }
  7894. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7895. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7896. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7897. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7898. element.addEventListener("mousemove", this._onMouseMove, false);
  7899. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7900. element.addEventListener("MSGestureChange", this._onGesture, false);
  7901. element.addEventListener('mousewheel', this._wheel, false);
  7902. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7903. BABYLON.Tools.RegisterTopRootEvents([
  7904. { name: "keydown", handler: this._onKeyDown },
  7905. { name: "keyup", handler: this._onKeyUp },
  7906. { name: "blur", handler: this._onLostFocus }
  7907. ]);
  7908. };
  7909. ArcRotateCamera.prototype.detachControl = function (element) {
  7910. if (this._attachedElement !== element) {
  7911. return;
  7912. }
  7913. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7914. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7915. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7916. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7917. element.removeEventListener("mousemove", this._onMouseMove);
  7918. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7919. element.removeEventListener("MSGestureChange", this._onGesture);
  7920. element.removeEventListener('mousewheel', this._wheel);
  7921. element.removeEventListener('DOMMouseScroll', this._wheel);
  7922. BABYLON.Tools.UnregisterTopRootEvents([
  7923. { name: "keydown", handler: this._onKeyDown },
  7924. { name: "keyup", handler: this._onKeyUp },
  7925. { name: "blur", handler: this._onLostFocus }
  7926. ]);
  7927. this._MSGestureHandler = null;
  7928. this._attachedElement = null;
  7929. if (this._reset) {
  7930. this._reset();
  7931. }
  7932. };
  7933. ArcRotateCamera.prototype._update = function () {
  7934. for (var index = 0; index < this._keys.length; index++) {
  7935. var keyCode = this._keys[index];
  7936. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7937. this.inertialAlphaOffset -= 0.01;
  7938. }
  7939. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7940. this.inertialBetaOffset -= 0.01;
  7941. }
  7942. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7943. this.inertialAlphaOffset += 0.01;
  7944. }
  7945. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7946. this.inertialBetaOffset += 0.01;
  7947. }
  7948. }
  7949. // Inertia
  7950. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  7951. this.alpha += this.inertialAlphaOffset;
  7952. this.beta += this.inertialBetaOffset;
  7953. this.radius -= this.inertialRadiusOffset;
  7954. this.inertialAlphaOffset *= this.inertia;
  7955. this.inertialBetaOffset *= this.inertia;
  7956. this.inertialRadiusOffset *= this.inertia;
  7957. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7958. this.inertialAlphaOffset = 0;
  7959. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7960. this.inertialBetaOffset = 0;
  7961. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7962. this.inertialRadiusOffset = 0;
  7963. }
  7964. // Limits
  7965. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7966. this.alpha = this.lowerAlphaLimit;
  7967. }
  7968. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7969. this.alpha = this.upperAlphaLimit;
  7970. }
  7971. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7972. this.beta = this.lowerBetaLimit;
  7973. }
  7974. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7975. this.beta = this.upperBetaLimit;
  7976. }
  7977. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7978. this.radius = this.lowerRadiusLimit;
  7979. }
  7980. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7981. this.radius = this.upperRadiusLimit;
  7982. }
  7983. };
  7984. ArcRotateCamera.prototype.setPosition = function (position) {
  7985. var radiusv3 = position.subtract(this._getTargetPosition());
  7986. this.radius = radiusv3.length();
  7987. // Alpha
  7988. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7989. if (radiusv3.z < 0) {
  7990. this.alpha = 2 * Math.PI - this.alpha;
  7991. }
  7992. // Beta
  7993. this.beta = Math.acos(radiusv3.y / this.radius);
  7994. };
  7995. ArcRotateCamera.prototype._getViewMatrix = function () {
  7996. // Compute
  7997. var cosa = Math.cos(this.alpha);
  7998. var sina = Math.sin(this.alpha);
  7999. var cosb = Math.cos(this.beta);
  8000. var sinb = Math.sin(this.beta);
  8001. var target = this._getTargetPosition();
  8002. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8003. if (this.checkCollisions) {
  8004. this._collider.radius = this.collisionRadius;
  8005. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8006. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8007. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8008. this.position.copyFrom(this._previousPosition);
  8009. this.alpha = this._previousAlpha;
  8010. this.beta = this._previousBeta;
  8011. this.radius = this._previousRadius;
  8012. if (this.onCollide) {
  8013. this.onCollide(this._collider.collidedMesh);
  8014. }
  8015. }
  8016. }
  8017. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8018. this._previousAlpha = this.alpha;
  8019. this._previousBeta = this.beta;
  8020. this._previousRadius = this.radius;
  8021. this._previousPosition.copyFrom(this.position);
  8022. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8023. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8024. return this._viewMatrix;
  8025. };
  8026. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8027. meshes = meshes || this.getScene().meshes;
  8028. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8029. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8030. this.radius = distance * this.zoomOnFactor;
  8031. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8032. };
  8033. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8034. var meshesOrMinMaxVector;
  8035. var distance;
  8036. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8037. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8038. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8039. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8040. }
  8041. else {
  8042. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8043. distance = meshesOrMinMaxVectorAndDistance.distance;
  8044. }
  8045. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8046. this.maxZ = distance * 2;
  8047. };
  8048. return ArcRotateCamera;
  8049. })(BABYLON.Camera);
  8050. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8051. })(BABYLON || (BABYLON = {}));
  8052. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8053. (function (BABYLON) {
  8054. /**
  8055. * Represents a scene to be rendered by the engine.
  8056. * @see http://doc.babylonjs.com/page.php?p=21911
  8057. */
  8058. var Scene = (function () {
  8059. /**
  8060. * @constructor
  8061. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8062. */
  8063. function Scene(engine) {
  8064. // Members
  8065. this.autoClear = true;
  8066. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8067. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8068. this.forceWireframe = false;
  8069. this.forcePointsCloud = false;
  8070. this.forceShowBoundingBoxes = false;
  8071. this.animationsEnabled = true;
  8072. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  8073. // Fog
  8074. /**
  8075. * is fog enabled on this scene.
  8076. * @type {boolean}
  8077. */
  8078. this.fogEnabled = true;
  8079. this.fogMode = Scene.FOGMODE_NONE;
  8080. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8081. this.fogDensity = 0.1;
  8082. this.fogStart = 0;
  8083. this.fogEnd = 1000.0;
  8084. // Lights
  8085. /**
  8086. * is shadow enabled on this scene.
  8087. * @type {boolean}
  8088. */
  8089. this.shadowsEnabled = true;
  8090. /**
  8091. * is light enabled on this scene.
  8092. * @type {boolean}
  8093. */
  8094. this.lightsEnabled = true;
  8095. /**
  8096. * All of the lights added to this scene.
  8097. * @see BABYLON.Light
  8098. * @type {BABYLON.Light[]}
  8099. */
  8100. this.lights = new Array();
  8101. // Cameras
  8102. /**
  8103. * All of the cameras added to this scene.
  8104. * @see BABYLON.Camera
  8105. * @type {BABYLON.Camera[]}
  8106. */
  8107. this.cameras = new Array();
  8108. this.activeCameras = new Array();
  8109. // Meshes
  8110. /**
  8111. * All of the (abstract) meshes added to this scene.
  8112. * @see BABYLON.AbstractMesh
  8113. * @type {BABYLON.AbstractMesh[]}
  8114. */
  8115. this.meshes = new Array();
  8116. // Geometries
  8117. this._geometries = new Array();
  8118. this.materials = new Array();
  8119. this.multiMaterials = new Array();
  8120. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8121. // Textures
  8122. this.texturesEnabled = true;
  8123. this.textures = new Array();
  8124. // Particles
  8125. this.particlesEnabled = true;
  8126. this.particleSystems = new Array();
  8127. // Sprites
  8128. this.spritesEnabled = true;
  8129. this.spriteManagers = new Array();
  8130. // Layers
  8131. this.layers = new Array();
  8132. // Skeletons
  8133. this.skeletonsEnabled = true;
  8134. this.skeletons = new Array();
  8135. // Lens flares
  8136. this.lensFlaresEnabled = true;
  8137. this.lensFlareSystems = new Array();
  8138. // Collisions
  8139. this.collisionsEnabled = true;
  8140. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8141. // Postprocesses
  8142. this.postProcessesEnabled = true;
  8143. // Customs render targets
  8144. this.renderTargetsEnabled = true;
  8145. this.dumpNextRenderTargets = false;
  8146. this.customRenderTargets = new Array();
  8147. // Imported meshes
  8148. this.importedMeshesFiles = new Array();
  8149. this._actionManagers = new Array();
  8150. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8151. // Procedural textures
  8152. this.proceduralTexturesEnabled = true;
  8153. this._proceduralTextures = new Array();
  8154. this.soundTracks = new Array();
  8155. this._audioEnabled = true;
  8156. this._headphone = false;
  8157. this._totalVertices = 0;
  8158. this._activeVertices = 0;
  8159. this._activeParticles = 0;
  8160. this._lastFrameDuration = 0;
  8161. this._evaluateActiveMeshesDuration = 0;
  8162. this._renderTargetsDuration = 0;
  8163. this._particlesDuration = 0;
  8164. this._renderDuration = 0;
  8165. this._spritesDuration = 0;
  8166. this._animationRatio = 0;
  8167. this._renderId = 0;
  8168. this._executeWhenReadyTimeoutId = -1;
  8169. this._toBeDisposed = new BABYLON.SmartArray(256);
  8170. this._onReadyCallbacks = new Array();
  8171. this._pendingData = []; //ANY
  8172. this._onBeforeRenderCallbacks = new Array();
  8173. this._onAfterRenderCallbacks = new Array();
  8174. this._activeMeshes = new BABYLON.SmartArray(256);
  8175. this._processedMaterials = new BABYLON.SmartArray(256);
  8176. this._renderTargets = new BABYLON.SmartArray(256);
  8177. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8178. this._activeSkeletons = new BABYLON.SmartArray(32);
  8179. this._activeBones = 0;
  8180. this._activeAnimatables = new Array();
  8181. this._transformMatrix = BABYLON.Matrix.Zero();
  8182. this._scaledPosition = BABYLON.Vector3.Zero();
  8183. this._scaledVelocity = BABYLON.Vector3.Zero();
  8184. this._engine = engine;
  8185. engine.scenes.push(this);
  8186. this._renderingManager = new BABYLON.RenderingManager(this);
  8187. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8188. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8189. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8190. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8191. this.attachControl();
  8192. this._debugLayer = new BABYLON.DebugLayer(this);
  8193. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8194. //simplification queue
  8195. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8196. }
  8197. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8198. get: function () {
  8199. return Scene._FOGMODE_NONE;
  8200. },
  8201. enumerable: true,
  8202. configurable: true
  8203. });
  8204. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8205. get: function () {
  8206. return Scene._FOGMODE_EXP;
  8207. },
  8208. enumerable: true,
  8209. configurable: true
  8210. });
  8211. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8212. get: function () {
  8213. return Scene._FOGMODE_EXP2;
  8214. },
  8215. enumerable: true,
  8216. configurable: true
  8217. });
  8218. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8219. get: function () {
  8220. return Scene._FOGMODE_LINEAR;
  8221. },
  8222. enumerable: true,
  8223. configurable: true
  8224. });
  8225. Object.defineProperty(Scene.prototype, "debugLayer", {
  8226. // Properties
  8227. get: function () {
  8228. return this._debugLayer;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8234. /**
  8235. * The mesh that is currently under the pointer.
  8236. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8237. */
  8238. get: function () {
  8239. return this._meshUnderPointer;
  8240. },
  8241. enumerable: true,
  8242. configurable: true
  8243. });
  8244. Object.defineProperty(Scene.prototype, "pointerX", {
  8245. /**
  8246. * Current on-screen X position of the pointer
  8247. * @return {number} X position of the pointer
  8248. */
  8249. get: function () {
  8250. return this._pointerX;
  8251. },
  8252. enumerable: true,
  8253. configurable: true
  8254. });
  8255. Object.defineProperty(Scene.prototype, "pointerY", {
  8256. /**
  8257. * Current on-screen Y position of the pointer
  8258. * @return {number} Y position of the pointer
  8259. */
  8260. get: function () {
  8261. return this._pointerY;
  8262. },
  8263. enumerable: true,
  8264. configurable: true
  8265. });
  8266. Scene.prototype.getCachedMaterial = function () {
  8267. return this._cachedMaterial;
  8268. };
  8269. Scene.prototype.getBoundingBoxRenderer = function () {
  8270. return this._boundingBoxRenderer;
  8271. };
  8272. Scene.prototype.getOutlineRenderer = function () {
  8273. return this._outlineRenderer;
  8274. };
  8275. Scene.prototype.getEngine = function () {
  8276. return this._engine;
  8277. };
  8278. Scene.prototype.getTotalVertices = function () {
  8279. return this._totalVertices;
  8280. };
  8281. Scene.prototype.getActiveVertices = function () {
  8282. return this._activeVertices;
  8283. };
  8284. Scene.prototype.getActiveParticles = function () {
  8285. return this._activeParticles;
  8286. };
  8287. Scene.prototype.getActiveBones = function () {
  8288. return this._activeBones;
  8289. };
  8290. // Stats
  8291. Scene.prototype.getLastFrameDuration = function () {
  8292. return this._lastFrameDuration;
  8293. };
  8294. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8295. return this._evaluateActiveMeshesDuration;
  8296. };
  8297. Scene.prototype.getActiveMeshes = function () {
  8298. return this._activeMeshes;
  8299. };
  8300. Scene.prototype.getRenderTargetsDuration = function () {
  8301. return this._renderTargetsDuration;
  8302. };
  8303. Scene.prototype.getRenderDuration = function () {
  8304. return this._renderDuration;
  8305. };
  8306. Scene.prototype.getParticlesDuration = function () {
  8307. return this._particlesDuration;
  8308. };
  8309. Scene.prototype.getSpritesDuration = function () {
  8310. return this._spritesDuration;
  8311. };
  8312. Scene.prototype.getAnimationRatio = function () {
  8313. return this._animationRatio;
  8314. };
  8315. Scene.prototype.getRenderId = function () {
  8316. return this._renderId;
  8317. };
  8318. Scene.prototype.incrementRenderId = function () {
  8319. this._renderId++;
  8320. };
  8321. Scene.prototype._updatePointerPosition = function (evt) {
  8322. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8323. this._pointerX = evt.clientX - canvasRect.left;
  8324. this._pointerY = evt.clientY - canvasRect.top;
  8325. if (this.cameraToUseForPointers) {
  8326. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8327. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8328. }
  8329. };
  8330. // Pointers handling
  8331. Scene.prototype.attachControl = function () {
  8332. var _this = this;
  8333. this._onPointerMove = function (evt) {
  8334. var canvas = _this._engine.getRenderingCanvas();
  8335. _this._updatePointerPosition(evt);
  8336. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  8337. if (pickResult.hit) {
  8338. _this._meshUnderPointer = pickResult.pickedMesh;
  8339. _this.setPointerOverMesh(pickResult.pickedMesh);
  8340. canvas.style.cursor = "pointer";
  8341. }
  8342. else {
  8343. _this.setPointerOverMesh(null);
  8344. canvas.style.cursor = "";
  8345. _this._meshUnderPointer = null;
  8346. }
  8347. };
  8348. this._onPointerDown = function (evt) {
  8349. var predicate = null;
  8350. if (!_this.onPointerDown) {
  8351. predicate = function (mesh) {
  8352. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8353. };
  8354. }
  8355. _this._updatePointerPosition(evt);
  8356. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8357. if (pickResult.hit) {
  8358. if (pickResult.pickedMesh.actionManager) {
  8359. switch (evt.button) {
  8360. case 0:
  8361. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8362. break;
  8363. case 1:
  8364. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8365. break;
  8366. case 2:
  8367. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8368. break;
  8369. }
  8370. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8371. }
  8372. }
  8373. if (_this.onPointerDown) {
  8374. _this.onPointerDown(evt, pickResult);
  8375. }
  8376. };
  8377. this._onKeyDown = function (evt) {
  8378. if (_this.actionManager) {
  8379. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8380. }
  8381. };
  8382. this._onKeyUp = function (evt) {
  8383. if (_this.actionManager) {
  8384. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8385. }
  8386. };
  8387. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8388. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8389. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8390. BABYLON.Tools.RegisterTopRootEvents([
  8391. { name: "keydown", handler: this._onKeyDown },
  8392. { name: "keyup", handler: this._onKeyUp }
  8393. ]);
  8394. };
  8395. Scene.prototype.detachControl = function () {
  8396. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8397. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8398. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8399. BABYLON.Tools.UnregisterTopRootEvents([
  8400. { name: "keydown", handler: this._onKeyDown },
  8401. { name: "keyup", handler: this._onKeyUp }
  8402. ]);
  8403. };
  8404. // Ready
  8405. Scene.prototype.isReady = function () {
  8406. if (this._pendingData.length > 0) {
  8407. return false;
  8408. }
  8409. for (var index = 0; index < this._geometries.length; index++) {
  8410. var geometry = this._geometries[index];
  8411. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8412. return false;
  8413. }
  8414. }
  8415. for (index = 0; index < this.meshes.length; index++) {
  8416. var mesh = this.meshes[index];
  8417. if (!mesh.isReady()) {
  8418. return false;
  8419. }
  8420. var mat = mesh.material;
  8421. if (mat) {
  8422. if (!mat.isReady(mesh)) {
  8423. return false;
  8424. }
  8425. }
  8426. }
  8427. return true;
  8428. };
  8429. Scene.prototype.resetCachedMaterial = function () {
  8430. this._cachedMaterial = null;
  8431. };
  8432. Scene.prototype.registerBeforeRender = function (func) {
  8433. this._onBeforeRenderCallbacks.push(func);
  8434. };
  8435. Scene.prototype.unregisterBeforeRender = function (func) {
  8436. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8437. if (index > -1) {
  8438. this._onBeforeRenderCallbacks.splice(index, 1);
  8439. }
  8440. };
  8441. Scene.prototype.registerAfterRender = function (func) {
  8442. this._onAfterRenderCallbacks.push(func);
  8443. };
  8444. Scene.prototype.unregisterAfterRender = function (func) {
  8445. var index = this._onAfterRenderCallbacks.indexOf(func);
  8446. if (index > -1) {
  8447. this._onAfterRenderCallbacks.splice(index, 1);
  8448. }
  8449. };
  8450. Scene.prototype._addPendingData = function (data) {
  8451. this._pendingData.push(data);
  8452. };
  8453. Scene.prototype._removePendingData = function (data) {
  8454. var index = this._pendingData.indexOf(data);
  8455. if (index !== -1) {
  8456. this._pendingData.splice(index, 1);
  8457. }
  8458. };
  8459. Scene.prototype.getWaitingItemsCount = function () {
  8460. return this._pendingData.length;
  8461. };
  8462. /**
  8463. * Registers a function to be executed when the scene is ready.
  8464. * @param {Function} func - the function to be executed.
  8465. */
  8466. Scene.prototype.executeWhenReady = function (func) {
  8467. var _this = this;
  8468. this._onReadyCallbacks.push(func);
  8469. if (this._executeWhenReadyTimeoutId !== -1) {
  8470. return;
  8471. }
  8472. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8473. _this._checkIsReady();
  8474. }, 150);
  8475. };
  8476. Scene.prototype._checkIsReady = function () {
  8477. var _this = this;
  8478. if (this.isReady()) {
  8479. this._onReadyCallbacks.forEach(function (func) {
  8480. func();
  8481. });
  8482. this._onReadyCallbacks = [];
  8483. this._executeWhenReadyTimeoutId = -1;
  8484. return;
  8485. }
  8486. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8487. _this._checkIsReady();
  8488. }, 150);
  8489. };
  8490. // Animations
  8491. /**
  8492. * Will start the animation sequence of a given target
  8493. * @param target - the target
  8494. * @param {number} from - from which frame should animation start
  8495. * @param {number} to - till which frame should animation run.
  8496. * @param {boolean} [loop] - should the animation loop
  8497. * @param {number} [speedRatio] - the speed in which to run the animation
  8498. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8499. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8500. * @return {BABYLON.Animatable} the animatable object created for this animation
  8501. * @see BABYLON.Animatable
  8502. * @see http://doc.babylonjs.com/page.php?p=22081
  8503. */
  8504. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8505. if (speedRatio === undefined) {
  8506. speedRatio = 1.0;
  8507. }
  8508. this.stopAnimation(target);
  8509. if (!animatable) {
  8510. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8511. }
  8512. // Local animations
  8513. if (target.animations) {
  8514. animatable.appendAnimations(target, target.animations);
  8515. }
  8516. // Children animations
  8517. if (target.getAnimatables) {
  8518. var animatables = target.getAnimatables();
  8519. for (var index = 0; index < animatables.length; index++) {
  8520. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8521. }
  8522. }
  8523. return animatable;
  8524. };
  8525. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8526. if (speedRatio === undefined) {
  8527. speedRatio = 1.0;
  8528. }
  8529. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8530. return animatable;
  8531. };
  8532. Scene.prototype.getAnimatableByTarget = function (target) {
  8533. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8534. if (this._activeAnimatables[index].target === target) {
  8535. return this._activeAnimatables[index];
  8536. }
  8537. }
  8538. return null;
  8539. };
  8540. /**
  8541. * Will stop the animation of the given target
  8542. * @param target - the target
  8543. * @see beginAnimation
  8544. */
  8545. Scene.prototype.stopAnimation = function (target) {
  8546. var animatable = this.getAnimatableByTarget(target);
  8547. if (animatable) {
  8548. animatable.stop();
  8549. }
  8550. };
  8551. Scene.prototype._animate = function () {
  8552. if (!this.animationsEnabled) {
  8553. return;
  8554. }
  8555. if (!this._animationStartDate) {
  8556. this._animationStartDate = BABYLON.Tools.Now;
  8557. }
  8558. // Getting time
  8559. var now = BABYLON.Tools.Now;
  8560. var delay = now - this._animationStartDate;
  8561. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8562. this._activeAnimatables[index]._animate(delay);
  8563. }
  8564. };
  8565. // Matrix
  8566. Scene.prototype.getViewMatrix = function () {
  8567. return this._viewMatrix;
  8568. };
  8569. Scene.prototype.getProjectionMatrix = function () {
  8570. return this._projectionMatrix;
  8571. };
  8572. Scene.prototype.getTransformMatrix = function () {
  8573. return this._transformMatrix;
  8574. };
  8575. Scene.prototype.setTransformMatrix = function (view, projection) {
  8576. this._viewMatrix = view;
  8577. this._projectionMatrix = projection;
  8578. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8579. };
  8580. // Methods
  8581. Scene.prototype.addMesh = function (newMesh) {
  8582. var position = this.meshes.push(newMesh);
  8583. if (this.onNewMeshAdded) {
  8584. this.onNewMeshAdded(newMesh, position, this);
  8585. }
  8586. };
  8587. Scene.prototype.removeMesh = function (toRemove) {
  8588. var index = this.meshes.indexOf(toRemove);
  8589. if (index !== -1) {
  8590. // Remove from the scene if mesh found
  8591. this.meshes.splice(index, 1);
  8592. }
  8593. if (this.onMeshRemoved) {
  8594. this.onMeshRemoved(toRemove);
  8595. }
  8596. return index;
  8597. };
  8598. Scene.prototype.removeLight = function (toRemove) {
  8599. var index = this.lights.indexOf(toRemove);
  8600. if (index !== -1) {
  8601. // Remove from the scene if mesh found
  8602. this.lights.splice(index, 1);
  8603. }
  8604. if (this.onLightRemoved) {
  8605. this.onLightRemoved(toRemove);
  8606. }
  8607. return index;
  8608. };
  8609. Scene.prototype.removeCamera = function (toRemove) {
  8610. var index = this.cameras.indexOf(toRemove);
  8611. if (index !== -1) {
  8612. // Remove from the scene if mesh found
  8613. this.cameras.splice(index, 1);
  8614. }
  8615. if (this.onCameraRemoved) {
  8616. this.onCameraRemoved(toRemove);
  8617. }
  8618. return index;
  8619. };
  8620. Scene.prototype.addLight = function (newLight) {
  8621. var position = this.lights.push(newLight);
  8622. if (this.onNewLightAdded) {
  8623. this.onNewLightAdded(newLight, position, this);
  8624. }
  8625. };
  8626. Scene.prototype.addCamera = function (newCamera) {
  8627. var position = this.cameras.push(newCamera);
  8628. if (this.onNewCameraAdded) {
  8629. this.onNewCameraAdded(newCamera, position, this);
  8630. }
  8631. };
  8632. /**
  8633. * sets the active camera of the scene using its ID
  8634. * @param {string} id - the camera's ID
  8635. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8636. * @see activeCamera
  8637. */
  8638. Scene.prototype.setActiveCameraByID = function (id) {
  8639. var camera = this.getCameraByID(id);
  8640. if (camera) {
  8641. this.activeCamera = camera;
  8642. return camera;
  8643. }
  8644. return null;
  8645. };
  8646. /**
  8647. * sets the active camera of the scene using its name
  8648. * @param {string} name - the camera's name
  8649. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8650. * @see activeCamera
  8651. */
  8652. Scene.prototype.setActiveCameraByName = function (name) {
  8653. var camera = this.getCameraByName(name);
  8654. if (camera) {
  8655. this.activeCamera = camera;
  8656. return camera;
  8657. }
  8658. return null;
  8659. };
  8660. /**
  8661. * get a material using its id
  8662. * @param {string} the material's ID
  8663. * @return {BABYLON.Material|null} the material or null if none found.
  8664. */
  8665. Scene.prototype.getMaterialByID = function (id) {
  8666. for (var index = 0; index < this.materials.length; index++) {
  8667. if (this.materials[index].id === id) {
  8668. return this.materials[index];
  8669. }
  8670. }
  8671. return null;
  8672. };
  8673. /**
  8674. * get a material using its name
  8675. * @param {string} the material's name
  8676. * @return {BABYLON.Material|null} the material or null if none found.
  8677. */
  8678. Scene.prototype.getMaterialByName = function (name) {
  8679. for (var index = 0; index < this.materials.length; index++) {
  8680. if (this.materials[index].name === name) {
  8681. return this.materials[index];
  8682. }
  8683. }
  8684. return null;
  8685. };
  8686. Scene.prototype.getCameraByID = function (id) {
  8687. for (var index = 0; index < this.cameras.length; index++) {
  8688. if (this.cameras[index].id === id) {
  8689. return this.cameras[index];
  8690. }
  8691. }
  8692. return null;
  8693. };
  8694. /**
  8695. * get a camera using its name
  8696. * @param {string} the camera's name
  8697. * @return {BABYLON.Camera|null} the camera or null if none found.
  8698. */
  8699. Scene.prototype.getCameraByName = function (name) {
  8700. for (var index = 0; index < this.cameras.length; index++) {
  8701. if (this.cameras[index].name === name) {
  8702. return this.cameras[index];
  8703. }
  8704. }
  8705. return null;
  8706. };
  8707. /**
  8708. * get a light node using its name
  8709. * @param {string} the light's name
  8710. * @return {BABYLON.Light|null} the light or null if none found.
  8711. */
  8712. Scene.prototype.getLightByName = function (name) {
  8713. for (var index = 0; index < this.lights.length; index++) {
  8714. if (this.lights[index].name === name) {
  8715. return this.lights[index];
  8716. }
  8717. }
  8718. return null;
  8719. };
  8720. /**
  8721. * get a light node using its ID
  8722. * @param {string} the light's id
  8723. * @return {BABYLON.Light|null} the light or null if none found.
  8724. */
  8725. Scene.prototype.getLightByID = function (id) {
  8726. for (var index = 0; index < this.lights.length; index++) {
  8727. if (this.lights[index].id === id) {
  8728. return this.lights[index];
  8729. }
  8730. }
  8731. return null;
  8732. };
  8733. /**
  8734. * get a geometry using its ID
  8735. * @param {string} the geometry's id
  8736. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8737. */
  8738. Scene.prototype.getGeometryByID = function (id) {
  8739. for (var index = 0; index < this._geometries.length; index++) {
  8740. if (this._geometries[index].id === id) {
  8741. return this._geometries[index];
  8742. }
  8743. }
  8744. return null;
  8745. };
  8746. /**
  8747. * add a new geometry to this scene.
  8748. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8749. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8750. * @return {boolean} was the geometry added or not
  8751. */
  8752. Scene.prototype.pushGeometry = function (geometry, force) {
  8753. if (!force && this.getGeometryByID(geometry.id)) {
  8754. return false;
  8755. }
  8756. this._geometries.push(geometry);
  8757. return true;
  8758. };
  8759. Scene.prototype.getGeometries = function () {
  8760. return this._geometries;
  8761. };
  8762. /**
  8763. * Get a the first added mesh found of a given ID
  8764. * @param {string} id - the id to search for
  8765. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8766. */
  8767. Scene.prototype.getMeshByID = function (id) {
  8768. for (var index = 0; index < this.meshes.length; index++) {
  8769. if (this.meshes[index].id === id) {
  8770. return this.meshes[index];
  8771. }
  8772. }
  8773. return null;
  8774. };
  8775. /**
  8776. * Get a the last added mesh found of a given ID
  8777. * @param {string} id - the id to search for
  8778. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8779. */
  8780. Scene.prototype.getLastMeshByID = function (id) {
  8781. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8782. if (this.meshes[index].id === id) {
  8783. return this.meshes[index];
  8784. }
  8785. }
  8786. return null;
  8787. };
  8788. /**
  8789. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8790. * @param {string} id - the id to search for
  8791. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8792. */
  8793. Scene.prototype.getLastEntryByID = function (id) {
  8794. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8795. if (this.meshes[index].id === id) {
  8796. return this.meshes[index];
  8797. }
  8798. }
  8799. for (index = this.cameras.length - 1; index >= 0; index--) {
  8800. if (this.cameras[index].id === id) {
  8801. return this.cameras[index];
  8802. }
  8803. }
  8804. for (index = this.lights.length - 1; index >= 0; index--) {
  8805. if (this.lights[index].id === id) {
  8806. return this.lights[index];
  8807. }
  8808. }
  8809. return null;
  8810. };
  8811. Scene.prototype.getNodeByName = function (name) {
  8812. var mesh = this.getMeshByName(name);
  8813. if (mesh) {
  8814. return mesh;
  8815. }
  8816. var light = this.getLightByName(name);
  8817. if (light) {
  8818. return light;
  8819. }
  8820. return this.getCameraByName(name);
  8821. };
  8822. Scene.prototype.getMeshByName = function (name) {
  8823. for (var index = 0; index < this.meshes.length; index++) {
  8824. if (this.meshes[index].name === name) {
  8825. return this.meshes[index];
  8826. }
  8827. }
  8828. return null;
  8829. };
  8830. Scene.prototype.getSoundByName = function (name) {
  8831. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8832. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8833. return this.mainSoundTrack.soundCollection[index];
  8834. }
  8835. }
  8836. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8837. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8838. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8839. return this.soundTracks[sdIndex].soundCollection[index];
  8840. }
  8841. }
  8842. }
  8843. return null;
  8844. };
  8845. Scene.prototype.getLastSkeletonByID = function (id) {
  8846. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8847. if (this.skeletons[index].id === id) {
  8848. return this.skeletons[index];
  8849. }
  8850. }
  8851. return null;
  8852. };
  8853. Scene.prototype.getSkeletonById = function (id) {
  8854. for (var index = 0; index < this.skeletons.length; index++) {
  8855. if (this.skeletons[index].id === id) {
  8856. return this.skeletons[index];
  8857. }
  8858. }
  8859. return null;
  8860. };
  8861. Scene.prototype.getSkeletonByName = function (name) {
  8862. for (var index = 0; index < this.skeletons.length; index++) {
  8863. if (this.skeletons[index].name === name) {
  8864. return this.skeletons[index];
  8865. }
  8866. }
  8867. return null;
  8868. };
  8869. Scene.prototype.isActiveMesh = function (mesh) {
  8870. return (this._activeMeshes.indexOf(mesh) !== -1);
  8871. };
  8872. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8873. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8874. var material = subMesh.getMaterial();
  8875. if (mesh.showSubMeshesBoundingBox) {
  8876. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8877. }
  8878. if (material) {
  8879. // Render targets
  8880. if (material.getRenderTargetTextures) {
  8881. if (this._processedMaterials.indexOf(material) === -1) {
  8882. this._processedMaterials.push(material);
  8883. this._renderTargets.concat(material.getRenderTargetTextures());
  8884. }
  8885. }
  8886. // Dispatch
  8887. this._activeVertices += subMesh.indexCount;
  8888. this._renderingManager.dispatch(subMesh);
  8889. }
  8890. }
  8891. };
  8892. Scene.prototype._evaluateActiveMeshes = function () {
  8893. this.activeCamera._activeMeshes.reset();
  8894. this._activeMeshes.reset();
  8895. this._renderingManager.reset();
  8896. this._processedMaterials.reset();
  8897. this._activeParticleSystems.reset();
  8898. this._activeSkeletons.reset();
  8899. this._boundingBoxRenderer.reset();
  8900. if (!this._frustumPlanes) {
  8901. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8902. }
  8903. else {
  8904. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8905. }
  8906. // Meshes
  8907. var meshes;
  8908. var len;
  8909. if (this._selectionOctree) {
  8910. var selection = this._selectionOctree.select(this._frustumPlanes);
  8911. meshes = selection.data;
  8912. len = selection.length;
  8913. }
  8914. else {
  8915. len = this.meshes.length;
  8916. meshes = this.meshes;
  8917. }
  8918. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8919. var mesh = meshes[meshIndex];
  8920. if (mesh.isBlocked) {
  8921. continue;
  8922. }
  8923. this._totalVertices += mesh.getTotalVertices();
  8924. if (!mesh.isReady()) {
  8925. continue;
  8926. }
  8927. mesh.computeWorldMatrix();
  8928. // Intersections
  8929. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8930. this._meshesForIntersections.pushNoDuplicate(mesh);
  8931. }
  8932. // Switch to current LOD
  8933. var meshLOD = mesh.getLOD(this.activeCamera);
  8934. if (!meshLOD) {
  8935. continue;
  8936. }
  8937. mesh._preActivate();
  8938. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8939. this._activeMeshes.push(mesh);
  8940. this.activeCamera._activeMeshes.push(mesh);
  8941. mesh._activate(this._renderId);
  8942. this._activeMesh(meshLOD);
  8943. }
  8944. }
  8945. // Particle systems
  8946. var beforeParticlesDate = BABYLON.Tools.Now;
  8947. if (this.particlesEnabled) {
  8948. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8949. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8950. var particleSystem = this.particleSystems[particleIndex];
  8951. if (!particleSystem.isStarted()) {
  8952. continue;
  8953. }
  8954. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8955. this._activeParticleSystems.push(particleSystem);
  8956. particleSystem.animate();
  8957. }
  8958. }
  8959. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8960. }
  8961. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8962. };
  8963. Scene.prototype._activeMesh = function (mesh) {
  8964. if (mesh.skeleton && this.skeletonsEnabled) {
  8965. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8966. }
  8967. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8968. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8969. }
  8970. if (mesh && mesh.subMeshes) {
  8971. // Submeshes Octrees
  8972. var len;
  8973. var subMeshes;
  8974. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8975. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8976. len = intersections.length;
  8977. subMeshes = intersections.data;
  8978. }
  8979. else {
  8980. subMeshes = mesh.subMeshes;
  8981. len = subMeshes.length;
  8982. }
  8983. for (var subIndex = 0; subIndex < len; subIndex++) {
  8984. var subMesh = subMeshes[subIndex];
  8985. this._evaluateSubMesh(subMesh, mesh);
  8986. }
  8987. }
  8988. };
  8989. Scene.prototype.updateTransformMatrix = function (force) {
  8990. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8991. };
  8992. Scene.prototype._renderForCamera = function (camera) {
  8993. var engine = this._engine;
  8994. this.activeCamera = camera;
  8995. if (!this.activeCamera)
  8996. throw new Error("Active camera not set");
  8997. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8998. // Viewport
  8999. engine.setViewport(this.activeCamera.viewport);
  9000. // Camera
  9001. this._renderId++;
  9002. this.updateTransformMatrix();
  9003. if (this.beforeCameraRender) {
  9004. this.beforeCameraRender(this.activeCamera);
  9005. }
  9006. // Meshes
  9007. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9008. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9009. this._evaluateActiveMeshes();
  9010. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9011. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9012. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9013. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9014. skeleton.prepare();
  9015. }
  9016. // Render targets
  9017. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9018. if (this.renderTargetsEnabled) {
  9019. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9020. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9021. var renderTarget = this._renderTargets.data[renderIndex];
  9022. if (renderTarget._shouldRender()) {
  9023. this._renderId++;
  9024. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9025. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9026. }
  9027. }
  9028. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9029. this._renderId++;
  9030. }
  9031. if (this._renderTargets.length > 0) {
  9032. engine.restoreDefaultFramebuffer();
  9033. }
  9034. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9035. // Prepare Frame
  9036. this.postProcessManager._prepareFrame();
  9037. var beforeRenderDate = BABYLON.Tools.Now;
  9038. // Backgrounds
  9039. if (this.layers.length) {
  9040. engine.setDepthBuffer(false);
  9041. var layerIndex;
  9042. var layer;
  9043. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9044. layer = this.layers[layerIndex];
  9045. if (layer.isBackground) {
  9046. layer.render();
  9047. }
  9048. }
  9049. engine.setDepthBuffer(true);
  9050. }
  9051. // Render
  9052. BABYLON.Tools.StartPerformanceCounter("Main render");
  9053. this._renderingManager.render(null, null, true, true);
  9054. BABYLON.Tools.EndPerformanceCounter("Main render");
  9055. // Bounding boxes
  9056. this._boundingBoxRenderer.render();
  9057. // Lens flares
  9058. if (this.lensFlaresEnabled) {
  9059. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9060. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9061. this.lensFlareSystems[lensFlareSystemIndex].render();
  9062. }
  9063. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9064. }
  9065. // Foregrounds
  9066. if (this.layers.length) {
  9067. engine.setDepthBuffer(false);
  9068. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9069. layer = this.layers[layerIndex];
  9070. if (!layer.isBackground) {
  9071. layer.render();
  9072. }
  9073. }
  9074. engine.setDepthBuffer(true);
  9075. }
  9076. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9077. // Finalize frame
  9078. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9079. // Update camera
  9080. this.activeCamera._updateFromScene();
  9081. // Reset some special arrays
  9082. this._renderTargets.reset();
  9083. if (this.afterCameraRender) {
  9084. this.afterCameraRender(this.activeCamera);
  9085. }
  9086. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9087. };
  9088. Scene.prototype._processSubCameras = function (camera) {
  9089. if (camera.subCameras.length === 0) {
  9090. this._renderForCamera(camera);
  9091. return;
  9092. }
  9093. for (var index = 0; index < camera.subCameras.length; index++) {
  9094. this._renderForCamera(camera.subCameras[index]);
  9095. }
  9096. this.activeCamera = camera;
  9097. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9098. // Update camera
  9099. this.activeCamera._updateFromScene();
  9100. };
  9101. Scene.prototype._checkIntersections = function () {
  9102. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9103. var sourceMesh = this._meshesForIntersections.data[index];
  9104. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9105. var action = sourceMesh.actionManager.actions[actionIndex];
  9106. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9107. var parameters = action.getTriggerParameter();
  9108. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9109. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9110. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9111. if (areIntersecting && currentIntersectionInProgress === -1) {
  9112. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9113. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9114. sourceMesh._intersectionsInProgress.push(otherMesh);
  9115. }
  9116. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9117. sourceMesh._intersectionsInProgress.push(otherMesh);
  9118. }
  9119. }
  9120. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9121. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9122. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9123. if (indexOfOther > -1) {
  9124. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9125. }
  9126. }
  9127. }
  9128. }
  9129. }
  9130. };
  9131. Scene.prototype.render = function () {
  9132. var startDate = BABYLON.Tools.Now;
  9133. this._particlesDuration = 0;
  9134. this._spritesDuration = 0;
  9135. this._activeParticles = 0;
  9136. this._renderDuration = 0;
  9137. this._renderTargetsDuration = 0;
  9138. this._evaluateActiveMeshesDuration = 0;
  9139. this._totalVertices = 0;
  9140. this._activeVertices = 0;
  9141. this._activeBones = 0;
  9142. this.getEngine().resetDrawCalls();
  9143. this._meshesForIntersections.reset();
  9144. this.resetCachedMaterial();
  9145. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9146. // Actions
  9147. if (this.actionManager) {
  9148. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9149. }
  9150. //Simplification Queue
  9151. if (!this.simplificationQueue.running) {
  9152. this.simplificationQueue.executeNext();
  9153. }
  9154. // Before render
  9155. if (this.beforeRender) {
  9156. this.beforeRender();
  9157. }
  9158. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9159. this._onBeforeRenderCallbacks[callbackIndex]();
  9160. }
  9161. // Animations
  9162. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9163. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9164. this._animate();
  9165. // Physics
  9166. if (this._physicsEngine) {
  9167. BABYLON.Tools.StartPerformanceCounter("Physics");
  9168. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9169. BABYLON.Tools.EndPerformanceCounter("Physics");
  9170. }
  9171. // Customs render targets
  9172. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9173. var engine = this.getEngine();
  9174. var currentActiveCamera = this.activeCamera;
  9175. if (this.renderTargetsEnabled) {
  9176. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9177. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9178. var renderTarget = this.customRenderTargets[customIndex];
  9179. if (renderTarget._shouldRender()) {
  9180. this._renderId++;
  9181. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9182. if (!this.activeCamera)
  9183. throw new Error("Active camera not set");
  9184. // Viewport
  9185. engine.setViewport(this.activeCamera.viewport);
  9186. // Camera
  9187. this.updateTransformMatrix();
  9188. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9189. }
  9190. }
  9191. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9192. this._renderId++;
  9193. }
  9194. if (this.customRenderTargets.length > 0) {
  9195. engine.restoreDefaultFramebuffer();
  9196. }
  9197. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9198. this.activeCamera = currentActiveCamera;
  9199. // Procedural textures
  9200. if (this.proceduralTexturesEnabled) {
  9201. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9202. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9203. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9204. if (proceduralTexture._shouldRender()) {
  9205. proceduralTexture.render();
  9206. }
  9207. }
  9208. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9209. }
  9210. // Clear
  9211. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9212. // Shadows
  9213. if (this.shadowsEnabled) {
  9214. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9215. var light = this.lights[lightIndex];
  9216. var shadowGenerator = light.getShadowGenerator();
  9217. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9218. this._renderTargets.push(shadowGenerator.getShadowMap());
  9219. }
  9220. }
  9221. }
  9222. // Depth renderer
  9223. if (this._depthRenderer) {
  9224. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9225. }
  9226. // RenderPipeline
  9227. this.postProcessRenderPipelineManager.update();
  9228. // Multi-cameras?
  9229. if (this.activeCameras.length > 0) {
  9230. var currentRenderId = this._renderId;
  9231. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9232. this._renderId = currentRenderId;
  9233. this._processSubCameras(this.activeCameras[cameraIndex]);
  9234. }
  9235. }
  9236. else {
  9237. if (!this.activeCamera) {
  9238. throw new Error("No camera defined");
  9239. }
  9240. this._processSubCameras(this.activeCamera);
  9241. }
  9242. // Intersection checks
  9243. this._checkIntersections();
  9244. // Update the audio listener attached to the camera
  9245. this._updateAudioParameters();
  9246. // After render
  9247. if (this.afterRender) {
  9248. this.afterRender();
  9249. }
  9250. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9251. this._onAfterRenderCallbacks[callbackIndex]();
  9252. }
  9253. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9254. this._toBeDisposed.data[index].dispose();
  9255. this._toBeDisposed[index] = null;
  9256. }
  9257. this._toBeDisposed.reset();
  9258. if (this.dumpNextRenderTargets) {
  9259. this.dumpNextRenderTargets = false;
  9260. }
  9261. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9262. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9263. };
  9264. Scene.prototype._updateAudioParameters = function () {
  9265. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9266. return;
  9267. }
  9268. var listeningCamera;
  9269. var audioEngine = BABYLON.Engine.audioEngine;
  9270. if (this.activeCameras.length > 0) {
  9271. listeningCamera = this.activeCameras[0];
  9272. }
  9273. else {
  9274. listeningCamera = this.activeCamera;
  9275. }
  9276. if (listeningCamera && audioEngine.canUseWebAudio) {
  9277. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9278. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9279. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9280. cameraDirection.normalize();
  9281. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9282. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9283. var sound = this.mainSoundTrack.soundCollection[i];
  9284. if (sound.useCustomAttenuation) {
  9285. sound.updateDistanceFromListener();
  9286. }
  9287. }
  9288. for (i = 0; i < this.soundTracks.length; i++) {
  9289. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9290. sound = this.soundTracks[i].soundCollection[j];
  9291. if (sound.useCustomAttenuation) {
  9292. sound.updateDistanceFromListener();
  9293. }
  9294. }
  9295. }
  9296. }
  9297. };
  9298. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9299. // Audio
  9300. get: function () {
  9301. return this._audioEnabled;
  9302. },
  9303. set: function (value) {
  9304. this._audioEnabled = value;
  9305. if (this._audioEnabled) {
  9306. this._enableAudio();
  9307. }
  9308. else {
  9309. this._disableAudio();
  9310. }
  9311. },
  9312. enumerable: true,
  9313. configurable: true
  9314. });
  9315. Scene.prototype._disableAudio = function () {
  9316. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9317. this.mainSoundTrack.soundCollection[i].pause();
  9318. }
  9319. for (i = 0; i < this.soundTracks.length; i++) {
  9320. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9321. this.soundTracks[i].soundCollection[j].pause();
  9322. }
  9323. }
  9324. };
  9325. Scene.prototype._enableAudio = function () {
  9326. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9327. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9328. this.mainSoundTrack.soundCollection[i].play();
  9329. }
  9330. }
  9331. for (i = 0; i < this.soundTracks.length; i++) {
  9332. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9333. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9334. this.soundTracks[i].soundCollection[j].play();
  9335. }
  9336. }
  9337. }
  9338. };
  9339. Object.defineProperty(Scene.prototype, "headphone", {
  9340. get: function () {
  9341. return this._headphone;
  9342. },
  9343. set: function (value) {
  9344. this._headphone = value;
  9345. if (this._headphone) {
  9346. this._switchAudioModeForHeadphones();
  9347. }
  9348. else {
  9349. this._switchAudioModeForNormalSpeakers();
  9350. }
  9351. },
  9352. enumerable: true,
  9353. configurable: true
  9354. });
  9355. Scene.prototype._switchAudioModeForHeadphones = function () {
  9356. this.mainSoundTrack.switchPanningModelToHRTF();
  9357. for (var i = 0; i < this.soundTracks.length; i++) {
  9358. this.soundTracks[i].switchPanningModelToHRTF();
  9359. }
  9360. };
  9361. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9362. this.mainSoundTrack.switchPanningModelToEqualPower();
  9363. for (var i = 0; i < this.soundTracks.length; i++) {
  9364. this.soundTracks[i].switchPanningModelToEqualPower();
  9365. }
  9366. };
  9367. Scene.prototype.enableDepthRenderer = function () {
  9368. if (this._depthRenderer) {
  9369. return this._depthRenderer;
  9370. }
  9371. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9372. return this._depthRenderer;
  9373. };
  9374. Scene.prototype.disableDepthRenderer = function () {
  9375. if (!this._depthRenderer) {
  9376. return;
  9377. }
  9378. this._depthRenderer.dispose();
  9379. this._depthRenderer = null;
  9380. };
  9381. Scene.prototype.dispose = function () {
  9382. this.beforeRender = null;
  9383. this.afterRender = null;
  9384. this.skeletons = [];
  9385. this._boundingBoxRenderer.dispose();
  9386. if (this._depthRenderer) {
  9387. this._depthRenderer.dispose();
  9388. }
  9389. // Debug layer
  9390. this.debugLayer.hide();
  9391. // Events
  9392. if (this.onDispose) {
  9393. this.onDispose();
  9394. }
  9395. this._onBeforeRenderCallbacks = [];
  9396. this._onAfterRenderCallbacks = [];
  9397. this.detachControl();
  9398. // Release sounds & sounds tracks
  9399. this.disposeSounds();
  9400. // Detach cameras
  9401. var canvas = this._engine.getRenderingCanvas();
  9402. var index;
  9403. for (index = 0; index < this.cameras.length; index++) {
  9404. this.cameras[index].detachControl(canvas);
  9405. }
  9406. while (this.lights.length) {
  9407. this.lights[0].dispose();
  9408. }
  9409. while (this.meshes.length) {
  9410. this.meshes[0].dispose(true);
  9411. }
  9412. while (this.cameras.length) {
  9413. this.cameras[0].dispose();
  9414. }
  9415. while (this.materials.length) {
  9416. this.materials[0].dispose();
  9417. }
  9418. while (this.particleSystems.length) {
  9419. this.particleSystems[0].dispose();
  9420. }
  9421. while (this.spriteManagers.length) {
  9422. this.spriteManagers[0].dispose();
  9423. }
  9424. while (this.layers.length) {
  9425. this.layers[0].dispose();
  9426. }
  9427. while (this.textures.length) {
  9428. this.textures[0].dispose();
  9429. }
  9430. // Post-processes
  9431. this.postProcessManager.dispose();
  9432. // Physics
  9433. if (this._physicsEngine) {
  9434. this.disablePhysicsEngine();
  9435. }
  9436. // Remove from engine
  9437. index = this._engine.scenes.indexOf(this);
  9438. if (index > -1) {
  9439. this._engine.scenes.splice(index, 1);
  9440. }
  9441. this._engine.wipeCaches();
  9442. };
  9443. // Release sounds & sounds tracks
  9444. Scene.prototype.disposeSounds = function () {
  9445. this.mainSoundTrack.dispose();
  9446. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9447. this.soundTracks[scIndex].dispose();
  9448. }
  9449. };
  9450. // Collisions
  9451. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9452. if (excludedMesh === void 0) { excludedMesh = null; }
  9453. position.divideToRef(collider.radius, this._scaledPosition);
  9454. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9455. collider.retry = 0;
  9456. collider.initialVelocity = this._scaledVelocity;
  9457. collider.initialPosition = this._scaledPosition;
  9458. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9459. finalPosition.multiplyInPlace(collider.radius);
  9460. };
  9461. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9462. if (excludedMesh === void 0) { excludedMesh = null; }
  9463. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9464. if (collider.retry >= maximumRetry) {
  9465. finalPosition.copyFrom(position);
  9466. return;
  9467. }
  9468. collider._initialize(position, velocity, closeDistance);
  9469. for (var index = 0; index < this.meshes.length; index++) {
  9470. var mesh = this.meshes[index];
  9471. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9472. mesh._checkCollision(collider);
  9473. }
  9474. }
  9475. if (!collider.collisionFound) {
  9476. position.addToRef(velocity, finalPosition);
  9477. return;
  9478. }
  9479. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9480. collider._getResponse(position, velocity);
  9481. }
  9482. if (velocity.length() <= closeDistance) {
  9483. finalPosition.copyFrom(position);
  9484. return;
  9485. }
  9486. collider.retry++;
  9487. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9488. };
  9489. // Octrees
  9490. Scene.prototype.getWorldExtends = function () {
  9491. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9492. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9493. for (var index = 0; index < this.meshes.length; index++) {
  9494. var mesh = this.meshes[index];
  9495. mesh.computeWorldMatrix(true);
  9496. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9497. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9498. BABYLON.Tools.CheckExtends(minBox, min, max);
  9499. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9500. }
  9501. return {
  9502. min: min,
  9503. max: max
  9504. };
  9505. };
  9506. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9507. if (maxCapacity === void 0) { maxCapacity = 64; }
  9508. if (maxDepth === void 0) { maxDepth = 2; }
  9509. if (!this._selectionOctree) {
  9510. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9511. }
  9512. var worldExtends = this.getWorldExtends();
  9513. // Update octree
  9514. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9515. return this._selectionOctree;
  9516. };
  9517. // Picking
  9518. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9519. var engine = this._engine;
  9520. if (!camera) {
  9521. if (!this.activeCamera)
  9522. throw new Error("Active camera not set");
  9523. camera = this.activeCamera;
  9524. }
  9525. var cameraViewport = camera.viewport;
  9526. var viewport = cameraViewport.toGlobal(engine);
  9527. // Moving coordinates to local viewport world
  9528. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9529. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9530. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9531. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9532. };
  9533. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9534. var pickingInfo = null;
  9535. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9536. var mesh = this.meshes[meshIndex];
  9537. if (predicate) {
  9538. if (!predicate(mesh)) {
  9539. continue;
  9540. }
  9541. }
  9542. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9543. continue;
  9544. }
  9545. var world = mesh.getWorldMatrix();
  9546. var ray = rayFunction(world);
  9547. var result = mesh.intersects(ray, fastCheck);
  9548. if (!result || !result.hit)
  9549. continue;
  9550. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9551. continue;
  9552. pickingInfo = result;
  9553. if (fastCheck) {
  9554. break;
  9555. }
  9556. }
  9557. return pickingInfo || new BABYLON.PickingInfo();
  9558. };
  9559. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9560. var _this = this;
  9561. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9562. /// <param name="x">X position on screen</param>
  9563. /// <param name="y">Y position on screen</param>
  9564. /// <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>
  9565. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9566. /// <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>
  9567. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9568. };
  9569. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9570. var _this = this;
  9571. return this._internalPick(function (world) {
  9572. if (!_this._pickWithRayInverseMatrix) {
  9573. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9574. }
  9575. world.invertToRef(_this._pickWithRayInverseMatrix);
  9576. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9577. }, predicate, fastCheck);
  9578. };
  9579. Scene.prototype.setPointerOverMesh = function (mesh) {
  9580. if (this._pointerOverMesh === mesh) {
  9581. return;
  9582. }
  9583. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9584. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9585. }
  9586. this._pointerOverMesh = mesh;
  9587. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9588. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9589. }
  9590. };
  9591. Scene.prototype.getPointerOverMesh = function () {
  9592. return this._pointerOverMesh;
  9593. };
  9594. // Physics
  9595. Scene.prototype.getPhysicsEngine = function () {
  9596. return this._physicsEngine;
  9597. };
  9598. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9599. if (this._physicsEngine) {
  9600. return true;
  9601. }
  9602. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9603. if (!this._physicsEngine.isSupported()) {
  9604. this._physicsEngine = null;
  9605. return false;
  9606. }
  9607. this._physicsEngine._initialize(gravity);
  9608. return true;
  9609. };
  9610. Scene.prototype.disablePhysicsEngine = function () {
  9611. if (!this._physicsEngine) {
  9612. return;
  9613. }
  9614. this._physicsEngine.dispose();
  9615. this._physicsEngine = undefined;
  9616. };
  9617. Scene.prototype.isPhysicsEnabled = function () {
  9618. return this._physicsEngine !== undefined;
  9619. };
  9620. Scene.prototype.setGravity = function (gravity) {
  9621. if (!this._physicsEngine) {
  9622. return;
  9623. }
  9624. this._physicsEngine._setGravity(gravity);
  9625. };
  9626. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9627. if (parts.parts) {
  9628. options = parts;
  9629. parts = parts.parts;
  9630. }
  9631. if (!this._physicsEngine) {
  9632. return null;
  9633. }
  9634. for (var index = 0; index < parts.length; index++) {
  9635. var mesh = parts[index].mesh;
  9636. mesh._physicImpostor = parts[index].impostor;
  9637. mesh._physicsMass = options.mass / parts.length;
  9638. mesh._physicsFriction = options.friction;
  9639. mesh._physicRestitution = options.restitution;
  9640. }
  9641. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9642. };
  9643. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9644. for (var index = 0; index < compound.parts.length; index++) {
  9645. var mesh = compound.parts[index].mesh;
  9646. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9647. this._physicsEngine._unregisterMesh(mesh);
  9648. }
  9649. };
  9650. // Misc.
  9651. Scene.prototype.createDefaultCameraOrLight = function () {
  9652. // Light
  9653. if (this.lights.length === 0) {
  9654. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9655. }
  9656. // Camera
  9657. if (!this.activeCamera) {
  9658. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9659. // Compute position
  9660. var worldExtends = this.getWorldExtends();
  9661. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9662. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9663. camera.setTarget(worldCenter);
  9664. this.activeCamera = camera;
  9665. }
  9666. };
  9667. // Tags
  9668. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9669. if (tagsQuery === undefined) {
  9670. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9671. return list;
  9672. }
  9673. var listByTags = [];
  9674. forEach = forEach || (function (item) {
  9675. return;
  9676. });
  9677. for (var i in list) {
  9678. var item = list[i];
  9679. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9680. listByTags.push(item);
  9681. forEach(item);
  9682. }
  9683. }
  9684. return listByTags;
  9685. };
  9686. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9687. return this._getByTags(this.meshes, tagsQuery, forEach);
  9688. };
  9689. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9690. return this._getByTags(this.cameras, tagsQuery, forEach);
  9691. };
  9692. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9693. return this._getByTags(this.lights, tagsQuery, forEach);
  9694. };
  9695. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9696. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9697. };
  9698. // Statics
  9699. Scene._FOGMODE_NONE = 0;
  9700. Scene._FOGMODE_EXP = 1;
  9701. Scene._FOGMODE_EXP2 = 2;
  9702. Scene._FOGMODE_LINEAR = 3;
  9703. Scene.MinDeltaTime = 1.0;
  9704. Scene.MaxDeltaTime = 1000.0;
  9705. return Scene;
  9706. })();
  9707. BABYLON.Scene = Scene;
  9708. })(BABYLON || (BABYLON = {}));
  9709. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9710. (function (BABYLON) {
  9711. var VertexBuffer = (function () {
  9712. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9713. if (engine instanceof BABYLON.Mesh) {
  9714. this._engine = engine.getScene().getEngine();
  9715. }
  9716. else {
  9717. this._engine = engine;
  9718. }
  9719. this._updatable = updatable;
  9720. this._data = data;
  9721. if (!postponeInternalCreation) {
  9722. this.create();
  9723. }
  9724. this._kind = kind;
  9725. if (stride) {
  9726. this._strideSize = stride;
  9727. return;
  9728. }
  9729. switch (kind) {
  9730. case VertexBuffer.PositionKind:
  9731. this._strideSize = 3;
  9732. break;
  9733. case VertexBuffer.NormalKind:
  9734. this._strideSize = 3;
  9735. break;
  9736. case VertexBuffer.UVKind:
  9737. this._strideSize = 2;
  9738. break;
  9739. case VertexBuffer.UV2Kind:
  9740. this._strideSize = 2;
  9741. break;
  9742. case VertexBuffer.ColorKind:
  9743. this._strideSize = 4;
  9744. break;
  9745. case VertexBuffer.MatricesIndicesKind:
  9746. this._strideSize = 4;
  9747. break;
  9748. case VertexBuffer.MatricesWeightsKind:
  9749. this._strideSize = 4;
  9750. break;
  9751. }
  9752. }
  9753. // Properties
  9754. VertexBuffer.prototype.isUpdatable = function () {
  9755. return this._updatable;
  9756. };
  9757. VertexBuffer.prototype.getData = function () {
  9758. return this._data;
  9759. };
  9760. VertexBuffer.prototype.getBuffer = function () {
  9761. return this._buffer;
  9762. };
  9763. VertexBuffer.prototype.getStrideSize = function () {
  9764. return this._strideSize;
  9765. };
  9766. // Methods
  9767. VertexBuffer.prototype.create = function (data) {
  9768. if (!data && this._buffer) {
  9769. return; // nothing to do
  9770. }
  9771. data = data || this._data;
  9772. if (!this._buffer) {
  9773. if (this._updatable) {
  9774. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9775. }
  9776. else {
  9777. this._buffer = this._engine.createVertexBuffer(data);
  9778. }
  9779. }
  9780. if (this._updatable) {
  9781. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9782. this._data = data;
  9783. }
  9784. };
  9785. VertexBuffer.prototype.update = function (data) {
  9786. this.create(data);
  9787. };
  9788. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9789. if (!this._buffer) {
  9790. return;
  9791. }
  9792. if (this._updatable) {
  9793. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9794. this._data = null;
  9795. }
  9796. };
  9797. VertexBuffer.prototype.dispose = function () {
  9798. if (!this._buffer) {
  9799. return;
  9800. }
  9801. if (this._engine._releaseBuffer(this._buffer)) {
  9802. this._buffer = null;
  9803. }
  9804. };
  9805. Object.defineProperty(VertexBuffer, "PositionKind", {
  9806. get: function () {
  9807. return VertexBuffer._PositionKind;
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. Object.defineProperty(VertexBuffer, "NormalKind", {
  9813. get: function () {
  9814. return VertexBuffer._NormalKind;
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. Object.defineProperty(VertexBuffer, "UVKind", {
  9820. get: function () {
  9821. return VertexBuffer._UVKind;
  9822. },
  9823. enumerable: true,
  9824. configurable: true
  9825. });
  9826. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9827. get: function () {
  9828. return VertexBuffer._UV2Kind;
  9829. },
  9830. enumerable: true,
  9831. configurable: true
  9832. });
  9833. Object.defineProperty(VertexBuffer, "ColorKind", {
  9834. get: function () {
  9835. return VertexBuffer._ColorKind;
  9836. },
  9837. enumerable: true,
  9838. configurable: true
  9839. });
  9840. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9841. get: function () {
  9842. return VertexBuffer._MatricesIndicesKind;
  9843. },
  9844. enumerable: true,
  9845. configurable: true
  9846. });
  9847. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9848. get: function () {
  9849. return VertexBuffer._MatricesWeightsKind;
  9850. },
  9851. enumerable: true,
  9852. configurable: true
  9853. });
  9854. // Enums
  9855. VertexBuffer._PositionKind = "position";
  9856. VertexBuffer._NormalKind = "normal";
  9857. VertexBuffer._UVKind = "uv";
  9858. VertexBuffer._UV2Kind = "uv2";
  9859. VertexBuffer._ColorKind = "color";
  9860. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9861. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9862. return VertexBuffer;
  9863. })();
  9864. BABYLON.VertexBuffer = VertexBuffer;
  9865. })(BABYLON || (BABYLON = {}));
  9866. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9867. var BABYLON;
  9868. (function (BABYLON) {
  9869. var AbstractMesh = (function (_super) {
  9870. __extends(AbstractMesh, _super);
  9871. function AbstractMesh(name, scene) {
  9872. _super.call(this, name, scene);
  9873. // Properties
  9874. this.definedFacingForward = true; // orientation for POV movement & rotation
  9875. this.position = new BABYLON.Vector3(0, 0, 0);
  9876. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9877. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9878. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9879. this.visibility = 1.0;
  9880. this.alphaIndex = Number.MAX_VALUE;
  9881. this.infiniteDistance = false;
  9882. this.isVisible = true;
  9883. this.isPickable = true;
  9884. this.showBoundingBox = false;
  9885. this.showSubMeshesBoundingBox = false;
  9886. this.onDispose = null;
  9887. this.checkCollisions = false;
  9888. this.isBlocker = false;
  9889. this.renderingGroupId = 0;
  9890. this.receiveShadows = false;
  9891. this.renderOutline = false;
  9892. this.outlineColor = BABYLON.Color3.Red();
  9893. this.outlineWidth = 0.02;
  9894. this.renderOverlay = false;
  9895. this.overlayColor = BABYLON.Color3.Red();
  9896. this.overlayAlpha = 0.5;
  9897. this.hasVertexAlpha = false;
  9898. this.useVertexColors = true;
  9899. this.applyFog = true;
  9900. this.useOctreeForRenderingSelection = true;
  9901. this.useOctreeForPicking = true;
  9902. this.useOctreeForCollisions = true;
  9903. this.layerMask = 0x0FFFFFFF;
  9904. // Physics
  9905. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9906. // Collisions
  9907. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9908. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9909. this._collider = new BABYLON.Collider();
  9910. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9911. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9912. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9913. // Cache
  9914. this._localScaling = BABYLON.Matrix.Zero();
  9915. this._localRotation = BABYLON.Matrix.Zero();
  9916. this._localTranslation = BABYLON.Matrix.Zero();
  9917. this._localBillboard = BABYLON.Matrix.Zero();
  9918. this._localPivotScaling = BABYLON.Matrix.Zero();
  9919. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9920. this._localWorld = BABYLON.Matrix.Zero();
  9921. this._worldMatrix = BABYLON.Matrix.Zero();
  9922. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9923. this._absolutePosition = BABYLON.Vector3.Zero();
  9924. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9925. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9926. this._isDirty = false;
  9927. this._pivotMatrix = BABYLON.Matrix.Identity();
  9928. this._isDisposed = false;
  9929. this._renderId = 0;
  9930. this._intersectionsInProgress = new Array();
  9931. this._onAfterWorldMatrixUpdate = new Array();
  9932. scene.addMesh(this);
  9933. }
  9934. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9935. get: function () {
  9936. return AbstractMesh._BILLBOARDMODE_NONE;
  9937. },
  9938. enumerable: true,
  9939. configurable: true
  9940. });
  9941. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9942. get: function () {
  9943. return AbstractMesh._BILLBOARDMODE_X;
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9949. get: function () {
  9950. return AbstractMesh._BILLBOARDMODE_Y;
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9956. get: function () {
  9957. return AbstractMesh._BILLBOARDMODE_Z;
  9958. },
  9959. enumerable: true,
  9960. configurable: true
  9961. });
  9962. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9963. get: function () {
  9964. return AbstractMesh._BILLBOARDMODE_ALL;
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9970. // Methods
  9971. get: function () {
  9972. return false;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. AbstractMesh.prototype.getLOD = function (camera) {
  9978. return this;
  9979. };
  9980. AbstractMesh.prototype.getTotalVertices = function () {
  9981. return 0;
  9982. };
  9983. AbstractMesh.prototype.getIndices = function () {
  9984. return null;
  9985. };
  9986. AbstractMesh.prototype.getVerticesData = function (kind) {
  9987. return null;
  9988. };
  9989. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9990. return false;
  9991. };
  9992. AbstractMesh.prototype.getBoundingInfo = function () {
  9993. if (this._masterMesh) {
  9994. return this._masterMesh.getBoundingInfo();
  9995. }
  9996. if (!this._boundingInfo) {
  9997. this._updateBoundingInfo();
  9998. }
  9999. return this._boundingInfo;
  10000. };
  10001. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10002. get: function () {
  10003. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10004. },
  10005. enumerable: true,
  10006. configurable: true
  10007. });
  10008. AbstractMesh.prototype._preActivate = function () {
  10009. };
  10010. AbstractMesh.prototype._activate = function (renderId) {
  10011. this._renderId = renderId;
  10012. };
  10013. AbstractMesh.prototype.getWorldMatrix = function () {
  10014. if (this._masterMesh) {
  10015. return this._masterMesh.getWorldMatrix();
  10016. }
  10017. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10018. this.computeWorldMatrix();
  10019. }
  10020. return this._worldMatrix;
  10021. };
  10022. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10023. get: function () {
  10024. return this._worldMatrix;
  10025. },
  10026. enumerable: true,
  10027. configurable: true
  10028. });
  10029. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10030. get: function () {
  10031. return this._absolutePosition;
  10032. },
  10033. enumerable: true,
  10034. configurable: true
  10035. });
  10036. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10037. if (!this.rotationQuaternion) {
  10038. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10039. this.rotation = BABYLON.Vector3.Zero();
  10040. }
  10041. if (!space || space === 0 /* LOCAL */) {
  10042. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10043. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10044. }
  10045. else {
  10046. if (this.parent) {
  10047. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10048. invertParentWorldMatrix.invert();
  10049. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10050. }
  10051. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10052. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10053. }
  10054. };
  10055. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10056. var displacementVector = axis.scale(distance);
  10057. if (!space || space === 0 /* LOCAL */) {
  10058. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10059. this.setPositionWithLocalVector(tempV3);
  10060. }
  10061. else {
  10062. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10063. }
  10064. };
  10065. AbstractMesh.prototype.getAbsolutePosition = function () {
  10066. this.computeWorldMatrix();
  10067. return this._absolutePosition;
  10068. };
  10069. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10070. if (!absolutePosition) {
  10071. return;
  10072. }
  10073. var absolutePositionX;
  10074. var absolutePositionY;
  10075. var absolutePositionZ;
  10076. if (absolutePosition.x === undefined) {
  10077. if (arguments.length < 3) {
  10078. return;
  10079. }
  10080. absolutePositionX = arguments[0];
  10081. absolutePositionY = arguments[1];
  10082. absolutePositionZ = arguments[2];
  10083. }
  10084. else {
  10085. absolutePositionX = absolutePosition.x;
  10086. absolutePositionY = absolutePosition.y;
  10087. absolutePositionZ = absolutePosition.z;
  10088. }
  10089. if (this.parent) {
  10090. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10091. invertParentWorldMatrix.invert();
  10092. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10093. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10094. }
  10095. else {
  10096. this.position.x = absolutePositionX;
  10097. this.position.y = absolutePositionY;
  10098. this.position.z = absolutePositionZ;
  10099. }
  10100. };
  10101. // ================================== Point of View Movement =================================
  10102. /**
  10103. * Perform relative position change from the point of view of behind the front of the mesh.
  10104. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10105. * Supports definition of mesh facing forward or backward.
  10106. * @param {number} amountRight
  10107. * @param {number} amountUp
  10108. * @param {number} amountForward
  10109. */
  10110. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10111. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10112. };
  10113. /**
  10114. * Calculate relative position change from the point of view of behind the front of the mesh.
  10115. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10116. * Supports definition of mesh facing forward or backward.
  10117. * @param {number} amountRight
  10118. * @param {number} amountUp
  10119. * @param {number} amountForward
  10120. */
  10121. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10122. var rotMatrix = new BABYLON.Matrix();
  10123. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10124. rotQuaternion.toRotationMatrix(rotMatrix);
  10125. var translationDelta = BABYLON.Vector3.Zero();
  10126. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10127. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10128. return translationDelta;
  10129. };
  10130. // ================================== Point of View Rotation =================================
  10131. /**
  10132. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10133. * Supports definition of mesh facing forward or backward.
  10134. * @param {number} flipBack
  10135. * @param {number} twirlClockwise
  10136. * @param {number} tiltRight
  10137. */
  10138. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10139. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10140. };
  10141. /**
  10142. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10143. * Supports definition of mesh facing forward or backward.
  10144. * @param {number} flipBack
  10145. * @param {number} twirlClockwise
  10146. * @param {number} tiltRight
  10147. */
  10148. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10149. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10150. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10151. };
  10152. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10153. this._pivotMatrix = matrix;
  10154. this._cache.pivotMatrixUpdated = true;
  10155. };
  10156. AbstractMesh.prototype.getPivotMatrix = function () {
  10157. return this._pivotMatrix;
  10158. };
  10159. AbstractMesh.prototype._isSynchronized = function () {
  10160. if (this._isDirty) {
  10161. return false;
  10162. }
  10163. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10164. return false;
  10165. if (this._cache.pivotMatrixUpdated) {
  10166. return false;
  10167. }
  10168. if (this.infiniteDistance) {
  10169. return false;
  10170. }
  10171. if (!this._cache.position.equals(this.position))
  10172. return false;
  10173. if (this.rotationQuaternion) {
  10174. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10175. return false;
  10176. }
  10177. else {
  10178. if (!this._cache.rotation.equals(this.rotation))
  10179. return false;
  10180. }
  10181. if (!this._cache.scaling.equals(this.scaling))
  10182. return false;
  10183. return true;
  10184. };
  10185. AbstractMesh.prototype._initCache = function () {
  10186. _super.prototype._initCache.call(this);
  10187. this._cache.localMatrixUpdated = false;
  10188. this._cache.position = BABYLON.Vector3.Zero();
  10189. this._cache.scaling = BABYLON.Vector3.Zero();
  10190. this._cache.rotation = BABYLON.Vector3.Zero();
  10191. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10192. };
  10193. AbstractMesh.prototype.markAsDirty = function (property) {
  10194. if (property === "rotation") {
  10195. this.rotationQuaternion = null;
  10196. }
  10197. this._currentRenderId = Number.MAX_VALUE;
  10198. this._isDirty = true;
  10199. };
  10200. AbstractMesh.prototype._updateBoundingInfo = function () {
  10201. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10202. this._boundingInfo._update(this.worldMatrixFromCache);
  10203. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10204. };
  10205. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10206. if (!this.subMeshes) {
  10207. return;
  10208. }
  10209. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10210. var subMesh = this.subMeshes[subIndex];
  10211. subMesh.updateBoundingInfo(matrix);
  10212. }
  10213. };
  10214. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10215. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10216. return this._worldMatrix;
  10217. }
  10218. this._cache.position.copyFrom(this.position);
  10219. this._cache.scaling.copyFrom(this.scaling);
  10220. this._cache.pivotMatrixUpdated = false;
  10221. this._currentRenderId = this.getScene().getRenderId();
  10222. this._isDirty = false;
  10223. // Scaling
  10224. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10225. // Rotation
  10226. if (this.rotationQuaternion) {
  10227. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10228. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10229. }
  10230. else {
  10231. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10232. this._cache.rotation.copyFrom(this.rotation);
  10233. }
  10234. // Translation
  10235. if (this.infiniteDistance && !this.parent) {
  10236. var camera = this.getScene().activeCamera;
  10237. var cameraWorldMatrix = camera.getWorldMatrix();
  10238. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10239. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10240. }
  10241. else {
  10242. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10243. }
  10244. // Composing transformations
  10245. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10246. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10247. // Billboarding
  10248. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10249. var localPosition = this.position.clone();
  10250. var zero = this.getScene().activeCamera.position.clone();
  10251. if (this.parent && this.parent.position) {
  10252. localPosition.addInPlace(this.parent.position);
  10253. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10254. }
  10255. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10256. zero = this.getScene().activeCamera.position;
  10257. }
  10258. else {
  10259. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10260. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10261. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10262. zero.y = localPosition.y + 0.001;
  10263. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10264. zero.z = localPosition.z + 0.001;
  10265. }
  10266. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10267. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10268. this._localBillboard.invert();
  10269. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10270. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10271. }
  10272. // Local world
  10273. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10274. // Parent
  10275. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10276. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10277. }
  10278. else {
  10279. this._worldMatrix.copyFrom(this._localWorld);
  10280. }
  10281. // Bounding info
  10282. this._updateBoundingInfo();
  10283. // Absolute position
  10284. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10285. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10286. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10287. }
  10288. return this._worldMatrix;
  10289. };
  10290. /**
  10291. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10292. * @param func: callback function to add
  10293. */
  10294. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10295. this._onAfterWorldMatrixUpdate.push(func);
  10296. };
  10297. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10298. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10299. if (index > -1) {
  10300. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10301. }
  10302. };
  10303. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10304. this.computeWorldMatrix();
  10305. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10306. };
  10307. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10308. this.computeWorldMatrix();
  10309. var invLocalWorldMatrix = this._localWorld.clone();
  10310. invLocalWorldMatrix.invert();
  10311. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10312. };
  10313. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10314. this.computeWorldMatrix();
  10315. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10316. };
  10317. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10318. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10319. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10320. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10321. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10322. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10323. /// <returns>Mesh oriented towards targetMesh</returns>
  10324. yawCor = yawCor || 0; // default to zero if undefined
  10325. pitchCor = pitchCor || 0;
  10326. rollCor = rollCor || 0;
  10327. var dv = targetPoint.subtract(this.position);
  10328. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10329. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10330. var pitch = Math.atan2(dv.y, len);
  10331. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10332. };
  10333. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10334. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10335. return false;
  10336. }
  10337. return true;
  10338. };
  10339. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10340. if (!camera) {
  10341. camera = this.getScene().activeCamera;
  10342. }
  10343. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10344. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10345. return false;
  10346. }
  10347. return true;
  10348. };
  10349. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10350. if (!this._boundingInfo || !mesh._boundingInfo) {
  10351. return false;
  10352. }
  10353. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10354. };
  10355. AbstractMesh.prototype.intersectsPoint = function (point) {
  10356. if (!this._boundingInfo) {
  10357. return false;
  10358. }
  10359. return this._boundingInfo.intersectsPoint(point);
  10360. };
  10361. // Physics
  10362. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10363. var physicsEngine = this.getScene().getPhysicsEngine();
  10364. if (!physicsEngine) {
  10365. return;
  10366. }
  10367. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10368. if (impostor.impostor) {
  10369. // Old API
  10370. options = impostor;
  10371. impostor = impostor.impostor;
  10372. }
  10373. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10374. physicsEngine._unregisterMesh(this);
  10375. return;
  10376. }
  10377. if (!options) {
  10378. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10379. }
  10380. else {
  10381. if (!options.mass && options.mass !== 0)
  10382. options.mass = 0;
  10383. if (!options.friction && options.friction !== 0)
  10384. options.friction = 0.2;
  10385. if (!options.restitution && options.restitution !== 0)
  10386. options.restitution = 0.2;
  10387. }
  10388. this._physicImpostor = impostor;
  10389. this._physicsMass = options.mass;
  10390. this._physicsFriction = options.friction;
  10391. this._physicRestitution = options.restitution;
  10392. return physicsEngine._registerMesh(this, impostor, options);
  10393. };
  10394. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10395. if (!this._physicImpostor) {
  10396. return BABYLON.PhysicsEngine.NoImpostor;
  10397. }
  10398. return this._physicImpostor;
  10399. };
  10400. AbstractMesh.prototype.getPhysicsMass = function () {
  10401. if (!this._physicsMass) {
  10402. return 0;
  10403. }
  10404. return this._physicsMass;
  10405. };
  10406. AbstractMesh.prototype.getPhysicsFriction = function () {
  10407. if (!this._physicsFriction) {
  10408. return 0;
  10409. }
  10410. return this._physicsFriction;
  10411. };
  10412. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10413. if (!this._physicRestitution) {
  10414. return 0;
  10415. }
  10416. return this._physicRestitution;
  10417. };
  10418. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10419. if (!camera) {
  10420. camera = this.getScene().activeCamera;
  10421. }
  10422. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10423. };
  10424. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10425. if (!camera) {
  10426. camera = this.getScene().activeCamera;
  10427. }
  10428. return this.absolutePosition.subtract(camera.position).length();
  10429. };
  10430. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10431. if (!this._physicImpostor) {
  10432. return;
  10433. }
  10434. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10435. };
  10436. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10437. if (!this._physicImpostor) {
  10438. return;
  10439. }
  10440. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10441. };
  10442. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10443. if (!this._physicImpostor) {
  10444. return;
  10445. }
  10446. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10447. };
  10448. // Collisions
  10449. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10450. var globalPosition = this.getAbsolutePosition();
  10451. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10452. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10453. this._collider.radius = this.ellipsoid;
  10454. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10455. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10456. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10457. this.position.addInPlace(this._diffPositionForCollisions);
  10458. }
  10459. };
  10460. // Submeshes octree
  10461. /**
  10462. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10463. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10464. */
  10465. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10466. if (maxCapacity === void 0) { maxCapacity = 64; }
  10467. if (maxDepth === void 0) { maxDepth = 2; }
  10468. if (!this._submeshesOctree) {
  10469. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10470. }
  10471. this.computeWorldMatrix(true);
  10472. // Update octree
  10473. var bbox = this.getBoundingInfo().boundingBox;
  10474. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10475. return this._submeshesOctree;
  10476. };
  10477. // Collisions
  10478. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10479. this._generatePointsArray();
  10480. // Transformation
  10481. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10482. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10483. subMesh._lastColliderWorldVertices = [];
  10484. subMesh._trianglePlanes = [];
  10485. var start = subMesh.verticesStart;
  10486. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10487. for (var i = start; i < end; i++) {
  10488. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10489. }
  10490. }
  10491. // Collide
  10492. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10493. };
  10494. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10495. var subMeshes;
  10496. var len;
  10497. // Octrees
  10498. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10499. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10500. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10501. len = intersections.length;
  10502. subMeshes = intersections.data;
  10503. }
  10504. else {
  10505. subMeshes = this.subMeshes;
  10506. len = subMeshes.length;
  10507. }
  10508. for (var index = 0; index < len; index++) {
  10509. var subMesh = subMeshes[index];
  10510. // Bounding test
  10511. if (len > 1 && !subMesh._checkCollision(collider))
  10512. continue;
  10513. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10514. }
  10515. };
  10516. AbstractMesh.prototype._checkCollision = function (collider) {
  10517. // Bounding box test
  10518. if (!this._boundingInfo._checkCollision(collider))
  10519. return;
  10520. // Transformation matrix
  10521. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10522. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10523. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10524. };
  10525. // Picking
  10526. AbstractMesh.prototype._generatePointsArray = function () {
  10527. return false;
  10528. };
  10529. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10530. var pickingInfo = new BABYLON.PickingInfo();
  10531. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10532. return pickingInfo;
  10533. }
  10534. if (!this._generatePointsArray()) {
  10535. return pickingInfo;
  10536. }
  10537. var intersectInfo = null;
  10538. // Octrees
  10539. var subMeshes;
  10540. var len;
  10541. if (this._submeshesOctree && this.useOctreeForPicking) {
  10542. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10543. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10544. len = intersections.length;
  10545. subMeshes = intersections.data;
  10546. }
  10547. else {
  10548. subMeshes = this.subMeshes;
  10549. len = subMeshes.length;
  10550. }
  10551. for (var index = 0; index < len; index++) {
  10552. var subMesh = subMeshes[index];
  10553. // Bounding test
  10554. if (len > 1 && !subMesh.canIntersects(ray))
  10555. continue;
  10556. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10557. if (currentIntersectInfo) {
  10558. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10559. intersectInfo = currentIntersectInfo;
  10560. intersectInfo.subMeshId = index;
  10561. if (fastCheck) {
  10562. break;
  10563. }
  10564. }
  10565. }
  10566. }
  10567. if (intersectInfo) {
  10568. // Get picked point
  10569. var world = this.getWorldMatrix();
  10570. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10571. var direction = ray.direction.clone();
  10572. direction = direction.scale(intersectInfo.distance);
  10573. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10574. var pickedPoint = worldOrigin.add(worldDirection);
  10575. // Return result
  10576. pickingInfo.hit = true;
  10577. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10578. pickingInfo.pickedPoint = pickedPoint;
  10579. pickingInfo.pickedMesh = this;
  10580. pickingInfo.bu = intersectInfo.bu;
  10581. pickingInfo.bv = intersectInfo.bv;
  10582. pickingInfo.faceId = intersectInfo.faceId;
  10583. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10584. return pickingInfo;
  10585. }
  10586. return pickingInfo;
  10587. };
  10588. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10589. return null;
  10590. };
  10591. AbstractMesh.prototype.releaseSubMeshes = function () {
  10592. if (this.subMeshes) {
  10593. while (this.subMeshes.length) {
  10594. this.subMeshes[0].dispose();
  10595. }
  10596. }
  10597. else {
  10598. this.subMeshes = new Array();
  10599. }
  10600. };
  10601. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10602. var index;
  10603. // Physics
  10604. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10605. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10606. }
  10607. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10608. var other = this._intersectionsInProgress[index];
  10609. var pos = other._intersectionsInProgress.indexOf(this);
  10610. other._intersectionsInProgress.splice(pos, 1);
  10611. }
  10612. this._intersectionsInProgress = [];
  10613. // SubMeshes
  10614. this.releaseSubMeshes();
  10615. // Remove from scene
  10616. this.getScene().removeMesh(this);
  10617. if (!doNotRecurse) {
  10618. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10619. if (this.getScene().particleSystems[index].emitter === this) {
  10620. this.getScene().particleSystems[index].dispose();
  10621. index--;
  10622. }
  10623. }
  10624. // Children
  10625. var objects = this.getScene().meshes.slice(0);
  10626. for (index = 0; index < objects.length; index++) {
  10627. if (objects[index].parent === this) {
  10628. objects[index].dispose();
  10629. }
  10630. }
  10631. }
  10632. else {
  10633. for (index = 0; index < this.getScene().meshes.length; index++) {
  10634. var obj = this.getScene().meshes[index];
  10635. if (obj.parent === this) {
  10636. obj.parent = null;
  10637. obj.computeWorldMatrix(true);
  10638. }
  10639. }
  10640. }
  10641. this._onAfterWorldMatrixUpdate = [];
  10642. this._isDisposed = true;
  10643. // Callback
  10644. if (this.onDispose) {
  10645. this.onDispose();
  10646. }
  10647. };
  10648. // Statics
  10649. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10650. AbstractMesh._BILLBOARDMODE_X = 1;
  10651. AbstractMesh._BILLBOARDMODE_Y = 2;
  10652. AbstractMesh._BILLBOARDMODE_Z = 4;
  10653. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10654. return AbstractMesh;
  10655. })(BABYLON.Node);
  10656. BABYLON.AbstractMesh = AbstractMesh;
  10657. })(BABYLON || (BABYLON = {}));
  10658. //# sourceMappingURL=babylon.abstractMesh.js.map
  10659. var BABYLON;
  10660. (function (BABYLON) {
  10661. var _InstancesBatch = (function () {
  10662. function _InstancesBatch() {
  10663. this.mustReturn = false;
  10664. this.visibleInstances = new Array();
  10665. this.renderSelf = new Array();
  10666. }
  10667. return _InstancesBatch;
  10668. })();
  10669. BABYLON._InstancesBatch = _InstancesBatch;
  10670. var Mesh = (function (_super) {
  10671. __extends(Mesh, _super);
  10672. /**
  10673. * @constructor
  10674. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10675. * @param {Scene} scene - The scene to add this mesh to.
  10676. * @param {Node} parent - The parent of this mesh, if it has one
  10677. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10678. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10679. * When false, achieved by calling a clone(), also passing False.
  10680. * This will make creation of children, recursive.
  10681. */
  10682. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10683. if (parent === void 0) { parent = null; }
  10684. _super.call(this, name, scene);
  10685. // Members
  10686. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10687. this.instances = new Array();
  10688. this._LODLevels = new Array();
  10689. this._onBeforeRenderCallbacks = new Array();
  10690. this._onAfterRenderCallbacks = new Array();
  10691. this._visibleInstances = {};
  10692. this._renderIdForInstances = new Array();
  10693. this._batchCache = new _InstancesBatch();
  10694. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10695. if (source) {
  10696. // Geometry
  10697. if (source._geometry) {
  10698. source._geometry.applyToMesh(this);
  10699. }
  10700. // Deep copy
  10701. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10702. // Material
  10703. this.material = source.material;
  10704. if (!doNotCloneChildren) {
  10705. for (var index = 0; index < scene.meshes.length; index++) {
  10706. var mesh = scene.meshes[index];
  10707. if (mesh.parent === source) {
  10708. // doNotCloneChildren is always going to be False
  10709. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10710. }
  10711. }
  10712. }
  10713. for (index = 0; index < scene.particleSystems.length; index++) {
  10714. var system = scene.particleSystems[index];
  10715. if (system.emitter === source) {
  10716. system.clone(system.name, this);
  10717. }
  10718. }
  10719. this.computeWorldMatrix(true);
  10720. }
  10721. // Parent
  10722. if (parent !== null) {
  10723. this.parent = parent;
  10724. }
  10725. }
  10726. Object.defineProperty(Mesh, "FRONTSIDE", {
  10727. get: function () {
  10728. return Mesh._FRONTSIDE;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(Mesh, "BACKSIDE", {
  10734. get: function () {
  10735. return Mesh._BACKSIDE;
  10736. },
  10737. enumerable: true,
  10738. configurable: true
  10739. });
  10740. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10741. get: function () {
  10742. return Mesh._DOUBLESIDE;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10748. get: function () {
  10749. return Mesh._DEFAULTSIDE;
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10755. // Methods
  10756. get: function () {
  10757. return this._LODLevels.length > 0;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Mesh.prototype._sortLODLevels = function () {
  10763. this._LODLevels.sort(function (a, b) {
  10764. if (a.distance < b.distance) {
  10765. return 1;
  10766. }
  10767. if (a.distance > b.distance) {
  10768. return -1;
  10769. }
  10770. return 0;
  10771. });
  10772. };
  10773. /**
  10774. * Add a mesh as LOD level triggered at the given distance.
  10775. * @param {number} distance - the distance from the center of the object to show this level
  10776. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10777. * @return {BABYLON.Mesh} this mesh (for chaining)
  10778. */
  10779. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10780. if (mesh && mesh._masterMesh) {
  10781. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10782. return this;
  10783. }
  10784. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10785. this._LODLevels.push(level);
  10786. if (mesh) {
  10787. mesh._masterMesh = this;
  10788. }
  10789. this._sortLODLevels();
  10790. return this;
  10791. };
  10792. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10793. for (var index = 0; index < this._LODLevels.length; index++) {
  10794. var level = this._LODLevels[index];
  10795. if (level.distance === distance) {
  10796. return level.mesh;
  10797. }
  10798. }
  10799. return null;
  10800. };
  10801. /**
  10802. * Remove a mesh from the LOD array
  10803. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10804. * @return {BABYLON.Mesh} this mesh (for chaining)
  10805. */
  10806. Mesh.prototype.removeLODLevel = function (mesh) {
  10807. for (var index = 0; index < this._LODLevels.length; index++) {
  10808. if (this._LODLevels[index].mesh === mesh) {
  10809. this._LODLevels.splice(index, 1);
  10810. if (mesh) {
  10811. mesh._masterMesh = null;
  10812. }
  10813. }
  10814. }
  10815. this._sortLODLevels();
  10816. return this;
  10817. };
  10818. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10819. if (!this._LODLevels || this._LODLevels.length === 0) {
  10820. return this;
  10821. }
  10822. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10823. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10824. return this;
  10825. }
  10826. for (var index = 0; index < this._LODLevels.length; index++) {
  10827. var level = this._LODLevels[index];
  10828. if (level.distance < distanceToCamera) {
  10829. if (level.mesh) {
  10830. level.mesh._preActivate();
  10831. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10832. }
  10833. return level.mesh;
  10834. }
  10835. }
  10836. return this;
  10837. };
  10838. Object.defineProperty(Mesh.prototype, "geometry", {
  10839. get: function () {
  10840. return this._geometry;
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Mesh.prototype.getTotalVertices = function () {
  10846. if (!this._geometry) {
  10847. return 0;
  10848. }
  10849. return this._geometry.getTotalVertices();
  10850. };
  10851. Mesh.prototype.getVerticesData = function (kind) {
  10852. if (!this._geometry) {
  10853. return null;
  10854. }
  10855. return this._geometry.getVerticesData(kind);
  10856. };
  10857. Mesh.prototype.getVertexBuffer = function (kind) {
  10858. if (!this._geometry) {
  10859. return undefined;
  10860. }
  10861. return this._geometry.getVertexBuffer(kind);
  10862. };
  10863. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10864. if (!this._geometry) {
  10865. if (this._delayInfo) {
  10866. return this._delayInfo.indexOf(kind) !== -1;
  10867. }
  10868. return false;
  10869. }
  10870. return this._geometry.isVerticesDataPresent(kind);
  10871. };
  10872. Mesh.prototype.getVerticesDataKinds = function () {
  10873. if (!this._geometry) {
  10874. var result = [];
  10875. if (this._delayInfo) {
  10876. for (var kind in this._delayInfo) {
  10877. result.push(kind);
  10878. }
  10879. }
  10880. return result;
  10881. }
  10882. return this._geometry.getVerticesDataKinds();
  10883. };
  10884. Mesh.prototype.getTotalIndices = function () {
  10885. if (!this._geometry) {
  10886. return 0;
  10887. }
  10888. return this._geometry.getTotalIndices();
  10889. };
  10890. Mesh.prototype.getIndices = function () {
  10891. if (!this._geometry) {
  10892. return [];
  10893. }
  10894. return this._geometry.getIndices();
  10895. };
  10896. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10897. get: function () {
  10898. return this._masterMesh !== null && this._masterMesh !== undefined;
  10899. },
  10900. enumerable: true,
  10901. configurable: true
  10902. });
  10903. Mesh.prototype.isReady = function () {
  10904. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10905. return false;
  10906. }
  10907. return _super.prototype.isReady.call(this);
  10908. };
  10909. Mesh.prototype.isDisposed = function () {
  10910. return this._isDisposed;
  10911. };
  10912. // Methods
  10913. Mesh.prototype._preActivate = function () {
  10914. var sceneRenderId = this.getScene().getRenderId();
  10915. if (this._preActivateId === sceneRenderId) {
  10916. return;
  10917. }
  10918. this._preActivateId = sceneRenderId;
  10919. this._visibleInstances = null;
  10920. };
  10921. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10922. if (!this._visibleInstances) {
  10923. this._visibleInstances = {};
  10924. this._visibleInstances.defaultRenderId = renderId;
  10925. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10926. }
  10927. if (!this._visibleInstances[renderId]) {
  10928. this._visibleInstances[renderId] = new Array();
  10929. }
  10930. this._visibleInstances[renderId].push(instance);
  10931. };
  10932. Mesh.prototype.refreshBoundingInfo = function () {
  10933. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10934. if (data) {
  10935. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10936. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10937. }
  10938. if (this.subMeshes) {
  10939. for (var index = 0; index < this.subMeshes.length; index++) {
  10940. this.subMeshes[index].refreshBoundingInfo();
  10941. }
  10942. }
  10943. this._updateBoundingInfo();
  10944. };
  10945. Mesh.prototype._createGlobalSubMesh = function () {
  10946. var totalVertices = this.getTotalVertices();
  10947. if (!totalVertices || !this.getIndices()) {
  10948. return null;
  10949. }
  10950. this.releaseSubMeshes();
  10951. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10952. };
  10953. Mesh.prototype.subdivide = function (count) {
  10954. if (count < 1) {
  10955. return;
  10956. }
  10957. var totalIndices = this.getTotalIndices();
  10958. var subdivisionSize = (totalIndices / count) | 0;
  10959. var offset = 0;
  10960. while (subdivisionSize % 3 !== 0) {
  10961. subdivisionSize++;
  10962. }
  10963. this.releaseSubMeshes();
  10964. for (var index = 0; index < count; index++) {
  10965. if (offset >= totalIndices) {
  10966. break;
  10967. }
  10968. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10969. offset += subdivisionSize;
  10970. }
  10971. this.synchronizeInstances();
  10972. };
  10973. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10974. if (kind instanceof Array) {
  10975. var temp = data;
  10976. data = kind;
  10977. kind = temp;
  10978. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10979. }
  10980. if (!this._geometry) {
  10981. var vertexData = new BABYLON.VertexData();
  10982. vertexData.set(data, kind);
  10983. var scene = this.getScene();
  10984. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10985. }
  10986. else {
  10987. this._geometry.setVerticesData(kind, data, updatable, stride);
  10988. }
  10989. };
  10990. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10991. if (!this._geometry) {
  10992. return;
  10993. }
  10994. if (!makeItUnique) {
  10995. this._geometry.updateVerticesData(kind, data, updateExtends);
  10996. }
  10997. else {
  10998. this.makeGeometryUnique();
  10999. this.updateVerticesData(kind, data, updateExtends, false);
  11000. }
  11001. };
  11002. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11003. if (!this._geometry) {
  11004. return;
  11005. }
  11006. if (!makeItUnique) {
  11007. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11008. }
  11009. else {
  11010. this.makeGeometryUnique();
  11011. this.updateVerticesDataDirectly(kind, data, offset, false);
  11012. }
  11013. };
  11014. Mesh.prototype.makeGeometryUnique = function () {
  11015. if (!this._geometry) {
  11016. return;
  11017. }
  11018. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11019. geometry.applyToMesh(this);
  11020. };
  11021. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11022. if (!this._geometry) {
  11023. var vertexData = new BABYLON.VertexData();
  11024. vertexData.indices = indices;
  11025. var scene = this.getScene();
  11026. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11027. }
  11028. else {
  11029. this._geometry.setIndices(indices, totalVertices);
  11030. }
  11031. };
  11032. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11033. var engine = this.getScene().getEngine();
  11034. // Wireframe
  11035. var indexToBind;
  11036. switch (fillMode) {
  11037. case BABYLON.Material.PointFillMode:
  11038. indexToBind = null;
  11039. break;
  11040. case BABYLON.Material.WireFrameFillMode:
  11041. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11042. break;
  11043. default:
  11044. case BABYLON.Material.TriangleFillMode:
  11045. indexToBind = this._geometry.getIndexBuffer();
  11046. break;
  11047. }
  11048. // VBOs
  11049. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11050. };
  11051. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11052. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11053. return;
  11054. }
  11055. var engine = this.getScene().getEngine();
  11056. switch (fillMode) {
  11057. case BABYLON.Material.PointFillMode:
  11058. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11059. break;
  11060. case BABYLON.Material.WireFrameFillMode:
  11061. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11062. break;
  11063. default:
  11064. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11065. }
  11066. };
  11067. Mesh.prototype.registerBeforeRender = function (func) {
  11068. this._onBeforeRenderCallbacks.push(func);
  11069. };
  11070. Mesh.prototype.unregisterBeforeRender = function (func) {
  11071. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11072. if (index > -1) {
  11073. this._onBeforeRenderCallbacks.splice(index, 1);
  11074. }
  11075. };
  11076. Mesh.prototype.registerAfterRender = function (func) {
  11077. this._onAfterRenderCallbacks.push(func);
  11078. };
  11079. Mesh.prototype.unregisterAfterRender = function (func) {
  11080. var index = this._onAfterRenderCallbacks.indexOf(func);
  11081. if (index > -1) {
  11082. this._onAfterRenderCallbacks.splice(index, 1);
  11083. }
  11084. };
  11085. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11086. var scene = this.getScene();
  11087. this._batchCache.mustReturn = false;
  11088. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11089. this._batchCache.visibleInstances[subMeshId] = null;
  11090. if (this._visibleInstances) {
  11091. var currentRenderId = scene.getRenderId();
  11092. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11093. var selfRenderId = this._renderId;
  11094. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11095. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11096. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11097. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11098. }
  11099. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11100. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11101. this._batchCache.mustReturn = true;
  11102. return this._batchCache;
  11103. }
  11104. if (currentRenderId !== selfRenderId) {
  11105. this._batchCache.renderSelf[subMeshId] = false;
  11106. }
  11107. }
  11108. this._renderIdForInstances[subMeshId] = currentRenderId;
  11109. }
  11110. return this._batchCache;
  11111. };
  11112. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11113. var visibleInstances = batch.visibleInstances[subMesh._id];
  11114. var matricesCount = visibleInstances.length + 1;
  11115. var bufferSize = matricesCount * 16 * 4;
  11116. while (this._instancesBufferSize < bufferSize) {
  11117. this._instancesBufferSize *= 2;
  11118. }
  11119. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11120. if (this._worldMatricesInstancesBuffer) {
  11121. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11122. }
  11123. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11124. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11125. }
  11126. var offset = 0;
  11127. var instancesCount = 0;
  11128. var world = this.getWorldMatrix();
  11129. if (batch.renderSelf[subMesh._id]) {
  11130. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11131. offset += 16;
  11132. instancesCount++;
  11133. }
  11134. if (visibleInstances) {
  11135. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11136. var instance = visibleInstances[instanceIndex];
  11137. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11138. offset += 16;
  11139. instancesCount++;
  11140. }
  11141. }
  11142. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11143. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11144. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11145. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11146. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11147. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11148. this._draw(subMesh, fillMode, instancesCount);
  11149. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11150. };
  11151. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11152. var scene = this.getScene();
  11153. var engine = scene.getEngine();
  11154. if (hardwareInstancedRendering) {
  11155. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11156. }
  11157. else {
  11158. if (batch.renderSelf[subMesh._id]) {
  11159. // Draw
  11160. if (onBeforeDraw) {
  11161. onBeforeDraw(false, this.getWorldMatrix());
  11162. }
  11163. this._draw(subMesh, fillMode);
  11164. }
  11165. if (batch.visibleInstances[subMesh._id]) {
  11166. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11167. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11168. // World
  11169. var world = instance.getWorldMatrix();
  11170. if (onBeforeDraw) {
  11171. onBeforeDraw(true, world);
  11172. }
  11173. // Draw
  11174. this._draw(subMesh, fillMode);
  11175. }
  11176. }
  11177. }
  11178. };
  11179. Mesh.prototype.render = function (subMesh) {
  11180. var scene = this.getScene();
  11181. // Managing instances
  11182. var batch = this._getInstancesRenderList(subMesh._id);
  11183. if (batch.mustReturn) {
  11184. return;
  11185. }
  11186. // Checking geometry state
  11187. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11188. return;
  11189. }
  11190. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11191. this._onBeforeRenderCallbacks[callbackIndex](this);
  11192. }
  11193. var engine = scene.getEngine();
  11194. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11195. // Material
  11196. var effectiveMaterial = subMesh.getMaterial();
  11197. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11198. return;
  11199. }
  11200. // Outline - step 1
  11201. var savedDepthWrite = engine.getDepthWrite();
  11202. if (this.renderOutline) {
  11203. engine.setDepthWrite(false);
  11204. scene.getOutlineRenderer().render(subMesh, batch);
  11205. engine.setDepthWrite(savedDepthWrite);
  11206. }
  11207. effectiveMaterial._preBind();
  11208. var effect = effectiveMaterial.getEffect();
  11209. // Bind
  11210. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11211. this._bind(subMesh, effect, fillMode);
  11212. var world = this.getWorldMatrix();
  11213. effectiveMaterial.bind(world, this);
  11214. // Draw
  11215. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11216. if (isInstance) {
  11217. effectiveMaterial.bindOnlyWorldMatrix(world);
  11218. }
  11219. });
  11220. // Unbind
  11221. effectiveMaterial.unbind();
  11222. // Outline - step 2
  11223. if (this.renderOutline && savedDepthWrite) {
  11224. engine.setDepthWrite(true);
  11225. engine.setColorWrite(false);
  11226. scene.getOutlineRenderer().render(subMesh, batch);
  11227. engine.setColorWrite(true);
  11228. }
  11229. // Overlay
  11230. if (this.renderOverlay) {
  11231. var currentMode = engine.getAlphaMode();
  11232. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11233. scene.getOutlineRenderer().render(subMesh, batch, true);
  11234. engine.setAlphaMode(currentMode);
  11235. }
  11236. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11237. this._onAfterRenderCallbacks[callbackIndex](this);
  11238. }
  11239. };
  11240. Mesh.prototype.getEmittedParticleSystems = function () {
  11241. var results = new Array();
  11242. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11243. var particleSystem = this.getScene().particleSystems[index];
  11244. if (particleSystem.emitter === this) {
  11245. results.push(particleSystem);
  11246. }
  11247. }
  11248. return results;
  11249. };
  11250. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11251. var results = new Array();
  11252. var descendants = this.getDescendants();
  11253. descendants.push(this);
  11254. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11255. var particleSystem = this.getScene().particleSystems[index];
  11256. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11257. results.push(particleSystem);
  11258. }
  11259. }
  11260. return results;
  11261. };
  11262. Mesh.prototype.getChildren = function () {
  11263. var results = [];
  11264. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11265. var mesh = this.getScene().meshes[index];
  11266. if (mesh.parent === this) {
  11267. results.push(mesh);
  11268. }
  11269. }
  11270. return results;
  11271. };
  11272. Mesh.prototype._checkDelayState = function () {
  11273. var _this = this;
  11274. var that = this;
  11275. var scene = this.getScene();
  11276. if (this._geometry) {
  11277. this._geometry.load(scene);
  11278. }
  11279. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11280. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11281. scene._addPendingData(that);
  11282. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11283. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11284. if (data instanceof ArrayBuffer) {
  11285. _this._delayLoadingFunction(data, _this);
  11286. }
  11287. else {
  11288. _this._delayLoadingFunction(JSON.parse(data), _this);
  11289. }
  11290. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11291. scene._removePendingData(_this);
  11292. }, function () {
  11293. }, scene.database, getBinaryData);
  11294. }
  11295. };
  11296. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11297. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11298. return false;
  11299. }
  11300. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11301. return false;
  11302. }
  11303. this._checkDelayState();
  11304. return true;
  11305. };
  11306. Mesh.prototype.setMaterialByID = function (id) {
  11307. var materials = this.getScene().materials;
  11308. for (var index = 0; index < materials.length; index++) {
  11309. if (materials[index].id === id) {
  11310. this.material = materials[index];
  11311. return;
  11312. }
  11313. }
  11314. // Multi
  11315. var multiMaterials = this.getScene().multiMaterials;
  11316. for (index = 0; index < multiMaterials.length; index++) {
  11317. if (multiMaterials[index].id === id) {
  11318. this.material = multiMaterials[index];
  11319. return;
  11320. }
  11321. }
  11322. };
  11323. Mesh.prototype.getAnimatables = function () {
  11324. var results = [];
  11325. if (this.material) {
  11326. results.push(this.material);
  11327. }
  11328. if (this.skeleton) {
  11329. results.push(this.skeleton);
  11330. }
  11331. return results;
  11332. };
  11333. // Geometry
  11334. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11335. // Position
  11336. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11337. return;
  11338. }
  11339. this._resetPointsArrayCache();
  11340. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11341. var temp = [];
  11342. for (var index = 0; index < data.length; index += 3) {
  11343. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11344. }
  11345. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11346. // Normals
  11347. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11348. return;
  11349. }
  11350. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11351. for (index = 0; index < data.length; index += 3) {
  11352. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11353. }
  11354. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11355. };
  11356. // Cache
  11357. Mesh.prototype._resetPointsArrayCache = function () {
  11358. this._positions = null;
  11359. };
  11360. Mesh.prototype._generatePointsArray = function () {
  11361. if (this._positions)
  11362. return true;
  11363. this._positions = [];
  11364. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11365. if (!data) {
  11366. return false;
  11367. }
  11368. for (var index = 0; index < data.length; index += 3) {
  11369. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11370. }
  11371. return true;
  11372. };
  11373. // Clone
  11374. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11375. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11376. };
  11377. // Dispose
  11378. Mesh.prototype.dispose = function (doNotRecurse) {
  11379. if (this._geometry) {
  11380. this._geometry.releaseForMesh(this, true);
  11381. }
  11382. // Instances
  11383. if (this._worldMatricesInstancesBuffer) {
  11384. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11385. this._worldMatricesInstancesBuffer = null;
  11386. }
  11387. while (this.instances.length) {
  11388. this.instances[0].dispose();
  11389. }
  11390. _super.prototype.dispose.call(this, doNotRecurse);
  11391. };
  11392. // Geometric tools
  11393. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11394. var _this = this;
  11395. var scene = this.getScene();
  11396. var onload = function (img) {
  11397. // Getting height map data
  11398. var canvas = document.createElement("canvas");
  11399. var context = canvas.getContext("2d");
  11400. var heightMapWidth = img.width;
  11401. var heightMapHeight = img.height;
  11402. canvas.width = heightMapWidth;
  11403. canvas.height = heightMapHeight;
  11404. context.drawImage(img, 0, 0);
  11405. // Create VertexData from map data
  11406. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11407. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11408. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11409. //execute success callback, if set
  11410. if (onSuccess) {
  11411. onSuccess(_this);
  11412. }
  11413. };
  11414. BABYLON.Tools.LoadImage(url, onload, function () {
  11415. }, scene.database);
  11416. };
  11417. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11418. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11419. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11420. return;
  11421. }
  11422. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11423. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11424. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11425. var position = BABYLON.Vector3.Zero();
  11426. var normal = BABYLON.Vector3.Zero();
  11427. var uv = BABYLON.Vector2.Zero();
  11428. for (var index = 0; index < positions.length; index += 3) {
  11429. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11430. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11431. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11432. // Compute height
  11433. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11434. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11435. var pos = (u + v * heightMapWidth) * 4;
  11436. var r = buffer[pos] / 255.0;
  11437. var g = buffer[pos + 1] / 255.0;
  11438. var b = buffer[pos + 2] / 255.0;
  11439. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11440. normal.normalize();
  11441. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11442. position = position.add(normal);
  11443. position.toArray(positions, index);
  11444. }
  11445. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11446. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11447. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11448. };
  11449. Mesh.prototype.convertToFlatShadedMesh = function () {
  11450. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11451. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11452. var kinds = this.getVerticesDataKinds();
  11453. var vbs = [];
  11454. var data = [];
  11455. var newdata = [];
  11456. var updatableNormals = false;
  11457. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11458. var kind = kinds[kindIndex];
  11459. var vertexBuffer = this.getVertexBuffer(kind);
  11460. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11461. updatableNormals = vertexBuffer.isUpdatable();
  11462. kinds.splice(kindIndex, 1);
  11463. kindIndex--;
  11464. continue;
  11465. }
  11466. vbs[kind] = vertexBuffer;
  11467. data[kind] = vbs[kind].getData();
  11468. newdata[kind] = [];
  11469. }
  11470. // Save previous submeshes
  11471. var previousSubmeshes = this.subMeshes.slice(0);
  11472. var indices = this.getIndices();
  11473. var totalIndices = this.getTotalIndices();
  11474. for (var index = 0; index < totalIndices; index++) {
  11475. var vertexIndex = indices[index];
  11476. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11477. kind = kinds[kindIndex];
  11478. var stride = vbs[kind].getStrideSize();
  11479. for (var offset = 0; offset < stride; offset++) {
  11480. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11481. }
  11482. }
  11483. }
  11484. // Updating faces & normal
  11485. var normals = [];
  11486. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11487. for (index = 0; index < totalIndices; index += 3) {
  11488. indices[index] = index;
  11489. indices[index + 1] = index + 1;
  11490. indices[index + 2] = index + 2;
  11491. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11492. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11493. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11494. var p1p2 = p1.subtract(p2);
  11495. var p3p2 = p3.subtract(p2);
  11496. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11497. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11498. normals.push(normal.x);
  11499. normals.push(normal.y);
  11500. normals.push(normal.z);
  11501. }
  11502. }
  11503. this.setIndices(indices);
  11504. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11505. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11506. kind = kinds[kindIndex];
  11507. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11508. }
  11509. // Updating submeshes
  11510. this.releaseSubMeshes();
  11511. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11512. var previousOne = previousSubmeshes[submeshIndex];
  11513. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11514. }
  11515. this.synchronizeInstances();
  11516. };
  11517. // Instances
  11518. Mesh.prototype.createInstance = function (name) {
  11519. return new BABYLON.InstancedMesh(name, this);
  11520. };
  11521. Mesh.prototype.synchronizeInstances = function () {
  11522. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11523. var instance = this.instances[instanceIndex];
  11524. instance._syncSubMeshes();
  11525. }
  11526. };
  11527. /**
  11528. * Simplify the mesh according to the given array of settings.
  11529. * Function will return immediately and will simplify async.
  11530. * @param settings a collection of simplification settings.
  11531. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11532. * @param type the type of simplification to run.
  11533. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11534. */
  11535. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11536. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11537. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11538. this.getScene().simplificationQueue.addTask({
  11539. settings: settings,
  11540. parallelProcessing: parallelProcessing,
  11541. mesh: this,
  11542. simplificationType: simplificationType,
  11543. successCallback: successCallback
  11544. });
  11545. };
  11546. /**
  11547. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11548. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11549. * This should be used together with the simplification to avoid disappearing triangles.
  11550. * @param successCallback an optional success callback to be called after the optimization finished.
  11551. */
  11552. Mesh.prototype.optimizeIndices = function (successCallback) {
  11553. var _this = this;
  11554. var indices = this.getIndices();
  11555. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11556. var vectorPositions = [];
  11557. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11558. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11559. }
  11560. var dupes = [];
  11561. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11562. var realPos = vectorPositions.length - 1 - iteration;
  11563. var testedPosition = vectorPositions[realPos];
  11564. for (var j = 0; j < realPos; ++j) {
  11565. var againstPosition = vectorPositions[j];
  11566. if (testedPosition.equals(againstPosition)) {
  11567. dupes[realPos] = j;
  11568. break;
  11569. }
  11570. }
  11571. }, function () {
  11572. for (var i = 0; i < indices.length; ++i) {
  11573. indices[i] = dupes[indices[i]] || indices[i];
  11574. }
  11575. //indices are now reordered
  11576. var originalSubMeshes = _this.subMeshes.slice(0);
  11577. _this.setIndices(indices);
  11578. _this.subMeshes = originalSubMeshes;
  11579. if (successCallback) {
  11580. successCallback(_this);
  11581. }
  11582. });
  11583. };
  11584. // Statics
  11585. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11586. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11587. var ribbon = new Mesh(name, scene);
  11588. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11589. vertexData.applyToMesh(ribbon, updatable);
  11590. return ribbon;
  11591. };
  11592. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11593. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11594. var box = new Mesh(name, scene);
  11595. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11596. vertexData.applyToMesh(box, updatable);
  11597. return box;
  11598. };
  11599. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11600. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11601. var sphere = new Mesh(name, scene);
  11602. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11603. vertexData.applyToMesh(sphere, updatable);
  11604. return sphere;
  11605. };
  11606. // Cylinder and cone (Code inspired by SharpDX.org)
  11607. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11608. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11609. // subdivisions is a new parameter, we need to support old signature
  11610. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11611. if (scene !== undefined) {
  11612. updatable = scene;
  11613. }
  11614. scene = subdivisions;
  11615. subdivisions = 1;
  11616. }
  11617. var cylinder = new Mesh(name, scene);
  11618. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11619. vertexData.applyToMesh(cylinder, updatable);
  11620. return cylinder;
  11621. };
  11622. // Torus (Code from SharpDX.org)
  11623. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11624. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11625. var torus = new Mesh(name, scene);
  11626. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11627. vertexData.applyToMesh(torus, updatable);
  11628. return torus;
  11629. };
  11630. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11631. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11632. var torusKnot = new Mesh(name, scene);
  11633. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11634. vertexData.applyToMesh(torusKnot, updatable);
  11635. return torusKnot;
  11636. };
  11637. // Lines
  11638. Mesh.CreateLines = function (name, points, scene, updatable) {
  11639. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11640. var vertexData = BABYLON.VertexData.CreateLines(points);
  11641. vertexData.applyToMesh(lines, updatable);
  11642. return lines;
  11643. };
  11644. // Extrusion
  11645. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11646. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11647. scale = scale || 1;
  11648. rotation = rotation || 0;
  11649. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11650. return extruded;
  11651. };
  11652. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11653. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11654. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11655. return extrudedCustom;
  11656. };
  11657. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11658. var path3D = new BABYLON.Path3D(curve);
  11659. var tangents = path3D.getTangents();
  11660. var normals = path3D.getNormals();
  11661. var binormals = path3D.getBinormals();
  11662. var distances = path3D.getDistances();
  11663. var shapePaths = new Array();
  11664. var angle = 0;
  11665. var returnScale = function (i, distance) {
  11666. return scale;
  11667. };
  11668. var returnRotation = function (i, distance) {
  11669. return rotation;
  11670. };
  11671. var rotate = custom ? rotateFunction : returnRotation;
  11672. var scl = custom ? scaleFunction : returnScale;
  11673. for (var i = 0; i < curve.length; i++) {
  11674. var shapePath = new Array();
  11675. var angleStep = rotate(i, distances[i]);
  11676. var scaleRatio = scl(i, distances[i]);
  11677. for (var p = 0; p < shape.length; p++) {
  11678. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11679. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11680. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11681. shapePath.push(rotated);
  11682. }
  11683. shapePaths.push(shapePath);
  11684. angle += angleStep;
  11685. }
  11686. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11687. return extrudedGeneric;
  11688. };
  11689. // Plane & ground
  11690. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11691. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11692. var plane = new Mesh(name, scene);
  11693. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11694. vertexData.applyToMesh(plane, updatable);
  11695. return plane;
  11696. };
  11697. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11698. var ground = new BABYLON.GroundMesh(name, scene);
  11699. ground._setReady(false);
  11700. ground._subdivisions = subdivisions;
  11701. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11702. vertexData.applyToMesh(ground, updatable);
  11703. ground._setReady(true);
  11704. return ground;
  11705. };
  11706. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11707. var tiledGround = new Mesh(name, scene);
  11708. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11709. vertexData.applyToMesh(tiledGround, updatable);
  11710. return tiledGround;
  11711. };
  11712. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11713. var ground = new BABYLON.GroundMesh(name, scene);
  11714. ground._subdivisions = subdivisions;
  11715. ground._setReady(false);
  11716. var onload = function (img) {
  11717. // Getting height map data
  11718. var canvas = document.createElement("canvas");
  11719. var context = canvas.getContext("2d");
  11720. var heightMapWidth = img.width;
  11721. var heightMapHeight = img.height;
  11722. canvas.width = heightMapWidth;
  11723. canvas.height = heightMapHeight;
  11724. context.drawImage(img, 0, 0);
  11725. // Create VertexData from map data
  11726. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11727. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11728. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11729. vertexData.applyToMesh(ground, updatable);
  11730. ground._setReady(true);
  11731. //execute ready callback, if set
  11732. if (onReady) {
  11733. onReady(ground);
  11734. }
  11735. };
  11736. BABYLON.Tools.LoadImage(url, onload, function () {
  11737. }, scene.database);
  11738. return ground;
  11739. };
  11740. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11741. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11742. var path3D = new BABYLON.Path3D(path);
  11743. var tangents = path3D.getTangents();
  11744. var normals = path3D.getNormals();
  11745. var distances = path3D.getDistances();
  11746. var pi2 = Math.PI * 2;
  11747. var step = pi2 / tesselation;
  11748. var returnRadius = function (i, distance) { return radius; };
  11749. var radiusFunctionFinal = radiusFunction || returnRadius;
  11750. var circlePaths = new Array();
  11751. var circlePath;
  11752. var rad;
  11753. var normal;
  11754. var rotated;
  11755. var rotationMatrix;
  11756. for (var i = 0; i < path.length; i++) {
  11757. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11758. circlePath = Array(); // current circle array
  11759. normal = normals[i]; // current normal
  11760. for (var ang = 0; ang < pi2; ang += step) {
  11761. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11762. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11763. circlePath.push(rotated);
  11764. }
  11765. circlePaths.push(circlePath);
  11766. }
  11767. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11768. return tube;
  11769. };
  11770. // Tools
  11771. Mesh.MinMax = function (meshes) {
  11772. var minVector = null;
  11773. var maxVector = null;
  11774. for (var i in meshes) {
  11775. var mesh = meshes[i];
  11776. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11777. if (!minVector) {
  11778. minVector = boundingBox.minimumWorld;
  11779. maxVector = boundingBox.maximumWorld;
  11780. continue;
  11781. }
  11782. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11783. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11784. }
  11785. return {
  11786. min: minVector,
  11787. max: maxVector
  11788. };
  11789. };
  11790. Mesh.Center = function (meshesOrMinMaxVector) {
  11791. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11792. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11793. };
  11794. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11795. if (disposeSource === void 0) { disposeSource = true; }
  11796. var source = meshes[0];
  11797. var material = source.material;
  11798. var scene = source.getScene();
  11799. if (!allow32BitsIndices) {
  11800. var totalVertices = 0;
  11801. for (var index = 0; index < meshes.length; index++) {
  11802. totalVertices += meshes[index].getTotalVertices();
  11803. if (totalVertices > 65536) {
  11804. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11805. return null;
  11806. }
  11807. }
  11808. }
  11809. // Merge
  11810. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11811. vertexData.transform(source.getWorldMatrix());
  11812. for (index = 1; index < meshes.length; index++) {
  11813. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11814. otherVertexData.transform(meshes[index].getWorldMatrix());
  11815. vertexData.merge(otherVertexData);
  11816. }
  11817. var newMesh = new Mesh(source.name + "_merged", scene);
  11818. vertexData.applyToMesh(newMesh);
  11819. // Setting properties
  11820. newMesh.material = material;
  11821. newMesh.checkCollisions = source.checkCollisions;
  11822. // Cleaning
  11823. if (disposeSource) {
  11824. for (index = 0; index < meshes.length; index++) {
  11825. meshes[index].dispose();
  11826. }
  11827. }
  11828. return newMesh;
  11829. };
  11830. // Consts
  11831. Mesh._FRONTSIDE = 0;
  11832. Mesh._BACKSIDE = 1;
  11833. Mesh._DOUBLESIDE = 2;
  11834. Mesh._DEFAULTSIDE = 0;
  11835. return Mesh;
  11836. })(BABYLON.AbstractMesh);
  11837. BABYLON.Mesh = Mesh;
  11838. })(BABYLON || (BABYLON = {}));
  11839. //# sourceMappingURL=babylon.mesh.js.map
  11840. var BABYLON;
  11841. (function (BABYLON) {
  11842. var GroundMesh = (function (_super) {
  11843. __extends(GroundMesh, _super);
  11844. function GroundMesh(name, scene) {
  11845. _super.call(this, name, scene);
  11846. this.generateOctree = false;
  11847. this._worldInverse = new BABYLON.Matrix();
  11848. }
  11849. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11850. get: function () {
  11851. return this._subdivisions;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. GroundMesh.prototype.optimize = function (chunksCount) {
  11857. this.subdivide(this._subdivisions);
  11858. this.createOrUpdateSubmeshesOctree(32);
  11859. };
  11860. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11861. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11862. this.getWorldMatrix().invertToRef(this._worldInverse);
  11863. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11864. var pickInfo = this.intersects(ray);
  11865. if (pickInfo.hit) {
  11866. return pickInfo.pickedPoint.y;
  11867. }
  11868. return 0;
  11869. };
  11870. return GroundMesh;
  11871. })(BABYLON.Mesh);
  11872. BABYLON.GroundMesh = GroundMesh;
  11873. })(BABYLON || (BABYLON = {}));
  11874. //# sourceMappingURL=babylon.groundMesh.js.map
  11875. var BABYLON;
  11876. (function (BABYLON) {
  11877. /**
  11878. * Creates an instance based on a source mesh.
  11879. */
  11880. var InstancedMesh = (function (_super) {
  11881. __extends(InstancedMesh, _super);
  11882. function InstancedMesh(name, source) {
  11883. _super.call(this, name, source.getScene());
  11884. source.instances.push(this);
  11885. this._sourceMesh = source;
  11886. this.position.copyFrom(source.position);
  11887. this.rotation.copyFrom(source.rotation);
  11888. this.scaling.copyFrom(source.scaling);
  11889. if (source.rotationQuaternion) {
  11890. this.rotationQuaternion = source.rotationQuaternion.clone();
  11891. }
  11892. this.infiniteDistance = source.infiniteDistance;
  11893. this.setPivotMatrix(source.getPivotMatrix());
  11894. this.refreshBoundingInfo();
  11895. this._syncSubMeshes();
  11896. }
  11897. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11898. // Methods
  11899. get: function () {
  11900. return this._sourceMesh.receiveShadows;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(InstancedMesh.prototype, "material", {
  11906. get: function () {
  11907. return this._sourceMesh.material;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11913. get: function () {
  11914. return this._sourceMesh.visibility;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11920. get: function () {
  11921. return this._sourceMesh.skeleton;
  11922. },
  11923. enumerable: true,
  11924. configurable: true
  11925. });
  11926. InstancedMesh.prototype.getTotalVertices = function () {
  11927. return this._sourceMesh.getTotalVertices();
  11928. };
  11929. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11930. get: function () {
  11931. return this._sourceMesh;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. InstancedMesh.prototype.getVerticesData = function (kind) {
  11937. return this._sourceMesh.getVerticesData(kind);
  11938. };
  11939. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11940. return this._sourceMesh.isVerticesDataPresent(kind);
  11941. };
  11942. InstancedMesh.prototype.getIndices = function () {
  11943. return this._sourceMesh.getIndices();
  11944. };
  11945. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11946. get: function () {
  11947. return this._sourceMesh._positions;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11953. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11954. if (data) {
  11955. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11956. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11957. }
  11958. this._updateBoundingInfo();
  11959. };
  11960. InstancedMesh.prototype._preActivate = function () {
  11961. if (this._currentLOD) {
  11962. this._currentLOD._preActivate();
  11963. }
  11964. };
  11965. InstancedMesh.prototype._activate = function (renderId) {
  11966. if (this._currentLOD) {
  11967. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11968. }
  11969. };
  11970. InstancedMesh.prototype.getLOD = function (camera) {
  11971. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11972. if (this._currentLOD === this.sourceMesh) {
  11973. return this;
  11974. }
  11975. return this._currentLOD;
  11976. };
  11977. InstancedMesh.prototype._syncSubMeshes = function () {
  11978. this.releaseSubMeshes();
  11979. if (this._sourceMesh.subMeshes) {
  11980. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11981. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11982. }
  11983. }
  11984. };
  11985. InstancedMesh.prototype._generatePointsArray = function () {
  11986. return this._sourceMesh._generatePointsArray();
  11987. };
  11988. // Clone
  11989. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11990. var result = this._sourceMesh.createInstance(name);
  11991. // Deep copy
  11992. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11993. // Bounding info
  11994. this.refreshBoundingInfo();
  11995. // Parent
  11996. if (newParent) {
  11997. result.parent = newParent;
  11998. }
  11999. if (!doNotCloneChildren) {
  12000. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12001. var mesh = this.getScene().meshes[index];
  12002. if (mesh.parent === this) {
  12003. mesh.clone(mesh.name, result);
  12004. }
  12005. }
  12006. }
  12007. result.computeWorldMatrix(true);
  12008. return result;
  12009. };
  12010. // Dispoe
  12011. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12012. // Remove from mesh
  12013. var index = this._sourceMesh.instances.indexOf(this);
  12014. this._sourceMesh.instances.splice(index, 1);
  12015. _super.prototype.dispose.call(this, doNotRecurse);
  12016. };
  12017. return InstancedMesh;
  12018. })(BABYLON.AbstractMesh);
  12019. BABYLON.InstancedMesh = InstancedMesh;
  12020. })(BABYLON || (BABYLON = {}));
  12021. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12022. (function (BABYLON) {
  12023. var SubMesh = (function () {
  12024. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12025. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12026. this.materialIndex = materialIndex;
  12027. this.verticesStart = verticesStart;
  12028. this.verticesCount = verticesCount;
  12029. this.indexStart = indexStart;
  12030. this.indexCount = indexCount;
  12031. this._renderId = 0;
  12032. this._mesh = mesh;
  12033. this._renderingMesh = renderingMesh || mesh;
  12034. mesh.subMeshes.push(this);
  12035. this._id = mesh.subMeshes.length - 1;
  12036. if (createBoundingBox) {
  12037. this.refreshBoundingInfo();
  12038. mesh.computeWorldMatrix(true);
  12039. }
  12040. }
  12041. SubMesh.prototype.getBoundingInfo = function () {
  12042. return this._boundingInfo;
  12043. };
  12044. SubMesh.prototype.getMesh = function () {
  12045. return this._mesh;
  12046. };
  12047. SubMesh.prototype.getRenderingMesh = function () {
  12048. return this._renderingMesh;
  12049. };
  12050. SubMesh.prototype.getMaterial = function () {
  12051. var rootMaterial = this._renderingMesh.material;
  12052. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12053. var multiMaterial = rootMaterial;
  12054. return multiMaterial.getSubMaterial(this.materialIndex);
  12055. }
  12056. if (!rootMaterial) {
  12057. return this._mesh.getScene().defaultMaterial;
  12058. }
  12059. return rootMaterial;
  12060. };
  12061. // Methods
  12062. SubMesh.prototype.refreshBoundingInfo = function () {
  12063. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12064. if (!data) {
  12065. this._boundingInfo = this._mesh._boundingInfo;
  12066. return;
  12067. }
  12068. var indices = this._renderingMesh.getIndices();
  12069. var extend;
  12070. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12071. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12072. }
  12073. else {
  12074. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12075. }
  12076. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12077. };
  12078. SubMesh.prototype._checkCollision = function (collider) {
  12079. return this._boundingInfo._checkCollision(collider);
  12080. };
  12081. SubMesh.prototype.updateBoundingInfo = function (world) {
  12082. if (!this._boundingInfo) {
  12083. this.refreshBoundingInfo();
  12084. }
  12085. this._boundingInfo._update(world);
  12086. };
  12087. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12088. return this._boundingInfo.isInFrustum(frustumPlanes);
  12089. };
  12090. SubMesh.prototype.render = function () {
  12091. this._renderingMesh.render(this);
  12092. };
  12093. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12094. if (!this._linesIndexBuffer) {
  12095. var linesIndices = [];
  12096. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12097. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12098. }
  12099. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12100. this.linesIndexCount = linesIndices.length;
  12101. }
  12102. return this._linesIndexBuffer;
  12103. };
  12104. SubMesh.prototype.canIntersects = function (ray) {
  12105. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12106. };
  12107. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12108. var intersectInfo = null;
  12109. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12110. var p0 = positions[indices[index]];
  12111. var p1 = positions[indices[index + 1]];
  12112. var p2 = positions[indices[index + 2]];
  12113. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12114. if (currentIntersectInfo) {
  12115. if (currentIntersectInfo.distance < 0) {
  12116. continue;
  12117. }
  12118. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12119. intersectInfo = currentIntersectInfo;
  12120. intersectInfo.faceId = index / 3;
  12121. if (fastCheck) {
  12122. break;
  12123. }
  12124. }
  12125. }
  12126. }
  12127. return intersectInfo;
  12128. };
  12129. // Clone
  12130. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12131. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12132. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12133. return result;
  12134. };
  12135. // Dispose
  12136. SubMesh.prototype.dispose = function () {
  12137. if (this._linesIndexBuffer) {
  12138. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12139. this._linesIndexBuffer = null;
  12140. }
  12141. // Remove from mesh
  12142. var index = this._mesh.subMeshes.indexOf(this);
  12143. this._mesh.subMeshes.splice(index, 1);
  12144. };
  12145. // Statics
  12146. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12147. var minVertexIndex = Number.MAX_VALUE;
  12148. var maxVertexIndex = -Number.MAX_VALUE;
  12149. renderingMesh = renderingMesh || mesh;
  12150. var indices = renderingMesh.getIndices();
  12151. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12152. var vertexIndex = indices[index];
  12153. if (vertexIndex < minVertexIndex)
  12154. minVertexIndex = vertexIndex;
  12155. if (vertexIndex > maxVertexIndex)
  12156. maxVertexIndex = vertexIndex;
  12157. }
  12158. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12159. };
  12160. return SubMesh;
  12161. })();
  12162. BABYLON.SubMesh = SubMesh;
  12163. })(BABYLON || (BABYLON = {}));
  12164. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12165. (function (BABYLON) {
  12166. var BaseTexture = (function () {
  12167. function BaseTexture(scene) {
  12168. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12169. this.hasAlpha = false;
  12170. this.getAlphaFromRGB = false;
  12171. this.level = 1;
  12172. this.isCube = false;
  12173. this.isRenderTarget = false;
  12174. this.animations = new Array();
  12175. this.coordinatesIndex = 0;
  12176. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12177. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12178. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12179. this.anisotropicFilteringLevel = 4;
  12180. this._scene = scene;
  12181. this._scene.textures.push(this);
  12182. }
  12183. BaseTexture.prototype.getScene = function () {
  12184. return this._scene;
  12185. };
  12186. BaseTexture.prototype.getTextureMatrix = function () {
  12187. return null;
  12188. };
  12189. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12190. return null;
  12191. };
  12192. BaseTexture.prototype.getInternalTexture = function () {
  12193. return this._texture;
  12194. };
  12195. BaseTexture.prototype.isReady = function () {
  12196. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12197. return true;
  12198. }
  12199. if (this._texture) {
  12200. return this._texture.isReady;
  12201. }
  12202. return false;
  12203. };
  12204. BaseTexture.prototype.getSize = function () {
  12205. if (this._texture._width) {
  12206. return { width: this._texture._width, height: this._texture._height };
  12207. }
  12208. if (this._texture._size) {
  12209. return { width: this._texture._size, height: this._texture._size };
  12210. }
  12211. return { width: 0, height: 0 };
  12212. };
  12213. BaseTexture.prototype.getBaseSize = function () {
  12214. if (!this.isReady())
  12215. return { width: 0, height: 0 };
  12216. if (this._texture._size) {
  12217. return { width: this._texture._size, height: this._texture._size };
  12218. }
  12219. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12220. };
  12221. BaseTexture.prototype.scale = function (ratio) {
  12222. };
  12223. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12224. get: function () {
  12225. return false;
  12226. },
  12227. enumerable: true,
  12228. configurable: true
  12229. });
  12230. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12231. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12232. for (var index = 0; index < texturesCache.length; index++) {
  12233. var texturesCacheEntry = texturesCache[index];
  12234. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12235. texturesCache.splice(index, 1);
  12236. return;
  12237. }
  12238. }
  12239. };
  12240. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12241. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12242. for (var index = 0; index < texturesCache.length; index++) {
  12243. var texturesCacheEntry = texturesCache[index];
  12244. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12245. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12246. texturesCacheEntry.references++;
  12247. return texturesCacheEntry;
  12248. }
  12249. }
  12250. }
  12251. return null;
  12252. };
  12253. BaseTexture.prototype.delayLoad = function () {
  12254. };
  12255. BaseTexture.prototype.releaseInternalTexture = function () {
  12256. if (!this._texture) {
  12257. return;
  12258. }
  12259. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12260. this._texture.references--;
  12261. // Final reference ?
  12262. if (this._texture.references === 0) {
  12263. var index = texturesCache.indexOf(this._texture);
  12264. texturesCache.splice(index, 1);
  12265. this._scene.getEngine()._releaseTexture(this._texture);
  12266. delete this._texture;
  12267. }
  12268. };
  12269. BaseTexture.prototype.clone = function () {
  12270. return null;
  12271. };
  12272. BaseTexture.prototype.dispose = function () {
  12273. // Remove from scene
  12274. var index = this._scene.textures.indexOf(this);
  12275. if (index >= 0) {
  12276. this._scene.textures.splice(index, 1);
  12277. }
  12278. if (this._texture === undefined) {
  12279. return;
  12280. }
  12281. this.releaseInternalTexture();
  12282. // Callback
  12283. if (this.onDispose) {
  12284. this.onDispose();
  12285. }
  12286. };
  12287. return BaseTexture;
  12288. })();
  12289. BABYLON.BaseTexture = BaseTexture;
  12290. })(BABYLON || (BABYLON = {}));
  12291. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12292. (function (BABYLON) {
  12293. var RenderingGroup = (function () {
  12294. function RenderingGroup(index, scene) {
  12295. this.index = index;
  12296. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12297. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12298. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12299. this._scene = scene;
  12300. }
  12301. RenderingGroup.prototype.render = function (customRenderFunction) {
  12302. if (customRenderFunction) {
  12303. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12304. return true;
  12305. }
  12306. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12307. return false;
  12308. }
  12309. var engine = this._scene.getEngine();
  12310. // Opaque
  12311. var subIndex;
  12312. var submesh;
  12313. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12314. submesh = this._opaqueSubMeshes.data[subIndex];
  12315. submesh.render();
  12316. }
  12317. // Alpha test
  12318. engine.setAlphaTesting(true);
  12319. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12320. submesh = this._alphaTestSubMeshes.data[subIndex];
  12321. submesh.render();
  12322. }
  12323. engine.setAlphaTesting(false);
  12324. // Transparent
  12325. if (this._transparentSubMeshes.length) {
  12326. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12327. submesh = this._transparentSubMeshes.data[subIndex];
  12328. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12329. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12330. }
  12331. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12332. sortedArray.sort(function (a, b) {
  12333. // Alpha index first
  12334. if (a._alphaIndex > b._alphaIndex) {
  12335. return 1;
  12336. }
  12337. if (a._alphaIndex < b._alphaIndex) {
  12338. return -1;
  12339. }
  12340. // Then distance to camera
  12341. if (a._distanceToCamera < b._distanceToCamera) {
  12342. return 1;
  12343. }
  12344. if (a._distanceToCamera > b._distanceToCamera) {
  12345. return -1;
  12346. }
  12347. return 0;
  12348. });
  12349. // Rendering
  12350. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12351. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12352. submesh = sortedArray[subIndex];
  12353. submesh.render();
  12354. }
  12355. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12356. }
  12357. return true;
  12358. };
  12359. RenderingGroup.prototype.prepare = function () {
  12360. this._opaqueSubMeshes.reset();
  12361. this._transparentSubMeshes.reset();
  12362. this._alphaTestSubMeshes.reset();
  12363. };
  12364. RenderingGroup.prototype.dispatch = function (subMesh) {
  12365. var material = subMesh.getMaterial();
  12366. var mesh = subMesh.getMesh();
  12367. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12368. this._transparentSubMeshes.push(subMesh);
  12369. }
  12370. else if (material.needAlphaTesting()) {
  12371. this._alphaTestSubMeshes.push(subMesh);
  12372. }
  12373. else {
  12374. this._opaqueSubMeshes.push(subMesh); // Opaque
  12375. }
  12376. };
  12377. return RenderingGroup;
  12378. })();
  12379. BABYLON.RenderingGroup = RenderingGroup;
  12380. })(BABYLON || (BABYLON = {}));
  12381. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12382. (function (BABYLON) {
  12383. var RenderingManager = (function () {
  12384. function RenderingManager(scene) {
  12385. this._renderingGroups = new Array();
  12386. this._scene = scene;
  12387. }
  12388. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12389. if (this._scene._activeParticleSystems.length === 0) {
  12390. return;
  12391. }
  12392. // Particles
  12393. var beforeParticlesDate = BABYLON.Tools.Now;
  12394. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12395. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12396. if (particleSystem.renderingGroupId !== index) {
  12397. continue;
  12398. }
  12399. this._clearDepthBuffer();
  12400. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12401. this._scene._activeParticles += particleSystem.render();
  12402. }
  12403. }
  12404. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12405. };
  12406. RenderingManager.prototype._renderSprites = function (index) {
  12407. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12408. return;
  12409. }
  12410. // Sprites
  12411. var beforeSpritessDate = BABYLON.Tools.Now;
  12412. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12413. var spriteManager = this._scene.spriteManagers[id];
  12414. if (spriteManager.renderingGroupId === index) {
  12415. this._clearDepthBuffer();
  12416. spriteManager.render();
  12417. }
  12418. }
  12419. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12420. };
  12421. RenderingManager.prototype._clearDepthBuffer = function () {
  12422. if (this._depthBufferAlreadyCleaned) {
  12423. return;
  12424. }
  12425. this._scene.getEngine().clear(0, false, true);
  12426. this._depthBufferAlreadyCleaned = true;
  12427. };
  12428. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12429. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12430. this._depthBufferAlreadyCleaned = false;
  12431. var renderingGroup = this._renderingGroups[index];
  12432. var needToStepBack = false;
  12433. if (renderingGroup) {
  12434. this._clearDepthBuffer();
  12435. if (!renderingGroup.render(customRenderFunction)) {
  12436. this._renderingGroups.splice(index, 1);
  12437. needToStepBack = true;
  12438. }
  12439. }
  12440. if (renderSprites) {
  12441. this._renderSprites(index);
  12442. }
  12443. if (renderParticles) {
  12444. this._renderParticles(index, activeMeshes);
  12445. }
  12446. if (needToStepBack) {
  12447. index--;
  12448. }
  12449. }
  12450. };
  12451. RenderingManager.prototype.reset = function () {
  12452. for (var index in this._renderingGroups) {
  12453. var renderingGroup = this._renderingGroups[index];
  12454. renderingGroup.prepare();
  12455. }
  12456. };
  12457. RenderingManager.prototype.dispatch = function (subMesh) {
  12458. var mesh = subMesh.getMesh();
  12459. var renderingGroupId = mesh.renderingGroupId || 0;
  12460. if (!this._renderingGroups[renderingGroupId]) {
  12461. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12462. }
  12463. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12464. };
  12465. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12466. return RenderingManager;
  12467. })();
  12468. BABYLON.RenderingManager = RenderingManager;
  12469. })(BABYLON || (BABYLON = {}));
  12470. //# sourceMappingURL=babylon.renderingManager.js.map
  12471. var BABYLON;
  12472. (function (BABYLON) {
  12473. var Texture = (function (_super) {
  12474. __extends(Texture, _super);
  12475. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12476. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12477. if (onLoad === void 0) { onLoad = null; }
  12478. if (onError === void 0) { onError = null; }
  12479. if (buffer === void 0) { buffer = null; }
  12480. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12481. _super.call(this, scene);
  12482. this.uOffset = 0;
  12483. this.vOffset = 0;
  12484. this.uScale = 1.0;
  12485. this.vScale = 1.0;
  12486. this.uAng = 0;
  12487. this.vAng = 0;
  12488. this.wAng = 0;
  12489. this.name = url;
  12490. this.url = url;
  12491. this._noMipmap = noMipmap;
  12492. this._invertY = invertY;
  12493. this._samplingMode = samplingMode;
  12494. this._buffer = buffer;
  12495. this._deleteBuffer = deleteBuffer;
  12496. if (!url) {
  12497. return;
  12498. }
  12499. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12500. if (!this._texture) {
  12501. if (!scene.useDelayedTextureLoading) {
  12502. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12503. if (deleteBuffer) {
  12504. delete this._buffer;
  12505. }
  12506. }
  12507. else {
  12508. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12509. }
  12510. }
  12511. }
  12512. Texture.prototype.delayLoad = function () {
  12513. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12514. return;
  12515. }
  12516. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12517. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12518. if (!this._texture) {
  12519. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12520. if (this._deleteBuffer) {
  12521. delete this._buffer;
  12522. }
  12523. }
  12524. };
  12525. Texture.prototype.updateSamplingMode = function (samplingMode) {
  12526. if (!this._texture) {
  12527. return;
  12528. }
  12529. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  12530. };
  12531. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12532. x -= this.uOffset + 0.5;
  12533. y -= this.vOffset + 0.5;
  12534. z -= 0.5;
  12535. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12536. t.x *= this.uScale;
  12537. t.y *= this.vScale;
  12538. t.x += 0.5;
  12539. t.y += 0.5;
  12540. t.z += 0.5;
  12541. };
  12542. Texture.prototype.getTextureMatrix = function () {
  12543. 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) {
  12544. return this._cachedTextureMatrix;
  12545. }
  12546. this._cachedUOffset = this.uOffset;
  12547. this._cachedVOffset = this.vOffset;
  12548. this._cachedUScale = this.uScale;
  12549. this._cachedVScale = this.vScale;
  12550. this._cachedUAng = this.uAng;
  12551. this._cachedVAng = this.vAng;
  12552. this._cachedWAng = this.wAng;
  12553. if (!this._cachedTextureMatrix) {
  12554. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12555. this._rowGenerationMatrix = new BABYLON.Matrix();
  12556. this._t0 = BABYLON.Vector3.Zero();
  12557. this._t1 = BABYLON.Vector3.Zero();
  12558. this._t2 = BABYLON.Vector3.Zero();
  12559. }
  12560. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12561. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12562. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12563. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12564. this._t1.subtractInPlace(this._t0);
  12565. this._t2.subtractInPlace(this._t0);
  12566. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12567. this._cachedTextureMatrix.m[0] = this._t1.x;
  12568. this._cachedTextureMatrix.m[1] = this._t1.y;
  12569. this._cachedTextureMatrix.m[2] = this._t1.z;
  12570. this._cachedTextureMatrix.m[4] = this._t2.x;
  12571. this._cachedTextureMatrix.m[5] = this._t2.y;
  12572. this._cachedTextureMatrix.m[6] = this._t2.z;
  12573. this._cachedTextureMatrix.m[8] = this._t0.x;
  12574. this._cachedTextureMatrix.m[9] = this._t0.y;
  12575. this._cachedTextureMatrix.m[10] = this._t0.z;
  12576. return this._cachedTextureMatrix;
  12577. };
  12578. Texture.prototype.getReflectionTextureMatrix = function () {
  12579. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12580. return this._cachedTextureMatrix;
  12581. }
  12582. if (!this._cachedTextureMatrix) {
  12583. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12584. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12585. }
  12586. this._cachedCoordinatesMode = this.coordinatesMode;
  12587. switch (this.coordinatesMode) {
  12588. case Texture.SPHERICAL_MODE:
  12589. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12590. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12591. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12592. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12593. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12594. break;
  12595. case Texture.PLANAR_MODE:
  12596. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12597. this._cachedTextureMatrix[0] = this.uScale;
  12598. this._cachedTextureMatrix[5] = this.vScale;
  12599. this._cachedTextureMatrix[12] = this.uOffset;
  12600. this._cachedTextureMatrix[13] = this.vOffset;
  12601. break;
  12602. case Texture.PROJECTION_MODE:
  12603. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12604. this._projectionModeMatrix.m[0] = 0.5;
  12605. this._projectionModeMatrix.m[5] = -0.5;
  12606. this._projectionModeMatrix.m[10] = 0.0;
  12607. this._projectionModeMatrix.m[12] = 0.5;
  12608. this._projectionModeMatrix.m[13] = 0.5;
  12609. this._projectionModeMatrix.m[14] = 1.0;
  12610. this._projectionModeMatrix.m[15] = 1.0;
  12611. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12612. break;
  12613. default:
  12614. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12615. break;
  12616. }
  12617. return this._cachedTextureMatrix;
  12618. };
  12619. Texture.prototype.clone = function () {
  12620. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12621. // Base texture
  12622. newTexture.hasAlpha = this.hasAlpha;
  12623. newTexture.level = this.level;
  12624. newTexture.wrapU = this.wrapU;
  12625. newTexture.wrapV = this.wrapV;
  12626. newTexture.coordinatesIndex = this.coordinatesIndex;
  12627. newTexture.coordinatesMode = this.coordinatesMode;
  12628. // Texture
  12629. newTexture.uOffset = this.uOffset;
  12630. newTexture.vOffset = this.vOffset;
  12631. newTexture.uScale = this.uScale;
  12632. newTexture.vScale = this.vScale;
  12633. newTexture.uAng = this.uAng;
  12634. newTexture.vAng = this.vAng;
  12635. newTexture.wAng = this.wAng;
  12636. return newTexture;
  12637. };
  12638. // Statics
  12639. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12640. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12641. if (onLoad === void 0) { onLoad = null; }
  12642. if (onError === void 0) { onError = null; }
  12643. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12644. };
  12645. // Constants
  12646. Texture.NEAREST_SAMPLINGMODE = 1;
  12647. Texture.BILINEAR_SAMPLINGMODE = 2;
  12648. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12649. Texture.EXPLICIT_MODE = 0;
  12650. Texture.SPHERICAL_MODE = 1;
  12651. Texture.PLANAR_MODE = 2;
  12652. Texture.CUBIC_MODE = 3;
  12653. Texture.PROJECTION_MODE = 4;
  12654. Texture.SKYBOX_MODE = 5;
  12655. Texture.CLAMP_ADDRESSMODE = 0;
  12656. Texture.WRAP_ADDRESSMODE = 1;
  12657. Texture.MIRROR_ADDRESSMODE = 2;
  12658. return Texture;
  12659. })(BABYLON.BaseTexture);
  12660. BABYLON.Texture = Texture;
  12661. })(BABYLON || (BABYLON = {}));
  12662. //# sourceMappingURL=babylon.texture.js.map
  12663. var BABYLON;
  12664. (function (BABYLON) {
  12665. var CubeTexture = (function (_super) {
  12666. __extends(CubeTexture, _super);
  12667. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12668. _super.call(this, scene);
  12669. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12670. this.name = rootUrl;
  12671. this.url = rootUrl;
  12672. this._noMipmap = noMipmap;
  12673. this.hasAlpha = false;
  12674. this._texture = this._getFromCache(rootUrl, noMipmap);
  12675. if (!extensions) {
  12676. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12677. }
  12678. this._extensions = extensions;
  12679. if (!this._texture) {
  12680. if (!scene.useDelayedTextureLoading) {
  12681. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12682. }
  12683. else {
  12684. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12685. }
  12686. }
  12687. this.isCube = true;
  12688. this._textureMatrix = BABYLON.Matrix.Identity();
  12689. }
  12690. CubeTexture.prototype.clone = function () {
  12691. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12692. // Base texture
  12693. newTexture.level = this.level;
  12694. newTexture.wrapU = this.wrapU;
  12695. newTexture.wrapV = this.wrapV;
  12696. newTexture.coordinatesIndex = this.coordinatesIndex;
  12697. newTexture.coordinatesMode = this.coordinatesMode;
  12698. return newTexture;
  12699. };
  12700. // Methods
  12701. CubeTexture.prototype.delayLoad = function () {
  12702. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12703. return;
  12704. }
  12705. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12706. this._texture = this._getFromCache(this.url, this._noMipmap);
  12707. if (!this._texture) {
  12708. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12709. }
  12710. };
  12711. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12712. return this._textureMatrix;
  12713. };
  12714. return CubeTexture;
  12715. })(BABYLON.BaseTexture);
  12716. BABYLON.CubeTexture = CubeTexture;
  12717. })(BABYLON || (BABYLON = {}));
  12718. //# sourceMappingURL=babylon.cubeTexture.js.map
  12719. var BABYLON;
  12720. (function (BABYLON) {
  12721. var RenderTargetTexture = (function (_super) {
  12722. __extends(RenderTargetTexture, _super);
  12723. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12724. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12725. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12726. _super.call(this, null, scene, !generateMipMaps);
  12727. this.renderList = new Array();
  12728. this.renderParticles = true;
  12729. this.renderSprites = false;
  12730. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12731. this._currentRefreshId = -1;
  12732. this._refreshRate = 1;
  12733. this.name = name;
  12734. this.isRenderTarget = true;
  12735. this._size = size;
  12736. this._generateMipMaps = generateMipMaps;
  12737. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12738. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12739. // Rendering groups
  12740. this._renderingManager = new BABYLON.RenderingManager(scene);
  12741. }
  12742. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12743. this._currentRefreshId = -1;
  12744. };
  12745. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12746. get: function () {
  12747. return this._refreshRate;
  12748. },
  12749. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12750. set: function (value) {
  12751. this._refreshRate = value;
  12752. this.resetRefreshCounter();
  12753. },
  12754. enumerable: true,
  12755. configurable: true
  12756. });
  12757. RenderTargetTexture.prototype._shouldRender = function () {
  12758. if (this._currentRefreshId === -1) {
  12759. this._currentRefreshId = 1;
  12760. return true;
  12761. }
  12762. if (this.refreshRate === this._currentRefreshId) {
  12763. this._currentRefreshId = 1;
  12764. return true;
  12765. }
  12766. this._currentRefreshId++;
  12767. return false;
  12768. };
  12769. RenderTargetTexture.prototype.isReady = function () {
  12770. if (!this.getScene().renderTargetsEnabled) {
  12771. return false;
  12772. }
  12773. return _super.prototype.isReady.call(this);
  12774. };
  12775. RenderTargetTexture.prototype.getRenderSize = function () {
  12776. return this._size;
  12777. };
  12778. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12779. get: function () {
  12780. return true;
  12781. },
  12782. enumerable: true,
  12783. configurable: true
  12784. });
  12785. RenderTargetTexture.prototype.scale = function (ratio) {
  12786. var newSize = this._size * ratio;
  12787. this.resize(newSize, this._generateMipMaps);
  12788. };
  12789. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12790. this.releaseInternalTexture();
  12791. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12792. };
  12793. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12794. var scene = this.getScene();
  12795. var engine = scene.getEngine();
  12796. if (this._waitingRenderList) {
  12797. this.renderList = [];
  12798. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12799. var id = this._waitingRenderList[index];
  12800. this.renderList.push(scene.getMeshByID(id));
  12801. }
  12802. delete this._waitingRenderList;
  12803. }
  12804. if (this.renderList && this.renderList.length === 0) {
  12805. return;
  12806. }
  12807. // Bind
  12808. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12809. engine.bindFramebuffer(this._texture);
  12810. }
  12811. this._renderingManager.reset();
  12812. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12813. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12814. var mesh = currentRenderList[meshIndex];
  12815. if (mesh) {
  12816. if (!mesh.isReady()) {
  12817. // Reset _currentRefreshId
  12818. this.resetRefreshCounter();
  12819. continue;
  12820. }
  12821. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12822. mesh._activate(scene.getRenderId());
  12823. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12824. var subMesh = mesh.subMeshes[subIndex];
  12825. scene._activeVertices += subMesh.indexCount;
  12826. this._renderingManager.dispatch(subMesh);
  12827. }
  12828. }
  12829. }
  12830. }
  12831. if (this.onBeforeRender) {
  12832. this.onBeforeRender();
  12833. }
  12834. // Clear
  12835. if (this.onClear) {
  12836. this.onClear(engine);
  12837. }
  12838. else {
  12839. engine.clear(scene.clearColor, true, true);
  12840. }
  12841. if (!this._doNotChangeAspectRatio) {
  12842. scene.updateTransformMatrix(true);
  12843. }
  12844. // Render
  12845. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12846. if (useCameraPostProcess) {
  12847. scene.postProcessManager._finalizeFrame(false, this._texture);
  12848. }
  12849. if (!this._doNotChangeAspectRatio) {
  12850. scene.updateTransformMatrix(true);
  12851. }
  12852. if (this.onAfterRender) {
  12853. this.onAfterRender();
  12854. }
  12855. // Dump ?
  12856. if (dumpForDebug) {
  12857. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12858. }
  12859. // Unbind
  12860. engine.unBindFramebuffer(this._texture);
  12861. if (this.onAfterUnbind) {
  12862. this.onAfterUnbind();
  12863. }
  12864. };
  12865. RenderTargetTexture.prototype.clone = function () {
  12866. var textureSize = this.getSize();
  12867. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12868. // Base texture
  12869. newTexture.hasAlpha = this.hasAlpha;
  12870. newTexture.level = this.level;
  12871. // RenderTarget Texture
  12872. newTexture.coordinatesMode = this.coordinatesMode;
  12873. newTexture.renderList = this.renderList.slice(0);
  12874. return newTexture;
  12875. };
  12876. return RenderTargetTexture;
  12877. })(BABYLON.Texture);
  12878. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12879. })(BABYLON || (BABYLON = {}));
  12880. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12881. var BABYLON;
  12882. (function (BABYLON) {
  12883. var ProceduralTexture = (function (_super) {
  12884. __extends(ProceduralTexture, _super);
  12885. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12886. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12887. _super.call(this, null, scene, !generateMipMaps);
  12888. this._currentRefreshId = -1;
  12889. this._refreshRate = 1;
  12890. this._vertexDeclaration = [2];
  12891. this._vertexStrideSize = 2 * 4;
  12892. this._uniforms = new Array();
  12893. this._samplers = new Array();
  12894. this._textures = new Array();
  12895. this._floats = new Array();
  12896. this._floatsArrays = {};
  12897. this._colors3 = new Array();
  12898. this._colors4 = new Array();
  12899. this._vectors2 = new Array();
  12900. this._vectors3 = new Array();
  12901. this._matrices = new Array();
  12902. this._fallbackTextureUsed = false;
  12903. scene._proceduralTextures.push(this);
  12904. this.name = name;
  12905. this.isRenderTarget = true;
  12906. this._size = size;
  12907. this._generateMipMaps = generateMipMaps;
  12908. this.setFragment(fragment);
  12909. this._fallbackTexture = fallbackTexture;
  12910. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12911. // VBO
  12912. var vertices = [];
  12913. vertices.push(1, 1);
  12914. vertices.push(-1, 1);
  12915. vertices.push(-1, -1);
  12916. vertices.push(1, -1);
  12917. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12918. // Indices
  12919. var indices = [];
  12920. indices.push(0);
  12921. indices.push(1);
  12922. indices.push(2);
  12923. indices.push(0);
  12924. indices.push(2);
  12925. indices.push(3);
  12926. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12927. }
  12928. ProceduralTexture.prototype.reset = function () {
  12929. if (this._effect === undefined) {
  12930. return;
  12931. }
  12932. var engine = this.getScene().getEngine();
  12933. engine._releaseEffect(this._effect);
  12934. };
  12935. ProceduralTexture.prototype.isReady = function () {
  12936. var _this = this;
  12937. var engine = this.getScene().getEngine();
  12938. var shaders;
  12939. if (!this._fragment) {
  12940. return false;
  12941. }
  12942. if (this._fallbackTextureUsed) {
  12943. return true;
  12944. }
  12945. if (this._fragment.fragmentElement !== undefined) {
  12946. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12947. }
  12948. else {
  12949. shaders = { vertex: "procedural", fragment: this._fragment };
  12950. }
  12951. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12952. _this.releaseInternalTexture();
  12953. if (_this._fallbackTexture) {
  12954. _this._texture = _this._fallbackTexture._texture;
  12955. _this._texture.references++;
  12956. }
  12957. _this._fallbackTextureUsed = true;
  12958. });
  12959. return this._effect.isReady();
  12960. };
  12961. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12962. this._currentRefreshId = -1;
  12963. };
  12964. ProceduralTexture.prototype.setFragment = function (fragment) {
  12965. this._fragment = fragment;
  12966. };
  12967. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12968. get: function () {
  12969. return this._refreshRate;
  12970. },
  12971. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12972. set: function (value) {
  12973. this._refreshRate = value;
  12974. this.resetRefreshCounter();
  12975. },
  12976. enumerable: true,
  12977. configurable: true
  12978. });
  12979. ProceduralTexture.prototype._shouldRender = function () {
  12980. if (!this.isReady() || !this._texture) {
  12981. return false;
  12982. }
  12983. if (this._fallbackTextureUsed) {
  12984. return false;
  12985. }
  12986. if (this._currentRefreshId === -1) {
  12987. this._currentRefreshId = 1;
  12988. return true;
  12989. }
  12990. if (this.refreshRate === this._currentRefreshId) {
  12991. this._currentRefreshId = 1;
  12992. return true;
  12993. }
  12994. this._currentRefreshId++;
  12995. return false;
  12996. };
  12997. ProceduralTexture.prototype.getRenderSize = function () {
  12998. return this._size;
  12999. };
  13000. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13001. if (this._fallbackTextureUsed) {
  13002. return;
  13003. }
  13004. this.releaseInternalTexture();
  13005. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13006. };
  13007. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13008. if (this._uniforms.indexOf(uniformName) === -1) {
  13009. this._uniforms.push(uniformName);
  13010. }
  13011. };
  13012. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13013. if (this._samplers.indexOf(name) === -1) {
  13014. this._samplers.push(name);
  13015. }
  13016. this._textures[name] = texture;
  13017. return this;
  13018. };
  13019. ProceduralTexture.prototype.setFloat = function (name, value) {
  13020. this._checkUniform(name);
  13021. this._floats[name] = value;
  13022. return this;
  13023. };
  13024. ProceduralTexture.prototype.setFloats = function (name, value) {
  13025. this._checkUniform(name);
  13026. this._floatsArrays[name] = value;
  13027. return this;
  13028. };
  13029. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13030. this._checkUniform(name);
  13031. this._colors3[name] = value;
  13032. return this;
  13033. };
  13034. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13035. this._checkUniform(name);
  13036. this._colors4[name] = value;
  13037. return this;
  13038. };
  13039. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13040. this._checkUniform(name);
  13041. this._vectors2[name] = value;
  13042. return this;
  13043. };
  13044. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13045. this._checkUniform(name);
  13046. this._vectors3[name] = value;
  13047. return this;
  13048. };
  13049. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13050. this._checkUniform(name);
  13051. this._matrices[name] = value;
  13052. return this;
  13053. };
  13054. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13055. var scene = this.getScene();
  13056. var engine = scene.getEngine();
  13057. engine.bindFramebuffer(this._texture);
  13058. // Clear
  13059. engine.clear(scene.clearColor, true, true);
  13060. // Render
  13061. engine.enableEffect(this._effect);
  13062. engine.setState(false);
  13063. for (var name in this._textures) {
  13064. this._effect.setTexture(name, this._textures[name]);
  13065. }
  13066. for (name in this._floats) {
  13067. this._effect.setFloat(name, this._floats[name]);
  13068. }
  13069. for (name in this._floatsArrays) {
  13070. this._effect.setArray(name, this._floatsArrays[name]);
  13071. }
  13072. for (name in this._colors3) {
  13073. this._effect.setColor3(name, this._colors3[name]);
  13074. }
  13075. for (name in this._colors4) {
  13076. var color = this._colors4[name];
  13077. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13078. }
  13079. for (name in this._vectors2) {
  13080. this._effect.setVector2(name, this._vectors2[name]);
  13081. }
  13082. for (name in this._vectors3) {
  13083. this._effect.setVector3(name, this._vectors3[name]);
  13084. }
  13085. for (name in this._matrices) {
  13086. this._effect.setMatrix(name, this._matrices[name]);
  13087. }
  13088. // VBOs
  13089. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13090. // Draw order
  13091. engine.draw(true, 0, 6);
  13092. // Unbind
  13093. engine.unBindFramebuffer(this._texture);
  13094. };
  13095. ProceduralTexture.prototype.clone = function () {
  13096. var textureSize = this.getSize();
  13097. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13098. // Base texture
  13099. newTexture.hasAlpha = this.hasAlpha;
  13100. newTexture.level = this.level;
  13101. // RenderTarget Texture
  13102. newTexture.coordinatesMode = this.coordinatesMode;
  13103. return newTexture;
  13104. };
  13105. ProceduralTexture.prototype.dispose = function () {
  13106. var index = this.getScene()._proceduralTextures.indexOf(this);
  13107. if (index >= 0) {
  13108. this.getScene()._proceduralTextures.splice(index, 1);
  13109. }
  13110. _super.prototype.dispose.call(this);
  13111. };
  13112. return ProceduralTexture;
  13113. })(BABYLON.Texture);
  13114. BABYLON.ProceduralTexture = ProceduralTexture;
  13115. })(BABYLON || (BABYLON = {}));
  13116. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13117. var BABYLON;
  13118. (function (BABYLON) {
  13119. var WoodProceduralTexture = (function (_super) {
  13120. __extends(WoodProceduralTexture, _super);
  13121. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13122. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13123. this._ampScale = 100.0;
  13124. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13125. this.updateShaderUniforms();
  13126. this.refreshRate = 0;
  13127. }
  13128. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13129. this.setFloat("ampScale", this._ampScale);
  13130. this.setColor3("woodColor", this._woodColor);
  13131. };
  13132. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13133. get: function () {
  13134. return this._ampScale;
  13135. },
  13136. set: function (value) {
  13137. this._ampScale = value;
  13138. this.updateShaderUniforms();
  13139. },
  13140. enumerable: true,
  13141. configurable: true
  13142. });
  13143. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13144. get: function () {
  13145. return this._woodColor;
  13146. },
  13147. set: function (value) {
  13148. this._woodColor = value;
  13149. this.updateShaderUniforms();
  13150. },
  13151. enumerable: true,
  13152. configurable: true
  13153. });
  13154. return WoodProceduralTexture;
  13155. })(BABYLON.ProceduralTexture);
  13156. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13157. var FireProceduralTexture = (function (_super) {
  13158. __extends(FireProceduralTexture, _super);
  13159. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13160. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13161. this._time = 0.0;
  13162. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13163. this._shift = 1.6;
  13164. this._autoGenerateTime = true;
  13165. this._alphaThreshold = 0.5;
  13166. this._fireColors = FireProceduralTexture.RedFireColors;
  13167. this.updateShaderUniforms();
  13168. this.refreshRate = 1;
  13169. }
  13170. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13171. this.setFloat("time", this._time);
  13172. this.setVector2("speed", this._speed);
  13173. this.setFloat("shift", this._shift);
  13174. this.setColor3("c1", this._fireColors[0]);
  13175. this.setColor3("c2", this._fireColors[1]);
  13176. this.setColor3("c3", this._fireColors[2]);
  13177. this.setColor3("c4", this._fireColors[3]);
  13178. this.setColor3("c5", this._fireColors[4]);
  13179. this.setColor3("c6", this._fireColors[5]);
  13180. this.setFloat("alphaThreshold", this._alphaThreshold);
  13181. };
  13182. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13183. if (this._autoGenerateTime) {
  13184. this._time += this.getScene().getAnimationRatio() * 0.03;
  13185. this.updateShaderUniforms();
  13186. }
  13187. _super.prototype.render.call(this, useCameraPostProcess);
  13188. };
  13189. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13190. get: function () {
  13191. return [
  13192. new BABYLON.Color3(0.5, 0.0, 1.0),
  13193. new BABYLON.Color3(0.9, 0.0, 1.0),
  13194. new BABYLON.Color3(0.2, 0.0, 1.0),
  13195. new BABYLON.Color3(1.0, 0.9, 1.0),
  13196. new BABYLON.Color3(0.1, 0.1, 1.0),
  13197. new BABYLON.Color3(0.9, 0.9, 1.0)
  13198. ];
  13199. },
  13200. enumerable: true,
  13201. configurable: true
  13202. });
  13203. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13204. get: function () {
  13205. return [
  13206. new BABYLON.Color3(0.5, 1.0, 0.0),
  13207. new BABYLON.Color3(0.5, 1.0, 0.0),
  13208. new BABYLON.Color3(0.3, 0.4, 0.0),
  13209. new BABYLON.Color3(0.5, 1.0, 0.0),
  13210. new BABYLON.Color3(0.2, 0.0, 0.0),
  13211. new BABYLON.Color3(0.5, 1.0, 0.0)
  13212. ];
  13213. },
  13214. enumerable: true,
  13215. configurable: true
  13216. });
  13217. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13218. get: function () {
  13219. return [
  13220. new BABYLON.Color3(0.5, 0.0, 0.1),
  13221. new BABYLON.Color3(0.9, 0.0, 0.0),
  13222. new BABYLON.Color3(0.2, 0.0, 0.0),
  13223. new BABYLON.Color3(1.0, 0.9, 0.0),
  13224. new BABYLON.Color3(0.1, 0.1, 0.1),
  13225. new BABYLON.Color3(0.9, 0.9, 0.9)
  13226. ];
  13227. },
  13228. enumerable: true,
  13229. configurable: true
  13230. });
  13231. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13232. get: function () {
  13233. return [
  13234. new BABYLON.Color3(0.1, 0.0, 0.5),
  13235. new BABYLON.Color3(0.0, 0.0, 0.5),
  13236. new BABYLON.Color3(0.1, 0.0, 0.2),
  13237. new BABYLON.Color3(0.0, 0.0, 1.0),
  13238. new BABYLON.Color3(0.1, 0.2, 0.3),
  13239. new BABYLON.Color3(0.0, 0.2, 0.9)
  13240. ];
  13241. },
  13242. enumerable: true,
  13243. configurable: true
  13244. });
  13245. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13246. get: function () {
  13247. return this._fireColors;
  13248. },
  13249. set: function (value) {
  13250. this._fireColors = value;
  13251. this.updateShaderUniforms();
  13252. },
  13253. enumerable: true,
  13254. configurable: true
  13255. });
  13256. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13257. get: function () {
  13258. return this._time;
  13259. },
  13260. set: function (value) {
  13261. this._time = value;
  13262. this.updateShaderUniforms();
  13263. },
  13264. enumerable: true,
  13265. configurable: true
  13266. });
  13267. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13268. get: function () {
  13269. return this._speed;
  13270. },
  13271. set: function (value) {
  13272. this._speed = value;
  13273. this.updateShaderUniforms();
  13274. },
  13275. enumerable: true,
  13276. configurable: true
  13277. });
  13278. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  13279. get: function () {
  13280. return this._shift;
  13281. },
  13282. set: function (value) {
  13283. this._shift = value;
  13284. this.updateShaderUniforms();
  13285. },
  13286. enumerable: true,
  13287. configurable: true
  13288. });
  13289. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13290. get: function () {
  13291. return this._alphaThreshold;
  13292. },
  13293. set: function (value) {
  13294. this._alphaThreshold = value;
  13295. this.updateShaderUniforms();
  13296. },
  13297. enumerable: true,
  13298. configurable: true
  13299. });
  13300. return FireProceduralTexture;
  13301. })(BABYLON.ProceduralTexture);
  13302. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13303. var CloudProceduralTexture = (function (_super) {
  13304. __extends(CloudProceduralTexture, _super);
  13305. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13306. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13307. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13308. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13309. this.updateShaderUniforms();
  13310. this.refreshRate = 0;
  13311. }
  13312. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13313. this.setColor3("skyColor", this._skyColor);
  13314. this.setColor3("cloudColor", this._cloudColor);
  13315. };
  13316. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13317. get: function () {
  13318. return this._skyColor;
  13319. },
  13320. set: function (value) {
  13321. this._skyColor = value;
  13322. this.updateShaderUniforms();
  13323. },
  13324. enumerable: true,
  13325. configurable: true
  13326. });
  13327. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13328. get: function () {
  13329. return this._cloudColor;
  13330. },
  13331. set: function (value) {
  13332. this._cloudColor = value;
  13333. this.updateShaderUniforms();
  13334. },
  13335. enumerable: true,
  13336. configurable: true
  13337. });
  13338. return CloudProceduralTexture;
  13339. })(BABYLON.ProceduralTexture);
  13340. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13341. var GrassProceduralTexture = (function (_super) {
  13342. __extends(GrassProceduralTexture, _super);
  13343. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13344. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13345. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13346. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13347. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13348. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13349. this._grassColors = [
  13350. new BABYLON.Color3(0.29, 0.38, 0.02),
  13351. new BABYLON.Color3(0.36, 0.49, 0.09),
  13352. new BABYLON.Color3(0.51, 0.6, 0.28)
  13353. ];
  13354. this.updateShaderUniforms();
  13355. this.refreshRate = 0;
  13356. }
  13357. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13358. this.setColor3("herb1Color", this._grassColors[0]);
  13359. this.setColor3("herb2Color", this._grassColors[1]);
  13360. this.setColor3("herb3Color", this._grassColors[2]);
  13361. this.setColor3("groundColor", this._groundColor);
  13362. };
  13363. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13364. get: function () {
  13365. return this._grassColors;
  13366. },
  13367. set: function (value) {
  13368. this._grassColors = value;
  13369. this.updateShaderUniforms();
  13370. },
  13371. enumerable: true,
  13372. configurable: true
  13373. });
  13374. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13375. get: function () {
  13376. return this._groundColor;
  13377. },
  13378. set: function (value) {
  13379. this.groundColor = value;
  13380. this.updateShaderUniforms();
  13381. },
  13382. enumerable: true,
  13383. configurable: true
  13384. });
  13385. return GrassProceduralTexture;
  13386. })(BABYLON.ProceduralTexture);
  13387. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13388. var RoadProceduralTexture = (function (_super) {
  13389. __extends(RoadProceduralTexture, _super);
  13390. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13391. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13392. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13393. this.updateShaderUniforms();
  13394. this.refreshRate = 0;
  13395. }
  13396. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13397. this.setColor3("roadColor", this._roadColor);
  13398. };
  13399. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13400. get: function () {
  13401. return this._roadColor;
  13402. },
  13403. set: function (value) {
  13404. this._roadColor = value;
  13405. this.updateShaderUniforms();
  13406. },
  13407. enumerable: true,
  13408. configurable: true
  13409. });
  13410. return RoadProceduralTexture;
  13411. })(BABYLON.ProceduralTexture);
  13412. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13413. var BrickProceduralTexture = (function (_super) {
  13414. __extends(BrickProceduralTexture, _super);
  13415. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13416. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13417. this._numberOfBricksHeight = 15;
  13418. this._numberOfBricksWidth = 5;
  13419. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13420. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13421. this.updateShaderUniforms();
  13422. this.refreshRate = 0;
  13423. }
  13424. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13425. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13426. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13427. this.setColor3("brickColor", this._brickColor);
  13428. this.setColor3("jointColor", this._jointColor);
  13429. };
  13430. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13431. get: function () {
  13432. return this._numberOfBricksHeight;
  13433. },
  13434. set: function (value) {
  13435. this._numberOfBricksHeight = value;
  13436. this.updateShaderUniforms();
  13437. },
  13438. enumerable: true,
  13439. configurable: true
  13440. });
  13441. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13442. get: function () {
  13443. return this._numberOfBricksWidth;
  13444. },
  13445. set: function (value) {
  13446. this._numberOfBricksHeight = value;
  13447. this.updateShaderUniforms();
  13448. },
  13449. enumerable: true,
  13450. configurable: true
  13451. });
  13452. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13453. get: function () {
  13454. return this._jointColor;
  13455. },
  13456. set: function (value) {
  13457. this._jointColor = value;
  13458. this.updateShaderUniforms();
  13459. },
  13460. enumerable: true,
  13461. configurable: true
  13462. });
  13463. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13464. get: function () {
  13465. return this._brickColor;
  13466. },
  13467. set: function (value) {
  13468. this._brickColor = value;
  13469. this.updateShaderUniforms();
  13470. },
  13471. enumerable: true,
  13472. configurable: true
  13473. });
  13474. return BrickProceduralTexture;
  13475. })(BABYLON.ProceduralTexture);
  13476. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13477. var MarbleProceduralTexture = (function (_super) {
  13478. __extends(MarbleProceduralTexture, _super);
  13479. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13480. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13481. this._numberOfTilesHeight = 3;
  13482. this._numberOfTilesWidth = 3;
  13483. this._amplitude = 9.0;
  13484. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13485. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13486. this.updateShaderUniforms();
  13487. this.refreshRate = 0;
  13488. }
  13489. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13490. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13491. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13492. this.setFloat("amplitude", this._amplitude);
  13493. this.setColor3("marbleColor", this._marbleColor);
  13494. this.setColor3("jointColor", this._jointColor);
  13495. };
  13496. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13497. get: function () {
  13498. return this._numberOfTilesHeight;
  13499. },
  13500. set: function (value) {
  13501. this._numberOfTilesHeight = value;
  13502. this.updateShaderUniforms();
  13503. },
  13504. enumerable: true,
  13505. configurable: true
  13506. });
  13507. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13508. get: function () {
  13509. return this._numberOfTilesWidth;
  13510. },
  13511. set: function (value) {
  13512. this._numberOfTilesWidth = value;
  13513. this.updateShaderUniforms();
  13514. },
  13515. enumerable: true,
  13516. configurable: true
  13517. });
  13518. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13519. get: function () {
  13520. return this._jointColor;
  13521. },
  13522. set: function (value) {
  13523. this._jointColor = value;
  13524. this.updateShaderUniforms();
  13525. },
  13526. enumerable: true,
  13527. configurable: true
  13528. });
  13529. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13530. get: function () {
  13531. return this._marbleColor;
  13532. },
  13533. set: function (value) {
  13534. this._marbleColor = value;
  13535. this.updateShaderUniforms();
  13536. },
  13537. enumerable: true,
  13538. configurable: true
  13539. });
  13540. return MarbleProceduralTexture;
  13541. })(BABYLON.ProceduralTexture);
  13542. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13543. })(BABYLON || (BABYLON = {}));
  13544. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13545. var BABYLON;
  13546. (function (BABYLON) {
  13547. var CustomProceduralTexture = (function (_super) {
  13548. __extends(CustomProceduralTexture, _super);
  13549. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13550. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13551. this._animate = true;
  13552. this._time = 0;
  13553. this._texturePath = texturePath;
  13554. //Try to load json
  13555. this.loadJson(texturePath);
  13556. this.refreshRate = 1;
  13557. }
  13558. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13559. var _this = this;
  13560. var that = this;
  13561. function noConfigFile() {
  13562. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13563. try {
  13564. that.setFragment(that._texturePath);
  13565. }
  13566. catch (ex) {
  13567. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13568. }
  13569. }
  13570. var configFileUrl = jsonUrl + "/config.json";
  13571. var xhr = new XMLHttpRequest();
  13572. xhr.open("GET", configFileUrl, true);
  13573. xhr.addEventListener("load", function () {
  13574. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13575. try {
  13576. _this._config = JSON.parse(xhr.response);
  13577. _this.updateShaderUniforms();
  13578. _this.updateTextures();
  13579. _this.setFragment(_this._texturePath + "/custom");
  13580. _this._animate = _this._config.animate;
  13581. _this.refreshRate = _this._config.refreshrate;
  13582. }
  13583. catch (ex) {
  13584. noConfigFile();
  13585. }
  13586. }
  13587. else {
  13588. noConfigFile();
  13589. }
  13590. }, false);
  13591. xhr.addEventListener("error", function () {
  13592. noConfigFile();
  13593. }, false);
  13594. try {
  13595. xhr.send();
  13596. }
  13597. catch (ex) {
  13598. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13599. }
  13600. };
  13601. CustomProceduralTexture.prototype.isReady = function () {
  13602. if (!_super.prototype.isReady.call(this)) {
  13603. return false;
  13604. }
  13605. for (var name in this._textures) {
  13606. var texture = this._textures[name];
  13607. if (!texture.isReady()) {
  13608. return false;
  13609. }
  13610. }
  13611. return true;
  13612. };
  13613. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13614. if (this._animate) {
  13615. this._time += this.getScene().getAnimationRatio() * 0.03;
  13616. this.updateShaderUniforms();
  13617. }
  13618. _super.prototype.render.call(this, useCameraPostProcess);
  13619. };
  13620. CustomProceduralTexture.prototype.updateTextures = function () {
  13621. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13622. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13623. }
  13624. };
  13625. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13626. if (this._config) {
  13627. for (var j = 0; j < this._config.uniforms.length; j++) {
  13628. var uniform = this._config.uniforms[j];
  13629. switch (uniform.type) {
  13630. case "float":
  13631. this.setFloat(uniform.name, uniform.value);
  13632. break;
  13633. case "color3":
  13634. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13635. break;
  13636. case "color4":
  13637. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13638. break;
  13639. case "vector2":
  13640. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13641. break;
  13642. case "vector3":
  13643. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13644. break;
  13645. }
  13646. }
  13647. }
  13648. this.setFloat("time", this._time);
  13649. };
  13650. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13651. get: function () {
  13652. return this._animate;
  13653. },
  13654. set: function (value) {
  13655. this._animate = value;
  13656. },
  13657. enumerable: true,
  13658. configurable: true
  13659. });
  13660. return CustomProceduralTexture;
  13661. })(BABYLON.ProceduralTexture);
  13662. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13663. })(BABYLON || (BABYLON = {}));
  13664. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13665. var BABYLON;
  13666. (function (BABYLON) {
  13667. var MirrorTexture = (function (_super) {
  13668. __extends(MirrorTexture, _super);
  13669. function MirrorTexture(name, size, scene, generateMipMaps) {
  13670. var _this = this;
  13671. _super.call(this, name, size, scene, generateMipMaps, true);
  13672. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13673. this._transformMatrix = BABYLON.Matrix.Zero();
  13674. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13675. this.onBeforeRender = function () {
  13676. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13677. _this._savedViewMatrix = scene.getViewMatrix();
  13678. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13679. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13680. scene.clipPlane = _this.mirrorPlane;
  13681. scene.getEngine().cullBackFaces = false;
  13682. };
  13683. this.onAfterRender = function () {
  13684. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13685. scene.getEngine().cullBackFaces = true;
  13686. delete scene.clipPlane;
  13687. };
  13688. }
  13689. MirrorTexture.prototype.clone = function () {
  13690. var textureSize = this.getSize();
  13691. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13692. // Base texture
  13693. newTexture.hasAlpha = this.hasAlpha;
  13694. newTexture.level = this.level;
  13695. // Mirror Texture
  13696. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13697. newTexture.renderList = this.renderList.slice(0);
  13698. return newTexture;
  13699. };
  13700. return MirrorTexture;
  13701. })(BABYLON.RenderTargetTexture);
  13702. BABYLON.MirrorTexture = MirrorTexture;
  13703. })(BABYLON || (BABYLON = {}));
  13704. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13705. var BABYLON;
  13706. (function (BABYLON) {
  13707. var DynamicTexture = (function (_super) {
  13708. __extends(DynamicTexture, _super);
  13709. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13710. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13711. _super.call(this, null, scene, !generateMipMaps);
  13712. this.name = name;
  13713. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13714. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13715. this._generateMipMaps = generateMipMaps;
  13716. if (options.getContext) {
  13717. this._canvas = options;
  13718. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13719. }
  13720. else {
  13721. this._canvas = document.createElement("canvas");
  13722. if (options.width) {
  13723. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13724. }
  13725. else {
  13726. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13727. }
  13728. }
  13729. var textureSize = this.getSize();
  13730. this._canvas.width = textureSize.width;
  13731. this._canvas.height = textureSize.height;
  13732. this._context = this._canvas.getContext("2d");
  13733. }
  13734. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13735. get: function () {
  13736. return true;
  13737. },
  13738. enumerable: true,
  13739. configurable: true
  13740. });
  13741. DynamicTexture.prototype.scale = function (ratio) {
  13742. var textureSize = this.getSize();
  13743. textureSize.width *= ratio;
  13744. textureSize.height *= ratio;
  13745. this._canvas.width = textureSize.width;
  13746. this._canvas.height = textureSize.height;
  13747. this.releaseInternalTexture();
  13748. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13749. };
  13750. DynamicTexture.prototype.getContext = function () {
  13751. return this._context;
  13752. };
  13753. DynamicTexture.prototype.clear = function () {
  13754. var size = this.getSize();
  13755. this._context.fillRect(0, 0, size.width, size.height);
  13756. };
  13757. DynamicTexture.prototype.update = function (invertY) {
  13758. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13759. };
  13760. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13761. if (update === void 0) { update = true; }
  13762. var size = this.getSize();
  13763. if (clearColor) {
  13764. this._context.fillStyle = clearColor;
  13765. this._context.fillRect(0, 0, size.width, size.height);
  13766. }
  13767. this._context.font = font;
  13768. if (x === null) {
  13769. var textSize = this._context.measureText(text);
  13770. x = (size.width - textSize.width) / 2;
  13771. }
  13772. this._context.fillStyle = color;
  13773. this._context.fillText(text, x, y);
  13774. if (update) {
  13775. this.update(invertY);
  13776. }
  13777. };
  13778. DynamicTexture.prototype.clone = function () {
  13779. var textureSize = this.getSize();
  13780. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13781. // Base texture
  13782. newTexture.hasAlpha = this.hasAlpha;
  13783. newTexture.level = this.level;
  13784. // Dynamic Texture
  13785. newTexture.wrapU = this.wrapU;
  13786. newTexture.wrapV = this.wrapV;
  13787. return newTexture;
  13788. };
  13789. return DynamicTexture;
  13790. })(BABYLON.Texture);
  13791. BABYLON.DynamicTexture = DynamicTexture;
  13792. })(BABYLON || (BABYLON = {}));
  13793. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13794. var BABYLON;
  13795. (function (BABYLON) {
  13796. var VideoTexture = (function (_super) {
  13797. __extends(VideoTexture, _super);
  13798. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13799. var _this = this;
  13800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13801. _super.call(this, null, scene, !generateMipMaps, invertY);
  13802. this._autoLaunch = true;
  13803. this.name = name;
  13804. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13805. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13806. var requiredWidth = size.width || size;
  13807. var requiredHeight = size.height || size;
  13808. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13809. var textureSize = this.getSize();
  13810. this.video = document.createElement("video");
  13811. this.video.width = textureSize.width;
  13812. this.video.height = textureSize.height;
  13813. this.video.autoplay = false;
  13814. this.video.loop = true;
  13815. this.video.addEventListener("canplaythrough", function () {
  13816. if (_this._texture) {
  13817. _this._texture.isReady = true;
  13818. }
  13819. });
  13820. urls.forEach(function (url) {
  13821. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13822. var source = document.createElement("source");
  13823. source.src = url;
  13824. _this.video.appendChild(source);
  13825. });
  13826. this._lastUpdate = BABYLON.Tools.Now;
  13827. }
  13828. VideoTexture.prototype.update = function () {
  13829. if (this._autoLaunch) {
  13830. this._autoLaunch = false;
  13831. this.video.play();
  13832. }
  13833. var now = BABYLON.Tools.Now;
  13834. if (now - this._lastUpdate < 15) {
  13835. return false;
  13836. }
  13837. this._lastUpdate = now;
  13838. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13839. return true;
  13840. };
  13841. return VideoTexture;
  13842. })(BABYLON.Texture);
  13843. BABYLON.VideoTexture = VideoTexture;
  13844. })(BABYLON || (BABYLON = {}));
  13845. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13846. (function (BABYLON) {
  13847. var EffectFallbacks = (function () {
  13848. function EffectFallbacks() {
  13849. this._defines = {};
  13850. this._currentRank = 32;
  13851. this._maxRank = -1;
  13852. }
  13853. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13854. if (!this._defines[rank]) {
  13855. if (rank < this._currentRank) {
  13856. this._currentRank = rank;
  13857. }
  13858. if (rank > this._maxRank) {
  13859. this._maxRank = rank;
  13860. }
  13861. this._defines[rank] = new Array();
  13862. }
  13863. this._defines[rank].push(define);
  13864. };
  13865. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13866. get: function () {
  13867. return this._currentRank <= this._maxRank;
  13868. },
  13869. enumerable: true,
  13870. configurable: true
  13871. });
  13872. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13873. var currentFallbacks = this._defines[this._currentRank];
  13874. for (var index = 0; index < currentFallbacks.length; index++) {
  13875. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13876. }
  13877. this._currentRank++;
  13878. return currentDefines;
  13879. };
  13880. return EffectFallbacks;
  13881. })();
  13882. BABYLON.EffectFallbacks = EffectFallbacks;
  13883. var Effect = (function () {
  13884. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13885. var _this = this;
  13886. this._isReady = false;
  13887. this._compilationError = "";
  13888. this._valueCache = [];
  13889. this._engine = engine;
  13890. this.name = baseName;
  13891. this.defines = defines;
  13892. this._uniformsNames = uniformsNames.concat(samplers);
  13893. this._samplers = samplers;
  13894. this._attributesNames = attributesNames;
  13895. this.onError = onError;
  13896. this.onCompiled = onCompiled;
  13897. var vertexSource;
  13898. var fragmentSource;
  13899. if (baseName.vertexElement) {
  13900. vertexSource = document.getElementById(baseName.vertexElement);
  13901. if (!vertexSource) {
  13902. vertexSource = baseName.vertexElement;
  13903. }
  13904. }
  13905. else {
  13906. vertexSource = baseName.vertex || baseName;
  13907. }
  13908. if (baseName.fragmentElement) {
  13909. fragmentSource = document.getElementById(baseName.fragmentElement);
  13910. if (!fragmentSource) {
  13911. fragmentSource = baseName.fragmentElement;
  13912. }
  13913. }
  13914. else {
  13915. fragmentSource = baseName.fragment || baseName;
  13916. }
  13917. this._loadVertexShader(vertexSource, function (vertexCode) {
  13918. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13919. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13920. });
  13921. });
  13922. }
  13923. // Properties
  13924. Effect.prototype.isReady = function () {
  13925. return this._isReady;
  13926. };
  13927. Effect.prototype.getProgram = function () {
  13928. return this._program;
  13929. };
  13930. Effect.prototype.getAttributesNames = function () {
  13931. return this._attributesNames;
  13932. };
  13933. Effect.prototype.getAttributeLocation = function (index) {
  13934. return this._attributes[index];
  13935. };
  13936. Effect.prototype.getAttributeLocationByName = function (name) {
  13937. var index = this._attributesNames.indexOf(name);
  13938. return this._attributes[index];
  13939. };
  13940. Effect.prototype.getAttributesCount = function () {
  13941. return this._attributes.length;
  13942. };
  13943. Effect.prototype.getUniformIndex = function (uniformName) {
  13944. return this._uniformsNames.indexOf(uniformName);
  13945. };
  13946. Effect.prototype.getUniform = function (uniformName) {
  13947. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13948. };
  13949. Effect.prototype.getSamplers = function () {
  13950. return this._samplers;
  13951. };
  13952. Effect.prototype.getCompilationError = function () {
  13953. return this._compilationError;
  13954. };
  13955. // Methods
  13956. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13957. // DOM element ?
  13958. if (vertex instanceof HTMLElement) {
  13959. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13960. callback(vertexCode);
  13961. return;
  13962. }
  13963. // Is in local store ?
  13964. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13965. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13966. return;
  13967. }
  13968. var vertexShaderUrl;
  13969. if (vertex[0] === ".") {
  13970. vertexShaderUrl = vertex;
  13971. }
  13972. else {
  13973. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13974. }
  13975. // Vertex shader
  13976. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13977. };
  13978. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13979. // DOM element ?
  13980. if (fragment instanceof HTMLElement) {
  13981. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13982. callback(fragmentCode);
  13983. return;
  13984. }
  13985. // Is in local store ?
  13986. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13987. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13988. return;
  13989. }
  13990. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13991. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13992. return;
  13993. }
  13994. var fragmentShaderUrl;
  13995. if (fragment[0] === ".") {
  13996. fragmentShaderUrl = fragment;
  13997. }
  13998. else {
  13999. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14000. }
  14001. // Fragment shader
  14002. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14003. };
  14004. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14005. try {
  14006. var engine = this._engine;
  14007. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14008. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14009. this._attributes = engine.getAttributes(this._program, attributesNames);
  14010. for (var index = 0; index < this._samplers.length; index++) {
  14011. var sampler = this.getUniform(this._samplers[index]);
  14012. if (sampler == null) {
  14013. this._samplers.splice(index, 1);
  14014. index--;
  14015. }
  14016. }
  14017. engine.bindSamplers(this);
  14018. this._isReady = true;
  14019. if (this.onCompiled) {
  14020. this.onCompiled(this);
  14021. }
  14022. }
  14023. catch (e) {
  14024. // Is it a problem with precision?
  14025. if (e.message.indexOf("highp") !== -1) {
  14026. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14027. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14028. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14029. return;
  14030. }
  14031. // Let's go through fallbacks then
  14032. if (fallbacks && fallbacks.isMoreFallbacks) {
  14033. defines = fallbacks.reduce(defines);
  14034. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14035. }
  14036. else {
  14037. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14038. BABYLON.Tools.Error("Defines: " + defines);
  14039. BABYLON.Tools.Error("Error: " + e.message);
  14040. this._compilationError = e.message;
  14041. if (this.onError) {
  14042. this.onError(this, this._compilationError);
  14043. }
  14044. }
  14045. }
  14046. };
  14047. Effect.prototype._bindTexture = function (channel, texture) {
  14048. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14049. };
  14050. Effect.prototype.setTexture = function (channel, texture) {
  14051. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14052. };
  14053. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14054. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14055. };
  14056. //public _cacheMatrix(uniformName, matrix) {
  14057. // if (!this._valueCache[uniformName]) {
  14058. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14059. // }
  14060. // for (var index = 0; index < 16; index++) {
  14061. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14062. // }
  14063. //};
  14064. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14065. if (!this._valueCache[uniformName]) {
  14066. this._valueCache[uniformName] = [x, y];
  14067. return;
  14068. }
  14069. this._valueCache[uniformName][0] = x;
  14070. this._valueCache[uniformName][1] = y;
  14071. };
  14072. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14073. if (!this._valueCache[uniformName]) {
  14074. this._valueCache[uniformName] = [x, y, z];
  14075. return;
  14076. }
  14077. this._valueCache[uniformName][0] = x;
  14078. this._valueCache[uniformName][1] = y;
  14079. this._valueCache[uniformName][2] = z;
  14080. };
  14081. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14082. if (!this._valueCache[uniformName]) {
  14083. this._valueCache[uniformName] = [x, y, z, w];
  14084. return;
  14085. }
  14086. this._valueCache[uniformName][0] = x;
  14087. this._valueCache[uniformName][1] = y;
  14088. this._valueCache[uniformName][2] = z;
  14089. this._valueCache[uniformName][3] = w;
  14090. };
  14091. Effect.prototype.setArray = function (uniformName, array) {
  14092. this._engine.setArray(this.getUniform(uniformName), array);
  14093. return this;
  14094. };
  14095. Effect.prototype.setArray2 = function (uniformName, array) {
  14096. this._engine.setArray2(this.getUniform(uniformName), array);
  14097. return this;
  14098. };
  14099. Effect.prototype.setArray3 = function (uniformName, array) {
  14100. this._engine.setArray3(this.getUniform(uniformName), array);
  14101. return this;
  14102. };
  14103. Effect.prototype.setArray4 = function (uniformName, array) {
  14104. this._engine.setArray4(this.getUniform(uniformName), array);
  14105. return this;
  14106. };
  14107. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14108. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14109. return this;
  14110. };
  14111. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14112. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14113. // return;
  14114. //this._cacheMatrix(uniformName, matrix);
  14115. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14116. return this;
  14117. };
  14118. Effect.prototype.setFloat = function (uniformName, value) {
  14119. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14120. return this;
  14121. this._valueCache[uniformName] = value;
  14122. this._engine.setFloat(this.getUniform(uniformName), value);
  14123. return this;
  14124. };
  14125. Effect.prototype.setBool = function (uniformName, bool) {
  14126. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14127. return this;
  14128. this._valueCache[uniformName] = bool;
  14129. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14130. return this;
  14131. };
  14132. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14133. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14134. return this;
  14135. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14136. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14137. return this;
  14138. };
  14139. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14140. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14141. return this;
  14142. this._cacheFloat2(uniformName, x, y);
  14143. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14144. return this;
  14145. };
  14146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14147. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14148. return this;
  14149. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14150. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14151. return this;
  14152. };
  14153. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14154. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14155. return this;
  14156. this._cacheFloat3(uniformName, x, y, z);
  14157. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14158. return this;
  14159. };
  14160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14161. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14162. return this;
  14163. this._cacheFloat4(uniformName, x, y, z, w);
  14164. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14165. return this;
  14166. };
  14167. Effect.prototype.setColor3 = function (uniformName, color3) {
  14168. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14169. return this;
  14170. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14171. this._engine.setColor3(this.getUniform(uniformName), color3);
  14172. return this;
  14173. };
  14174. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14175. 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)
  14176. return this;
  14177. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14178. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14179. return this;
  14180. };
  14181. // Statics
  14182. 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}",
  14183. 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}",
  14184. 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}",
  14185. 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}",
  14186. chromaticAberrationPixelShader:"/*\n BABYLON.JS Chromatic Aberration GLSL Shader\n Author: Olivier Guyot\n Separates very slightly R, G and B colors on the edges of the screen\n Inspired by Francois Tarlier & Martins Upitis \n*/\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n// samplers\nuniform sampler2D textureSampler; // original color\n\n// uniforms\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\n// varyings\nvarying vec2 vUV;\n\nvoid main(void)\n{\n vec2 centered_screen_pos = vec2(vUV.x-0.5, vUV.y-0.5);\n float radius2 = centered_screen_pos.x*centered_screen_pos.x\n + centered_screen_pos.y*centered_screen_pos.y;\n float radius = sqrt(radius2);\n\n vec4 original = texture2D(textureSampler, vUV);\n\n if(chromatic_aberration > 0.0) {\n //index of refraction of each color channel, causing chromatic dispersion\n vec3 ref_indices = vec3(0.6, 0.3, 0.0);\n float ref_shiftX = chromatic_aberration * radius * 12.0 / screen_width;\n float ref_shiftY = chromatic_aberration * radius * 12.0 / screen_height;\n\n // shifts for red, green & blue\n vec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\n vec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\n vec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\n original.r = texture2D(textureSampler, ref_coords_r).r;\n original.g = texture2D(textureSampler, ref_coords_g).g;\n original.b = texture2D(textureSampler, ref_coords_b).b;\n }\n\n gl_FragColor = original;\n}",
  14187. 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}",
  14188. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  14189. 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}",
  14190. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// samplers\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\n// varyings\nvarying vec2 vUV;\n\n// constants\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n// it means the image is 256x16 pixels\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\n float sliceSize = 1.0 / width; // space of 1 slice\n float slicePixelSize = sliceSize / width; // space of 1 pixel\n float sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\n float zSlice0 = min(floor(uv.z * width), width - 1.0);\n float zSlice1 = min(zSlice0 + 1.0, width - 1.0);\n float xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\n float s0 = xOffset + (zSlice0 * sliceSize);\n float s1 = xOffset + (zSlice1 * sliceSize);\n vec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\n vec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\n float zOffset = mod(uv.z * width, 1.0);\n vec4 result = mix(slice0Color, slice1Color, zOffset);\n return result;\n}\n\nvoid main(void)\n{\n vec4 screen_color = texture2D(textureSampler, vUV);\n gl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  14191. 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}",
  14192. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform vec3 shadowsInfo0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform vec3 shadowsInfo1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform vec3 shadowsInfo2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform vec3 shadowsInfo3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n return dot(color, bit_shift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n float biasedDepth = depth.z - bias;\n\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat linstep(float low, float high, float v) {\n return clamp((v - low) / (high - low), 0.0, 1.0);\n}\n\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\n{\n float p = smoothstep(compare - bias, compare, moments.x);\n float variance = max(moments.y - moments.x * moments.x, 0.02);\n float d = compare - moments.x;\n float p_max = linstep(0.2, 1.0, variance / (variance + d * d));\n\n return clamp(max(p, p_max), 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return 1.0 - ChebychevInequality(moments, depth.z, bias);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n#ifdef NORMAL\n vec3 normalW = normalize(vNormalW);\n#else\n vec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  14193. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n\n#ifdef NORMAL\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  14194. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  14195. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14196. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\n\nvoid main(void)\n{\n vec4 colorDepth = vec4(0.0);\n\n for (int x = -OFFSET; x <= OFFSET; x++)\n for (int y = -OFFSET; y <= OFFSET; y++)\n colorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\n gl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  14197. depthOfFieldPixelShader:"/*\n BABYLON.JS Depth-of-field GLSL Shader\n Author: Olivier Guyot\n Does depth-of-field blur, edge blur, highlights enhancing\n Inspired by Francois Tarlier & Martins Upitis\n*/\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\n// samplers\nuniform sampler2D textureSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\n// uniforms\nuniform float grain_amount;\nuniform bool pentagon;\nuniform float maxZ;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform float focus_depth;\nuniform float aperture;\nuniform float gain;\nuniform float threshold;\nuniform float edge_blur;\n\n// varyings\nvarying vec2 vUV;\n\n// constants\n#define PI 3.14159265\nconst int RING_1_SAMPLES = 4;\nconst int RING_2_SAMPLES = 6;\nconst int RING_3_SAMPLES = 9;\nconst int RING_4_SAMPLES = 12;\nconst int RING_5_SAMPLES = 16;\n//const int RING_6_SAMPLES = 15;\nconst float RING_STEP_DIST = 0.4; // a new blur ring is added each time this distance is passed\nconst float PENTAGON_ANGLE_SUB = 1.2566; // 2PI / 5\nconst float PENTAGON_ANGLE_SUB_HALF = 0.6283; // 2PI / 10\n\n// common calculations\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\n// applies edge distortion on texture coords\nvec2 getDistortedCoords(vec2 coords) {\n\n if(distortion == 0.0) { return coords; }\n\n vec2 direction = 1.0 * normalize(centered_screen_pos);\n vec2 dist_coords = vec2(0.5, 0.5);\n dist_coords.x = 0.5 + direction.x * radius2 * 1.0;\n dist_coords.y = 0.5 + direction.y * radius2 * 1.0;\n float dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\n dist_coords = mix(coords, dist_coords, dist_amount);\n\n return dist_coords;\n}\n\n// picks either original screen color or highlights only\nvec4 getColor(vec2 coords, bool highlight) {\n\n vec4 color = texture2D(textureSampler, coords);\n\n if(highlight) {\n float luminance = dot(color.rgb, vec3(0.2125, 0.7154, 0.0721));\n float lum_threshold;\n if(threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\n else { lum_threshold = 0.5 + 0.44 * threshold; }\n if(luminance < lum_threshold) {\n color.rgb = vec3(0.0, 0.0, 0.0);\n color.a = 1.0;\n }\n }\n\n return color;\n}\n\n// returns a modifier to be applied on the radius, in order to simulate a pentagon\nfloat pentagonShape(float angle) {\n float a1 = mod(angle, PENTAGON_ANGLE_SUB) / PENTAGON_ANGLE_SUB - 0.5;\n float a2 = 0.5 - a1 * a1;\n return 1.35 - 0.94 * a2;\n}\n\n// returns original screen color after blur\nvec4 getBlurColor(vec2 coords, float size, bool highlight) {\n\n float w = (size/screen_width);\n float h = (size/screen_height);\n\n vec4 col = getColor(coords, highlight);\n if(size == 0.0) { return col; }\n\n float s = 1.0;\n float pw; // sample x relative coord\n float ph; // sample y relative coord\n float bias = 0.65; // inner/outer ring bias\n if(highlight) { bias = 0.95; }\n float sample_angle;\n float ratio_rings;\n float ring_radius;\n float penta; // pentagon shape modifier\n\n int ring_count;\n if(size >= 6.0 * RING_STEP_DIST) { ring_count = 6; }\n else if(size >= 5.0 * RING_STEP_DIST) { ring_count = 5; }\n else if(size >= 4.0 * RING_STEP_DIST) { ring_count = 4; }\n else if(size >= 3.0 * RING_STEP_DIST) { ring_count = 3; }\n else if(size >= 2.0 * RING_STEP_DIST) { ring_count = 2; }\n else { ring_count = 1; }\n \n // RING 1\n if(size > RING_STEP_DIST) {\n ring_radius = size / float(ring_count);\n ratio_rings = 1.0 / float(ring_count);\n for(int i = 0; i < RING_1_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_1_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias);\n }\n } \n\n // RING 2\n if(size > RING_STEP_DIST * 2.0) {\n ring_radius = 2.0 * size / float(ring_count);\n ratio_rings = 2.0 / float(ring_count);\n for(int i = 0; i < RING_2_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_2_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 3\n if(size > RING_STEP_DIST * 3.0) {\n ring_radius = 3.0 * size / float(ring_count);\n ratio_rings = 3.0 / float(ring_count);\n for(int i = 0; i < RING_3_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_3_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 4\n if(size > RING_STEP_DIST * 4.0) {\n ring_radius = 4.0 * size / float(ring_count);\n ratio_rings = 4.0 / float(ring_count);\n for(int i = 0; i < RING_4_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_4_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 5\n if(size > RING_STEP_DIST * 5.0) {\n ring_radius = 5.0 * size / float(ring_count);\n ratio_rings = 5.0 / float(ring_count);\n for(int i = 0; i < RING_5_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_5_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n col /= s; // scales color according to samples taken\n col.a = 1.0;\n\n return col;\n}\n\n// on-the-fly constant noise\nvec2 rand(vec2 co)\n{\n float noise1 = (fract(sin(dot(co ,vec2(12.9898,78.233))) * 43758.5453));\n float noise2 = (fract(sin(dot(co ,vec2(12.9898,78.233)*2.0)) * 43758.5453));\n return clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvoid main(void)\n{\n\n // Common calc\n centered_screen_pos = vec2(vUV.x-0.5, vUV.y-0.5);\n radius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\n radius = sqrt(radius2);\n\n vec4 final_color;\n vec2 distorted_coords = getDistortedCoords(vUV);\n vec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\n // blur from depth of field effect\n float dof_blur_amount = 0.0;\n if(focus_depth != -1.0) {\n vec4 depth_sample = texture2D(depthSampler, distorted_coords);\n float depth = depth_sample.r;\n dof_blur_amount = abs(depth - focus_depth) * aperture * 3.5;\n if(dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n else if( depth - focus_depth < 0.0 ) { dof_blur_amount *= 2.0; } // blur more when close to camera\n dof_blur_amount = clamp(dof_blur_amount, 0.0, 1.0);\n }\n\n // blur from edge blur effect\n float edge_blur_amount = 0.0;\n if(edge_blur > 0.0) {\n edge_blur_amount = clamp( ( radius*2.0 - 1.0 + 0.15*edge_blur ) * 1.5 , 0.0 , 1.0 ) * 1.3;\n }\n\n // total blur amount\n float blur_amount = max(edge_blur_amount, dof_blur_amount);\n\n // apply blur if necessary\n if(blur_amount == 0.0) {\n gl_FragColor = getColor(distorted_coords, false);\n } else {\n gl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7, false)\n + gain * blur_amount*getBlurColor(distorted_coords, blur_amount * 2.75, true);\n\n if(blur_noise) {\n // we put a slight amount of noise in the blurred color\n vec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\n vec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\n gl_FragColor = 0.04 * getColor(blurred_coord, false) + 0.96 * gl_FragColor;\n }\n }\n\n if(grain_amount > 0.0) {\n vec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\n gl_FragColor.rgb += ( -0.5 + grain_color.rgb ) * 0.20;\n }\n}",
  14198. 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}",
  14199. 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}",
  14200. 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}",
  14201. 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}",
  14202. 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}",
  14203. 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}",
  14204. 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}",
  14205. 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}",
  14206. 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}",
  14207. 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}",
  14208. 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}",
  14209. 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}",
  14210. 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}",
  14211. 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}",
  14212. 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}",
  14213. 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}",
  14214. 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}",
  14215. 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}",
  14216. 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}",
  14217. 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}",
  14218. 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}",
  14219. 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}",
  14220. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\n vec4 res = fract(depth * bit_shift);\n res -= res.xxyz * bit_mask;\n\n return res;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n float depth = vPosition.z / vPosition.w;\n depth = depth * 0.5 + 0.5;\n\n#ifdef VSM\n float moment1 = depth;\n float moment2 = moment1 * moment1;\n\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(depth);\n#endif\n}",
  14221. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#endif\n\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n gl_Position = vPosition;\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14222. 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}",
  14223. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec4 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.xyz, 1.0)).xyz; \n vec2 cornerPos;\n \n float angle = position.w;\n vec2 size = vec2(options.x, options.y);\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * 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}",
  14224. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.01);\nconst vec2 offset2 = vec2(0.01, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n\n return normalize(normal);\n}\n\nvoid main(void)\n{\n const float base = 0.2;\n\n vec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\n float depth = texture2D(textureSampler, vUV).r;\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n\n vec3 ray;\n vec3 hemiRay;\n float occlusionDepth;\n float difference;\n\n for (int i = 0; i < SAMPLES; i++)\n {\n ray = radiusDepth * reflect(sampleSphere[i], random);\n hemiRay = position + sign(dot(ray, normal)) * ray;\n\n occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\n difference = depth - occlusionDepth;\n\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n\n float ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = 1.0;\n}",
  14225. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n gl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  14226. volumetricLightScatteringPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n vec2 tc = vUV;\n vec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\n float illuminationDecay = 1.0;\n\n vec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\n for(int i=0; i < NUM_SAMPLES; i++) {\n tc -= deltaTexCoord;\n vec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\n sample *= illuminationDecay * weight;\n color += sample;\n illuminationDecay *= decay;\n }\n\n vec4 realColor = texture2D(textureSampler, vUV);\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  14227. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef OPACITY\n vec4 opacityColor = texture2D(opacitySampler, vUV);\n float alpha = 1.0;\n\n #ifdef OPACITYRGB\n opacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n #else\n alpha *= opacityColor.a * opacityLevel;\n #endif\n\n #if defined(BASIC_RENDER)\n gl_FragColor = vec4(diffuseColor.rgb, alpha);\n #else\n gl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n #endif\n\n gl_FragColor.a = alpha;\n#else\n #ifndef BASIC_RENDER\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n #else\n gl_FragColor = diffuseColor;\n #endif\n#endif\n\n}",
  14228. 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}",
  14229. };
  14230. return Effect;
  14231. })();
  14232. BABYLON.Effect = Effect;
  14233. })(BABYLON || (BABYLON = {}));
  14234. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14235. (function (BABYLON) {
  14236. var Material = (function () {
  14237. function Material(name, scene, doNotAdd) {
  14238. this.name = name;
  14239. this.checkReadyOnEveryCall = true;
  14240. this.checkReadyOnlyOnce = false;
  14241. this.state = "";
  14242. this.alpha = 1.0;
  14243. this.backFaceCulling = true;
  14244. this._wasPreviouslyReady = false;
  14245. this._fillMode = Material.TriangleFillMode;
  14246. this.pointSize = 1.0;
  14247. this.id = name;
  14248. this._scene = scene;
  14249. if (!doNotAdd) {
  14250. scene.materials.push(this);
  14251. }
  14252. }
  14253. Object.defineProperty(Material, "TriangleFillMode", {
  14254. get: function () {
  14255. return Material._TriangleFillMode;
  14256. },
  14257. enumerable: true,
  14258. configurable: true
  14259. });
  14260. Object.defineProperty(Material, "WireFrameFillMode", {
  14261. get: function () {
  14262. return Material._WireFrameFillMode;
  14263. },
  14264. enumerable: true,
  14265. configurable: true
  14266. });
  14267. Object.defineProperty(Material, "PointFillMode", {
  14268. get: function () {
  14269. return Material._PointFillMode;
  14270. },
  14271. enumerable: true,
  14272. configurable: true
  14273. });
  14274. Object.defineProperty(Material.prototype, "wireframe", {
  14275. get: function () {
  14276. return this._fillMode === Material.WireFrameFillMode;
  14277. },
  14278. set: function (value) {
  14279. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14280. },
  14281. enumerable: true,
  14282. configurable: true
  14283. });
  14284. Object.defineProperty(Material.prototype, "pointsCloud", {
  14285. get: function () {
  14286. return this._fillMode === Material.PointFillMode;
  14287. },
  14288. set: function (value) {
  14289. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14290. },
  14291. enumerable: true,
  14292. configurable: true
  14293. });
  14294. Object.defineProperty(Material.prototype, "fillMode", {
  14295. get: function () {
  14296. return this._fillMode;
  14297. },
  14298. set: function (value) {
  14299. this._fillMode = value;
  14300. },
  14301. enumerable: true,
  14302. configurable: true
  14303. });
  14304. Material.prototype.isReady = function (mesh, useInstances) {
  14305. return true;
  14306. };
  14307. Material.prototype.getEffect = function () {
  14308. return this._effect;
  14309. };
  14310. Material.prototype.getScene = function () {
  14311. return this._scene;
  14312. };
  14313. Material.prototype.needAlphaBlending = function () {
  14314. return (this.alpha < 1.0);
  14315. };
  14316. Material.prototype.needAlphaTesting = function () {
  14317. return false;
  14318. };
  14319. Material.prototype.getAlphaTestTexture = function () {
  14320. return null;
  14321. };
  14322. Material.prototype.trackCreation = function (onCompiled, onError) {
  14323. };
  14324. Material.prototype._preBind = function () {
  14325. var engine = this._scene.getEngine();
  14326. engine.enableEffect(this._effect);
  14327. engine.setState(this.backFaceCulling);
  14328. };
  14329. Material.prototype.bind = function (world, mesh) {
  14330. this._scene._cachedMaterial = this;
  14331. if (this.onBind) {
  14332. this.onBind(this);
  14333. }
  14334. };
  14335. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14336. };
  14337. Material.prototype.unbind = function () {
  14338. };
  14339. Material.prototype.dispose = function (forceDisposeEffect) {
  14340. // Remove from scene
  14341. var index = this._scene.materials.indexOf(this);
  14342. this._scene.materials.splice(index, 1);
  14343. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14344. if (forceDisposeEffect && this._effect) {
  14345. this._scene.getEngine()._releaseEffect(this._effect);
  14346. this._effect = null;
  14347. }
  14348. // Callback
  14349. if (this.onDispose) {
  14350. this.onDispose();
  14351. }
  14352. };
  14353. Material._TriangleFillMode = 0;
  14354. Material._WireFrameFillMode = 1;
  14355. Material._PointFillMode = 2;
  14356. return Material;
  14357. })();
  14358. BABYLON.Material = Material;
  14359. })(BABYLON || (BABYLON = {}));
  14360. //# sourceMappingURL=babylon.material.js.map
  14361. var BABYLON;
  14362. (function (BABYLON) {
  14363. var maxSimultaneousLights = 4;
  14364. var FresnelParameters = (function () {
  14365. function FresnelParameters() {
  14366. this.isEnabled = true;
  14367. this.leftColor = BABYLON.Color3.White();
  14368. this.rightColor = BABYLON.Color3.Black();
  14369. this.bias = 0;
  14370. this.power = 1;
  14371. }
  14372. return FresnelParameters;
  14373. })();
  14374. BABYLON.FresnelParameters = FresnelParameters;
  14375. var StandardMaterial = (function (_super) {
  14376. __extends(StandardMaterial, _super);
  14377. function StandardMaterial(name, scene) {
  14378. var _this = this;
  14379. _super.call(this, name, scene);
  14380. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14381. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14382. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14383. this.specularPower = 64;
  14384. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14385. this.useAlphaFromDiffuseTexture = false;
  14386. this.useSpecularOverAlpha = true;
  14387. this.fogEnabled = true;
  14388. this._cachedDefines = null;
  14389. this._renderTargets = new BABYLON.SmartArray(16);
  14390. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14391. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14392. this._scaledDiffuse = new BABYLON.Color3();
  14393. this._scaledSpecular = new BABYLON.Color3();
  14394. this.getRenderTargetTextures = function () {
  14395. _this._renderTargets.reset();
  14396. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14397. _this._renderTargets.push(_this.reflectionTexture);
  14398. }
  14399. return _this._renderTargets;
  14400. };
  14401. }
  14402. StandardMaterial.prototype.needAlphaBlending = function () {
  14403. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14404. };
  14405. StandardMaterial.prototype.needAlphaTesting = function () {
  14406. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14407. };
  14408. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14409. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14410. };
  14411. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14412. return this.diffuseTexture;
  14413. };
  14414. // Methods
  14415. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14416. if (this.checkReadyOnlyOnce) {
  14417. if (this._wasPreviouslyReady) {
  14418. }
  14419. }
  14420. var scene = this.getScene();
  14421. if (!this.checkReadyOnEveryCall) {
  14422. if (this._renderId === scene.getRenderId()) {
  14423. }
  14424. }
  14425. var engine = scene.getEngine();
  14426. var defines = [];
  14427. var fallbacks = new BABYLON.EffectFallbacks();
  14428. var needNormals = false;
  14429. var needUVs = false;
  14430. // Textures
  14431. if (scene.texturesEnabled) {
  14432. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14433. if (!this.diffuseTexture.isReady()) {
  14434. return false;
  14435. }
  14436. else {
  14437. needUVs = true;
  14438. defines.push("#define DIFFUSE");
  14439. }
  14440. }
  14441. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14442. if (!this.ambientTexture.isReady()) {
  14443. return false;
  14444. }
  14445. else {
  14446. needUVs = true;
  14447. defines.push("#define AMBIENT");
  14448. }
  14449. }
  14450. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14451. if (!this.opacityTexture.isReady()) {
  14452. return false;
  14453. }
  14454. else {
  14455. needUVs = true;
  14456. defines.push("#define OPACITY");
  14457. if (this.opacityTexture.getAlphaFromRGB) {
  14458. defines.push("#define OPACITYRGB");
  14459. }
  14460. }
  14461. }
  14462. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14463. if (!this.reflectionTexture.isReady()) {
  14464. return false;
  14465. }
  14466. else {
  14467. needNormals = true;
  14468. needUVs = true;
  14469. defines.push("#define REFLECTION");
  14470. fallbacks.addFallback(0, "REFLECTION");
  14471. }
  14472. }
  14473. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14474. if (!this.emissiveTexture.isReady()) {
  14475. return false;
  14476. }
  14477. else {
  14478. needUVs = true;
  14479. defines.push("#define EMISSIVE");
  14480. }
  14481. }
  14482. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14483. if (!this.specularTexture.isReady()) {
  14484. return false;
  14485. }
  14486. else {
  14487. needUVs = true;
  14488. defines.push("#define SPECULAR");
  14489. fallbacks.addFallback(0, "SPECULAR");
  14490. }
  14491. }
  14492. }
  14493. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14494. if (!this.bumpTexture.isReady()) {
  14495. return false;
  14496. }
  14497. else {
  14498. needUVs = true;
  14499. defines.push("#define BUMP");
  14500. fallbacks.addFallback(0, "BUMP");
  14501. }
  14502. }
  14503. // Effect
  14504. if (this.useSpecularOverAlpha) {
  14505. defines.push("#define SPECULAROVERALPHA");
  14506. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14507. }
  14508. if (scene.clipPlane) {
  14509. defines.push("#define CLIPPLANE");
  14510. }
  14511. if (engine.getAlphaTesting()) {
  14512. defines.push("#define ALPHATEST");
  14513. }
  14514. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14515. defines.push("#define ALPHAFROMDIFFUSE");
  14516. }
  14517. // Point size
  14518. if (this.pointsCloud || scene.forcePointsCloud) {
  14519. defines.push("#define POINTSIZE");
  14520. }
  14521. // Fog
  14522. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14523. defines.push("#define FOG");
  14524. fallbacks.addFallback(1, "FOG");
  14525. }
  14526. var shadowsActivated = false;
  14527. var lightIndex = 0;
  14528. if (scene.lightsEnabled) {
  14529. for (var index = 0; index < scene.lights.length; index++) {
  14530. var light = scene.lights[index];
  14531. if (!light.isEnabled()) {
  14532. continue;
  14533. }
  14534. // Excluded check
  14535. if (light._excludedMeshesIds.length > 0) {
  14536. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14537. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14538. if (excludedMesh) {
  14539. light.excludedMeshes.push(excludedMesh);
  14540. }
  14541. }
  14542. light._excludedMeshesIds = [];
  14543. }
  14544. // Included check
  14545. if (light._includedOnlyMeshesIds.length > 0) {
  14546. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14547. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14548. if (includedOnlyMesh) {
  14549. light.includedOnlyMeshes.push(includedOnlyMesh);
  14550. }
  14551. }
  14552. light._includedOnlyMeshesIds = [];
  14553. }
  14554. if (!light.canAffectMesh(mesh)) {
  14555. continue;
  14556. }
  14557. needNormals = true;
  14558. defines.push("#define LIGHT" + lightIndex);
  14559. if (lightIndex > 0) {
  14560. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14561. }
  14562. var type;
  14563. if (light instanceof BABYLON.SpotLight) {
  14564. type = "#define SPOTLIGHT" + lightIndex;
  14565. }
  14566. else if (light instanceof BABYLON.HemisphericLight) {
  14567. type = "#define HEMILIGHT" + lightIndex;
  14568. }
  14569. else {
  14570. type = "#define POINTDIRLIGHT" + lightIndex;
  14571. }
  14572. defines.push(type);
  14573. if (lightIndex > 0) {
  14574. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14575. }
  14576. // Shadows
  14577. if (scene.shadowsEnabled) {
  14578. var shadowGenerator = light.getShadowGenerator();
  14579. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14580. defines.push("#define SHADOW" + lightIndex);
  14581. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14582. if (!shadowsActivated) {
  14583. defines.push("#define SHADOWS");
  14584. shadowsActivated = true;
  14585. }
  14586. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14587. defines.push("#define SHADOWVSM" + lightIndex);
  14588. if (lightIndex > 0) {
  14589. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14590. }
  14591. }
  14592. if (shadowGenerator.usePoissonSampling) {
  14593. defines.push("#define SHADOWPCF" + lightIndex);
  14594. if (lightIndex > 0) {
  14595. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14596. }
  14597. }
  14598. }
  14599. }
  14600. lightIndex++;
  14601. if (lightIndex === maxSimultaneousLights)
  14602. break;
  14603. }
  14604. }
  14605. if (StandardMaterial.FresnelEnabled) {
  14606. // Fresnel
  14607. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14608. var fresnelRank = 1;
  14609. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14610. defines.push("#define DIFFUSEFRESNEL");
  14611. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14612. fresnelRank++;
  14613. }
  14614. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14615. defines.push("#define OPACITYFRESNEL");
  14616. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14617. fresnelRank++;
  14618. }
  14619. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14620. defines.push("#define REFLECTIONFRESNEL");
  14621. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14622. fresnelRank++;
  14623. }
  14624. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14625. defines.push("#define EMISSIVEFRESNEL");
  14626. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14627. fresnelRank++;
  14628. }
  14629. needNormals = true;
  14630. defines.push("#define FRESNEL");
  14631. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14632. }
  14633. }
  14634. // Attribs
  14635. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14636. if (mesh) {
  14637. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14638. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14639. defines.push("#define NORMAL");
  14640. }
  14641. if (needUVs) {
  14642. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14643. attribs.push(BABYLON.VertexBuffer.UVKind);
  14644. defines.push("#define UV1");
  14645. }
  14646. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14647. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14648. defines.push("#define UV2");
  14649. }
  14650. }
  14651. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14652. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14653. defines.push("#define VERTEXCOLOR");
  14654. if (mesh.hasVertexAlpha) {
  14655. defines.push("#define VERTEXALPHA");
  14656. }
  14657. }
  14658. if (mesh.useBones) {
  14659. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14660. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14661. defines.push("#define BONES");
  14662. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14663. defines.push("#define BONES4");
  14664. fallbacks.addFallback(0, "BONES4");
  14665. }
  14666. // Instances
  14667. if (useInstances) {
  14668. defines.push("#define INSTANCES");
  14669. attribs.push("world0");
  14670. attribs.push("world1");
  14671. attribs.push("world2");
  14672. attribs.push("world3");
  14673. }
  14674. }
  14675. // Get correct effect
  14676. var join = defines.join("\n");
  14677. if (this._cachedDefines !== join) {
  14678. this._cachedDefines = join;
  14679. scene.resetCachedMaterial();
  14680. // Legacy browser patch
  14681. var shaderName = "default";
  14682. if (!scene.getEngine().getCaps().standardDerivatives) {
  14683. shaderName = "legacydefault";
  14684. }
  14685. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  14686. }
  14687. if (!this._effect.isReady()) {
  14688. return false;
  14689. }
  14690. this._renderId = scene.getRenderId();
  14691. this._wasPreviouslyReady = true;
  14692. return true;
  14693. };
  14694. StandardMaterial.prototype.unbind = function () {
  14695. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14696. this._effect.setTexture("reflection2DSampler", null);
  14697. }
  14698. };
  14699. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14700. this._effect.setMatrix("world", world);
  14701. };
  14702. StandardMaterial.prototype.bind = function (world, mesh) {
  14703. var scene = this.getScene();
  14704. // Matrices
  14705. this.bindOnlyWorldMatrix(world);
  14706. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14707. // Bones
  14708. if (mesh.useBones) {
  14709. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14710. }
  14711. if (scene.getCachedMaterial() !== this) {
  14712. if (StandardMaterial.FresnelEnabled) {
  14713. // Fresnel
  14714. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14715. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14716. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14717. }
  14718. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14719. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14720. }
  14721. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14722. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14723. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14724. }
  14725. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14726. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14727. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14728. }
  14729. }
  14730. // Textures
  14731. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14732. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14733. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14734. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14735. }
  14736. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14737. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14738. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14739. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14740. }
  14741. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14742. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14743. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14744. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14745. }
  14746. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14747. if (this.reflectionTexture.isCube) {
  14748. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14749. }
  14750. else {
  14751. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14752. }
  14753. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14754. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14755. }
  14756. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14757. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14758. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14759. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14760. }
  14761. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14762. this._effect.setTexture("specularSampler", this.specularTexture);
  14763. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14764. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14765. }
  14766. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14767. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14768. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14769. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14770. }
  14771. // Clip plane
  14772. if (scene.clipPlane) {
  14773. var clipPlane = scene.clipPlane;
  14774. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14775. }
  14776. // Point size
  14777. if (this.pointsCloud) {
  14778. this._effect.setFloat("pointSize", this.pointSize);
  14779. }
  14780. // Colors
  14781. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14782. // Scaling down color according to emissive
  14783. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14784. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14785. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14786. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14787. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14788. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14789. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14790. }
  14791. // Scaling down color according to emissive
  14792. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14793. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14794. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14795. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14796. if (scene.lightsEnabled) {
  14797. var lightIndex = 0;
  14798. for (var index = 0; index < scene.lights.length; index++) {
  14799. var light = scene.lights[index];
  14800. if (!light.isEnabled()) {
  14801. continue;
  14802. }
  14803. if (!light.canAffectMesh(mesh)) {
  14804. continue;
  14805. }
  14806. if (light instanceof BABYLON.PointLight) {
  14807. // Point Light
  14808. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14809. }
  14810. else if (light instanceof BABYLON.DirectionalLight) {
  14811. // Directional Light
  14812. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14813. }
  14814. else if (light instanceof BABYLON.SpotLight) {
  14815. // Spot Light
  14816. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14817. }
  14818. else if (light instanceof BABYLON.HemisphericLight) {
  14819. // Hemispheric Light
  14820. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14821. }
  14822. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14823. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14824. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14825. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14826. // Shadows
  14827. if (scene.shadowsEnabled) {
  14828. var shadowGenerator = light.getShadowGenerator();
  14829. if (mesh.receiveShadows && shadowGenerator) {
  14830. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14831. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14832. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  14833. }
  14834. }
  14835. lightIndex++;
  14836. if (lightIndex === maxSimultaneousLights)
  14837. break;
  14838. }
  14839. }
  14840. // View
  14841. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14842. this._effect.setMatrix("view", scene.getViewMatrix());
  14843. }
  14844. // Fog
  14845. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14846. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14847. this._effect.setColor3("vFogColor", scene.fogColor);
  14848. }
  14849. _super.prototype.bind.call(this, world, mesh);
  14850. };
  14851. StandardMaterial.prototype.getAnimatables = function () {
  14852. var results = [];
  14853. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14854. results.push(this.diffuseTexture);
  14855. }
  14856. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14857. results.push(this.ambientTexture);
  14858. }
  14859. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14860. results.push(this.opacityTexture);
  14861. }
  14862. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14863. results.push(this.reflectionTexture);
  14864. }
  14865. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14866. results.push(this.emissiveTexture);
  14867. }
  14868. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14869. results.push(this.specularTexture);
  14870. }
  14871. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14872. results.push(this.bumpTexture);
  14873. }
  14874. return results;
  14875. };
  14876. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14877. if (this.diffuseTexture) {
  14878. this.diffuseTexture.dispose();
  14879. }
  14880. if (this.ambientTexture) {
  14881. this.ambientTexture.dispose();
  14882. }
  14883. if (this.opacityTexture) {
  14884. this.opacityTexture.dispose();
  14885. }
  14886. if (this.reflectionTexture) {
  14887. this.reflectionTexture.dispose();
  14888. }
  14889. if (this.emissiveTexture) {
  14890. this.emissiveTexture.dispose();
  14891. }
  14892. if (this.specularTexture) {
  14893. this.specularTexture.dispose();
  14894. }
  14895. if (this.bumpTexture) {
  14896. this.bumpTexture.dispose();
  14897. }
  14898. _super.prototype.dispose.call(this, forceDisposeEffect);
  14899. };
  14900. StandardMaterial.prototype.clone = function (name) {
  14901. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14902. // Base material
  14903. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14904. newStandardMaterial.alpha = this.alpha;
  14905. newStandardMaterial.fillMode = this.fillMode;
  14906. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14907. // Standard material
  14908. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14909. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14910. }
  14911. if (this.ambientTexture && this.ambientTexture.clone) {
  14912. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14913. }
  14914. if (this.opacityTexture && this.opacityTexture.clone) {
  14915. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14916. }
  14917. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14918. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14919. }
  14920. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14921. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14922. }
  14923. if (this.specularTexture && this.specularTexture.clone) {
  14924. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14925. }
  14926. if (this.bumpTexture && this.bumpTexture.clone) {
  14927. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14928. }
  14929. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14930. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14931. newStandardMaterial.specularColor = this.specularColor.clone();
  14932. newStandardMaterial.specularPower = this.specularPower;
  14933. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14934. return newStandardMaterial;
  14935. };
  14936. // Statics
  14937. // Flags used to enable or disable a type of texture for all Standard Materials
  14938. StandardMaterial.DiffuseTextureEnabled = true;
  14939. StandardMaterial.AmbientTextureEnabled = true;
  14940. StandardMaterial.OpacityTextureEnabled = true;
  14941. StandardMaterial.ReflectionTextureEnabled = true;
  14942. StandardMaterial.EmissiveTextureEnabled = true;
  14943. StandardMaterial.SpecularTextureEnabled = true;
  14944. StandardMaterial.BumpTextureEnabled = true;
  14945. StandardMaterial.FresnelEnabled = true;
  14946. return StandardMaterial;
  14947. })(BABYLON.Material);
  14948. BABYLON.StandardMaterial = StandardMaterial;
  14949. })(BABYLON || (BABYLON = {}));
  14950. //# sourceMappingURL=babylon.standardMaterial.js.map
  14951. var BABYLON;
  14952. (function (BABYLON) {
  14953. var MultiMaterial = (function (_super) {
  14954. __extends(MultiMaterial, _super);
  14955. function MultiMaterial(name, scene) {
  14956. _super.call(this, name, scene, true);
  14957. this.subMaterials = new Array();
  14958. scene.multiMaterials.push(this);
  14959. }
  14960. // Properties
  14961. MultiMaterial.prototype.getSubMaterial = function (index) {
  14962. if (index < 0 || index >= this.subMaterials.length) {
  14963. return this.getScene().defaultMaterial;
  14964. }
  14965. return this.subMaterials[index];
  14966. };
  14967. // Methods
  14968. MultiMaterial.prototype.isReady = function (mesh) {
  14969. for (var index = 0; index < this.subMaterials.length; index++) {
  14970. var subMaterial = this.subMaterials[index];
  14971. if (subMaterial) {
  14972. if (!this.subMaterials[index].isReady(mesh)) {
  14973. return false;
  14974. }
  14975. }
  14976. }
  14977. return true;
  14978. };
  14979. return MultiMaterial;
  14980. })(BABYLON.Material);
  14981. BABYLON.MultiMaterial = MultiMaterial;
  14982. })(BABYLON || (BABYLON = {}));
  14983. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14984. (function (BABYLON) {
  14985. var Database = (function () {
  14986. function Database(urlToScene, callbackManifestChecked) {
  14987. // Handling various flavors of prefixed version of IndexedDB
  14988. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14989. this.callbackManifestChecked = callbackManifestChecked;
  14990. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14991. this.db = null;
  14992. this.enableSceneOffline = false;
  14993. this.enableTexturesOffline = false;
  14994. this.manifestVersionFound = 0;
  14995. this.mustUpdateRessources = false;
  14996. this.hasReachedQuota = false;
  14997. this.checkManifestFile();
  14998. }
  14999. Database.prototype.checkManifestFile = function () {
  15000. var _this = this;
  15001. function noManifestFile() {
  15002. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15003. that.enableSceneOffline = false;
  15004. that.enableTexturesOffline = false;
  15005. that.callbackManifestChecked(false);
  15006. }
  15007. var that = this;
  15008. var manifestURL = this.currentSceneUrl + ".manifest";
  15009. var xhr = new XMLHttpRequest();
  15010. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15011. xhr.open("GET", manifestURLTimeStamped, true);
  15012. xhr.addEventListener("load", function () {
  15013. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15014. try {
  15015. var manifestFile = JSON.parse(xhr.response);
  15016. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15017. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15018. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15019. _this.manifestVersionFound = manifestFile.version;
  15020. }
  15021. if (_this.callbackManifestChecked) {
  15022. _this.callbackManifestChecked(true);
  15023. }
  15024. }
  15025. catch (ex) {
  15026. noManifestFile();
  15027. }
  15028. }
  15029. else {
  15030. noManifestFile();
  15031. }
  15032. }, false);
  15033. xhr.addEventListener("error", function (event) {
  15034. noManifestFile();
  15035. }, false);
  15036. try {
  15037. xhr.send();
  15038. }
  15039. catch (ex) {
  15040. BABYLON.Tools.Error("Error on XHR send request.");
  15041. that.callbackManifestChecked(false);
  15042. }
  15043. };
  15044. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15045. var _this = this;
  15046. function handleError() {
  15047. that.isSupported = false;
  15048. if (errorCallback)
  15049. errorCallback();
  15050. }
  15051. var that = this;
  15052. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15053. // Your browser doesn't support IndexedDB
  15054. this.isSupported = false;
  15055. if (errorCallback)
  15056. errorCallback();
  15057. }
  15058. else {
  15059. // If the DB hasn't been opened or created yet
  15060. if (!this.db) {
  15061. this.hasReachedQuota = false;
  15062. this.isSupported = true;
  15063. var request = this.idbFactory.open("babylonjs", 1);
  15064. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15065. request.onerror = function (event) {
  15066. handleError();
  15067. };
  15068. // executes when a version change transaction cannot complete due to other active transactions
  15069. request.onblocked = function (event) {
  15070. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15071. handleError();
  15072. };
  15073. // DB has been opened successfully
  15074. request.onsuccess = function (event) {
  15075. _this.db = request.result;
  15076. successCallback();
  15077. };
  15078. // Initialization of the DB. Creating Scenes & Textures stores
  15079. request.onupgradeneeded = function (event) {
  15080. _this.db = (event.target).result;
  15081. try {
  15082. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15083. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15084. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15085. }
  15086. catch (ex) {
  15087. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15088. handleError();
  15089. }
  15090. };
  15091. }
  15092. else {
  15093. if (successCallback)
  15094. successCallback();
  15095. }
  15096. }
  15097. };
  15098. Database.prototype.loadImageFromDB = function (url, image) {
  15099. var _this = this;
  15100. var completeURL = Database.ReturnFullUrlLocation(url);
  15101. var saveAndLoadImage = function () {
  15102. if (!_this.hasReachedQuota && _this.db !== null) {
  15103. // the texture is not yet in the DB, let's try to save it
  15104. _this._saveImageIntoDBAsync(completeURL, image);
  15105. }
  15106. else {
  15107. image.src = url;
  15108. }
  15109. };
  15110. if (!this.mustUpdateRessources) {
  15111. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15112. }
  15113. else {
  15114. saveAndLoadImage();
  15115. }
  15116. };
  15117. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15118. if (this.isSupported && this.db !== null) {
  15119. var texture;
  15120. var transaction = this.db.transaction(["textures"]);
  15121. transaction.onabort = function (event) {
  15122. image.src = url;
  15123. };
  15124. transaction.oncomplete = function (event) {
  15125. var blobTextureURL;
  15126. if (texture) {
  15127. var URL = window.URL || window.webkitURL;
  15128. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15129. image.onerror = function () {
  15130. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15131. image.src = url;
  15132. };
  15133. image.src = blobTextureURL;
  15134. }
  15135. else {
  15136. notInDBCallback();
  15137. }
  15138. };
  15139. var getRequest = transaction.objectStore("textures").get(url);
  15140. getRequest.onsuccess = function (event) {
  15141. texture = (event.target).result;
  15142. };
  15143. getRequest.onerror = function (event) {
  15144. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15145. image.src = url;
  15146. };
  15147. }
  15148. else {
  15149. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15150. image.src = url;
  15151. }
  15152. };
  15153. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15154. var _this = this;
  15155. if (this.isSupported) {
  15156. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15157. var generateBlobUrl = function () {
  15158. var blobTextureURL;
  15159. if (blob) {
  15160. var URL = window.URL || window.webkitURL;
  15161. try {
  15162. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15163. }
  15164. catch (ex) {
  15165. blobTextureURL = URL.createObjectURL(blob);
  15166. }
  15167. }
  15168. image.src = blobTextureURL;
  15169. };
  15170. if (Database.isUASupportingBlobStorage) {
  15171. var xhr = new XMLHttpRequest(), blob;
  15172. xhr.open("GET", url, true);
  15173. xhr.responseType = "blob";
  15174. xhr.addEventListener("load", function () {
  15175. if (xhr.status === 200) {
  15176. // Blob as response (XHR2)
  15177. blob = xhr.response;
  15178. var transaction = _this.db.transaction(["textures"], "readwrite");
  15179. // the transaction could abort because of a QuotaExceededError error
  15180. transaction.onabort = function (event) {
  15181. try {
  15182. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15183. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15184. this.hasReachedQuota = true;
  15185. }
  15186. }
  15187. catch (ex) {
  15188. }
  15189. generateBlobUrl();
  15190. };
  15191. transaction.oncomplete = function (event) {
  15192. generateBlobUrl();
  15193. };
  15194. var newTexture = { textureUrl: url, data: blob };
  15195. try {
  15196. // Put the blob into the dabase
  15197. var addRequest = transaction.objectStore("textures").put(newTexture);
  15198. addRequest.onsuccess = function (event) {
  15199. };
  15200. addRequest.onerror = function (event) {
  15201. generateBlobUrl();
  15202. };
  15203. }
  15204. catch (ex) {
  15205. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15206. if (ex.code === 25) {
  15207. Database.isUASupportingBlobStorage = false;
  15208. }
  15209. image.src = url;
  15210. }
  15211. }
  15212. else {
  15213. image.src = url;
  15214. }
  15215. }, false);
  15216. xhr.addEventListener("error", function (event) {
  15217. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15218. image.src = url;
  15219. }, false);
  15220. xhr.send();
  15221. }
  15222. else {
  15223. image.src = url;
  15224. }
  15225. }
  15226. else {
  15227. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15228. image.src = url;
  15229. }
  15230. };
  15231. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15232. var _this = this;
  15233. var updateVersion = function (event) {
  15234. // the version is not yet in the DB or we need to update it
  15235. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15236. };
  15237. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15238. };
  15239. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15240. var _this = this;
  15241. if (this.isSupported) {
  15242. var version;
  15243. try {
  15244. var transaction = this.db.transaction(["versions"]);
  15245. transaction.oncomplete = function (event) {
  15246. if (version) {
  15247. // If the version in the JSON file is > than the version in DB
  15248. if (_this.manifestVersionFound > version.data) {
  15249. _this.mustUpdateRessources = true;
  15250. updateInDBCallback();
  15251. }
  15252. else {
  15253. callback(version.data);
  15254. }
  15255. }
  15256. else {
  15257. _this.mustUpdateRessources = true;
  15258. updateInDBCallback();
  15259. }
  15260. };
  15261. transaction.onabort = function (event) {
  15262. callback(-1);
  15263. };
  15264. var getRequest = transaction.objectStore("versions").get(url);
  15265. getRequest.onsuccess = function (event) {
  15266. version = (event.target).result;
  15267. };
  15268. getRequest.onerror = function (event) {
  15269. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15270. callback(-1);
  15271. };
  15272. }
  15273. catch (ex) {
  15274. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15275. callback(-1);
  15276. }
  15277. }
  15278. else {
  15279. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15280. callback(-1);
  15281. }
  15282. };
  15283. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15284. var _this = this;
  15285. if (this.isSupported && !this.hasReachedQuota) {
  15286. try {
  15287. // Open a transaction to the database
  15288. var transaction = this.db.transaction(["versions"], "readwrite");
  15289. // the transaction could abort because of a QuotaExceededError error
  15290. transaction.onabort = function (event) {
  15291. try {
  15292. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15293. _this.hasReachedQuota = true;
  15294. }
  15295. }
  15296. catch (ex) {
  15297. }
  15298. callback(-1);
  15299. };
  15300. transaction.oncomplete = function (event) {
  15301. callback(_this.manifestVersionFound);
  15302. };
  15303. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15304. // Put the scene into the database
  15305. var addRequest = transaction.objectStore("versions").put(newVersion);
  15306. addRequest.onsuccess = function (event) {
  15307. };
  15308. addRequest.onerror = function (event) {
  15309. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15310. };
  15311. }
  15312. catch (ex) {
  15313. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15314. callback(-1);
  15315. }
  15316. }
  15317. else {
  15318. callback(-1);
  15319. }
  15320. };
  15321. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15322. var _this = this;
  15323. var completeUrl = Database.ReturnFullUrlLocation(url);
  15324. var saveAndLoadFile = function (event) {
  15325. // the scene is not yet in the DB, let's try to save it
  15326. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15327. };
  15328. this._checkVersionFromDB(completeUrl, function (version) {
  15329. if (version !== -1) {
  15330. if (!_this.mustUpdateRessources) {
  15331. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15332. }
  15333. else {
  15334. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15335. }
  15336. }
  15337. else {
  15338. errorCallback();
  15339. }
  15340. });
  15341. };
  15342. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15343. if (this.isSupported) {
  15344. var targetStore;
  15345. if (url.indexOf(".babylon") !== -1) {
  15346. targetStore = "scenes";
  15347. }
  15348. else {
  15349. targetStore = "textures";
  15350. }
  15351. var file;
  15352. var transaction = this.db.transaction([targetStore]);
  15353. transaction.oncomplete = function (event) {
  15354. if (file) {
  15355. callback(file.data);
  15356. }
  15357. else {
  15358. notInDBCallback();
  15359. }
  15360. };
  15361. transaction.onabort = function (event) {
  15362. notInDBCallback();
  15363. };
  15364. var getRequest = transaction.objectStore(targetStore).get(url);
  15365. getRequest.onsuccess = function (event) {
  15366. file = (event.target).result;
  15367. };
  15368. getRequest.onerror = function (event) {
  15369. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15370. notInDBCallback();
  15371. };
  15372. }
  15373. else {
  15374. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15375. callback();
  15376. }
  15377. };
  15378. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15379. var _this = this;
  15380. if (this.isSupported) {
  15381. var targetStore;
  15382. if (url.indexOf(".babylon") !== -1) {
  15383. targetStore = "scenes";
  15384. }
  15385. else {
  15386. targetStore = "textures";
  15387. }
  15388. // Create XHR
  15389. var xhr = new XMLHttpRequest(), fileData;
  15390. xhr.open("GET", url, true);
  15391. if (useArrayBuffer) {
  15392. xhr.responseType = "arraybuffer";
  15393. }
  15394. xhr.onprogress = progressCallback;
  15395. xhr.addEventListener("load", function () {
  15396. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15397. // Blob as response (XHR2)
  15398. //fileData = xhr.responseText;
  15399. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15400. if (!_this.hasReachedQuota) {
  15401. // Open a transaction to the database
  15402. var transaction = _this.db.transaction([targetStore], "readwrite");
  15403. // the transaction could abort because of a QuotaExceededError error
  15404. transaction.onabort = function (event) {
  15405. try {
  15406. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15407. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15408. this.hasReachedQuota = true;
  15409. }
  15410. }
  15411. catch (ex) {
  15412. }
  15413. callback(fileData);
  15414. };
  15415. transaction.oncomplete = function (event) {
  15416. callback(fileData);
  15417. };
  15418. var newFile;
  15419. if (targetStore === "scenes") {
  15420. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15421. }
  15422. else {
  15423. newFile = { textureUrl: url, data: fileData };
  15424. }
  15425. try {
  15426. // Put the scene into the database
  15427. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15428. addRequest.onsuccess = function (event) {
  15429. };
  15430. addRequest.onerror = function (event) {
  15431. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15432. };
  15433. }
  15434. catch (ex) {
  15435. callback(fileData);
  15436. }
  15437. }
  15438. else {
  15439. callback(fileData);
  15440. }
  15441. }
  15442. else {
  15443. callback();
  15444. }
  15445. }, false);
  15446. xhr.addEventListener("error", function (event) {
  15447. BABYLON.Tools.Error("error on XHR request.");
  15448. callback();
  15449. }, false);
  15450. xhr.send();
  15451. }
  15452. else {
  15453. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15454. callback();
  15455. }
  15456. };
  15457. Database.isUASupportingBlobStorage = true;
  15458. Database.parseURL = function (url) {
  15459. var a = document.createElement('a');
  15460. a.href = url;
  15461. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15462. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15463. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15464. return absLocation;
  15465. };
  15466. Database.ReturnFullUrlLocation = function (url) {
  15467. if (url.indexOf("http:/") === -1) {
  15468. return (BABYLON.Database.parseURL(window.location.href) + url);
  15469. }
  15470. else {
  15471. return url;
  15472. }
  15473. };
  15474. return Database;
  15475. })();
  15476. BABYLON.Database = Database;
  15477. })(BABYLON || (BABYLON = {}));
  15478. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15479. (function (BABYLON) {
  15480. var SpriteManager = (function () {
  15481. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15482. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15483. this.name = name;
  15484. this.cellSize = cellSize;
  15485. this.sprites = new Array();
  15486. this.renderingGroupId = 0;
  15487. this.fogEnabled = true;
  15488. this._vertexDeclaration = [4, 4, 4, 4];
  15489. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15490. this._capacity = capacity;
  15491. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15492. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15493. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15494. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15495. this._scene = scene;
  15496. this._scene.spriteManagers.push(this);
  15497. // VBO
  15498. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15499. var indices = [];
  15500. var index = 0;
  15501. for (var count = 0; count < capacity; count++) {
  15502. indices.push(index);
  15503. indices.push(index + 1);
  15504. indices.push(index + 2);
  15505. indices.push(index);
  15506. indices.push(index + 2);
  15507. indices.push(index + 3);
  15508. index += 4;
  15509. }
  15510. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15511. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15512. // Effects
  15513. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15514. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15515. }
  15516. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15517. var arrayOffset = index * 16;
  15518. if (offsetX === 0)
  15519. offsetX = this._epsilon;
  15520. else if (offsetX === 1)
  15521. offsetX = 1 - this._epsilon;
  15522. if (offsetY === 0)
  15523. offsetY = this._epsilon;
  15524. else if (offsetY === 1)
  15525. offsetY = 1 - this._epsilon;
  15526. this._vertices[arrayOffset] = sprite.position.x;
  15527. this._vertices[arrayOffset + 1] = sprite.position.y;
  15528. this._vertices[arrayOffset + 2] = sprite.position.z;
  15529. this._vertices[arrayOffset + 3] = sprite.angle;
  15530. this._vertices[arrayOffset + 4] = sprite.width;
  15531. this._vertices[arrayOffset + 5] = sprite.height;
  15532. this._vertices[arrayOffset + 6] = offsetX;
  15533. this._vertices[arrayOffset + 7] = offsetY;
  15534. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  15535. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  15536. var offset = (sprite.cellIndex / rowSize) >> 0;
  15537. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  15538. this._vertices[arrayOffset + 11] = offset;
  15539. // Color
  15540. this._vertices[arrayOffset + 12] = sprite.color.r;
  15541. this._vertices[arrayOffset + 13] = sprite.color.g;
  15542. this._vertices[arrayOffset + 14] = sprite.color.b;
  15543. this._vertices[arrayOffset + 15] = sprite.color.a;
  15544. };
  15545. SpriteManager.prototype.render = function () {
  15546. // Check
  15547. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15548. return;
  15549. var engine = this._scene.getEngine();
  15550. var baseSize = this._spriteTexture.getBaseSize();
  15551. // Sprites
  15552. var deltaTime = engine.getDeltaTime();
  15553. var max = Math.min(this._capacity, this.sprites.length);
  15554. var rowSize = baseSize.width / this.cellSize;
  15555. var offset = 0;
  15556. for (var index = 0; index < max; index++) {
  15557. var sprite = this.sprites[index];
  15558. if (!sprite) {
  15559. continue;
  15560. }
  15561. sprite._animate(deltaTime);
  15562. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15563. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15564. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15565. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15566. }
  15567. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15568. // Render
  15569. var effect = this._effectBase;
  15570. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15571. effect = this._effectFog;
  15572. }
  15573. engine.enableEffect(effect);
  15574. var viewMatrix = this._scene.getViewMatrix();
  15575. effect.setTexture("diffuseSampler", this._spriteTexture);
  15576. effect.setMatrix("view", viewMatrix);
  15577. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15578. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15579. // Fog
  15580. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15581. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15582. effect.setColor3("vFogColor", this._scene.fogColor);
  15583. }
  15584. // VBOs
  15585. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15586. // Draw order
  15587. effect.setBool("alphaTest", true);
  15588. engine.setColorWrite(false);
  15589. engine.draw(true, 0, max * 6);
  15590. engine.setColorWrite(true);
  15591. effect.setBool("alphaTest", false);
  15592. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15593. engine.draw(true, 0, max * 6);
  15594. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15595. };
  15596. SpriteManager.prototype.dispose = function () {
  15597. if (this._vertexBuffer) {
  15598. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15599. this._vertexBuffer = null;
  15600. }
  15601. if (this._indexBuffer) {
  15602. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15603. this._indexBuffer = null;
  15604. }
  15605. if (this._spriteTexture) {
  15606. this._spriteTexture.dispose();
  15607. this._spriteTexture = null;
  15608. }
  15609. // Remove from scene
  15610. var index = this._scene.spriteManagers.indexOf(this);
  15611. this._scene.spriteManagers.splice(index, 1);
  15612. // Callback
  15613. if (this.onDispose) {
  15614. this.onDispose();
  15615. }
  15616. };
  15617. return SpriteManager;
  15618. })();
  15619. BABYLON.SpriteManager = SpriteManager;
  15620. })(BABYLON || (BABYLON = {}));
  15621. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15622. (function (BABYLON) {
  15623. var Sprite = (function () {
  15624. function Sprite(name, manager) {
  15625. this.name = name;
  15626. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15627. this.width = 1.0;
  15628. this.height = 1.0;
  15629. this.angle = 0;
  15630. this.cellIndex = 0;
  15631. this.invertU = 0;
  15632. this.invertV = 0;
  15633. this.animations = new Array();
  15634. this._animationStarted = false;
  15635. this._loopAnimation = false;
  15636. this._fromIndex = 0;
  15637. this._toIndex = 0;
  15638. this._delay = 0;
  15639. this._direction = 1;
  15640. this._frameCount = 0;
  15641. this._time = 0;
  15642. this._manager = manager;
  15643. this._manager.sprites.push(this);
  15644. this.position = BABYLON.Vector3.Zero();
  15645. }
  15646. Object.defineProperty(Sprite.prototype, "size", {
  15647. get: function () {
  15648. return this.width;
  15649. },
  15650. set: function (value) {
  15651. this.width = value;
  15652. this.height = value;
  15653. },
  15654. enumerable: true,
  15655. configurable: true
  15656. });
  15657. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15658. this._fromIndex = from;
  15659. this._toIndex = to;
  15660. this._loopAnimation = loop;
  15661. this._delay = delay;
  15662. this._animationStarted = true;
  15663. this._direction = from < to ? 1 : -1;
  15664. this.cellIndex = from;
  15665. this._time = 0;
  15666. };
  15667. Sprite.prototype.stopAnimation = function () {
  15668. this._animationStarted = false;
  15669. };
  15670. Sprite.prototype._animate = function (deltaTime) {
  15671. if (!this._animationStarted)
  15672. return;
  15673. this._time += deltaTime;
  15674. if (this._time > this._delay) {
  15675. this._time = this._time % this._delay;
  15676. this.cellIndex += this._direction;
  15677. if (this.cellIndex == this._toIndex) {
  15678. if (this._loopAnimation) {
  15679. this.cellIndex = this._fromIndex;
  15680. }
  15681. else {
  15682. this._animationStarted = false;
  15683. if (this.disposeWhenFinishedAnimating) {
  15684. this.dispose();
  15685. }
  15686. }
  15687. }
  15688. }
  15689. };
  15690. Sprite.prototype.dispose = function () {
  15691. for (var i = 0; i < this._manager.sprites.length; i++) {
  15692. if (this._manager.sprites[i] == this) {
  15693. this._manager.sprites.splice(i, 1);
  15694. }
  15695. }
  15696. };
  15697. return Sprite;
  15698. })();
  15699. BABYLON.Sprite = Sprite;
  15700. })(BABYLON || (BABYLON = {}));
  15701. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15702. (function (BABYLON) {
  15703. var Layer = (function () {
  15704. function Layer(name, imgUrl, scene, isBackground, color) {
  15705. this.name = name;
  15706. this._vertexDeclaration = [2];
  15707. this._vertexStrideSize = 2 * 4;
  15708. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15709. this.isBackground = isBackground === undefined ? true : isBackground;
  15710. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15711. this._scene = scene;
  15712. this._scene.layers.push(this);
  15713. // VBO
  15714. var vertices = [];
  15715. vertices.push(1, 1);
  15716. vertices.push(-1, 1);
  15717. vertices.push(-1, -1);
  15718. vertices.push(1, -1);
  15719. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15720. // Indices
  15721. var indices = [];
  15722. indices.push(0);
  15723. indices.push(1);
  15724. indices.push(2);
  15725. indices.push(0);
  15726. indices.push(2);
  15727. indices.push(3);
  15728. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15729. // Effects
  15730. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15731. }
  15732. Layer.prototype.render = function () {
  15733. // Check
  15734. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15735. return;
  15736. var engine = this._scene.getEngine();
  15737. // Render
  15738. engine.enableEffect(this._effect);
  15739. engine.setState(false);
  15740. // Texture
  15741. this._effect.setTexture("textureSampler", this.texture);
  15742. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15743. // Color
  15744. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15745. // VBOs
  15746. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15747. // Draw order
  15748. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15749. engine.draw(true, 0, 6);
  15750. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15751. };
  15752. Layer.prototype.dispose = function () {
  15753. if (this._vertexBuffer) {
  15754. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15755. this._vertexBuffer = null;
  15756. }
  15757. if (this._indexBuffer) {
  15758. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15759. this._indexBuffer = null;
  15760. }
  15761. if (this.texture) {
  15762. this.texture.dispose();
  15763. this.texture = null;
  15764. }
  15765. // Remove from scene
  15766. var index = this._scene.layers.indexOf(this);
  15767. this._scene.layers.splice(index, 1);
  15768. // Callback
  15769. if (this.onDispose) {
  15770. this.onDispose();
  15771. }
  15772. };
  15773. return Layer;
  15774. })();
  15775. BABYLON.Layer = Layer;
  15776. })(BABYLON || (BABYLON = {}));
  15777. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15778. (function (BABYLON) {
  15779. var Particle = (function () {
  15780. function Particle() {
  15781. this.position = BABYLON.Vector3.Zero();
  15782. this.direction = BABYLON.Vector3.Zero();
  15783. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15784. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15785. this.lifeTime = 1.0;
  15786. this.age = 0;
  15787. this.size = 0;
  15788. this.angle = 0;
  15789. this.angularSpeed = 0;
  15790. }
  15791. Particle.prototype.copyTo = function (other) {
  15792. other.position.copyFrom(this.position);
  15793. other.direction.copyFrom(this.direction);
  15794. other.color.copyFrom(this.color);
  15795. other.colorStep.copyFrom(this.colorStep);
  15796. other.lifeTime = this.lifeTime;
  15797. other.age = this.age;
  15798. other.size = this.size;
  15799. other.angle = this.angle;
  15800. other.angularSpeed = this.angularSpeed;
  15801. };
  15802. return Particle;
  15803. })();
  15804. BABYLON.Particle = Particle;
  15805. })(BABYLON || (BABYLON = {}));
  15806. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15807. (function (BABYLON) {
  15808. var randomNumber = function (min, max) {
  15809. if (min === max) {
  15810. return (min);
  15811. }
  15812. var random = Math.random();
  15813. return ((random * (max - min)) + min);
  15814. };
  15815. var ParticleSystem = (function () {
  15816. function ParticleSystem(name, capacity, scene, customEffect) {
  15817. var _this = this;
  15818. this.name = name;
  15819. this.renderingGroupId = 0;
  15820. this.emitter = null;
  15821. this.emitRate = 10;
  15822. this.manualEmitCount = -1;
  15823. this.updateSpeed = 0.01;
  15824. this.targetStopDuration = 0;
  15825. this.disposeOnStop = false;
  15826. this.minEmitPower = 1;
  15827. this.maxEmitPower = 1;
  15828. this.minLifeTime = 1;
  15829. this.maxLifeTime = 1;
  15830. this.minSize = 1;
  15831. this.maxSize = 1;
  15832. this.minAngularSpeed = 0;
  15833. this.maxAngularSpeed = 0;
  15834. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15835. this.forceDepthWrite = false;
  15836. this.gravity = BABYLON.Vector3.Zero();
  15837. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15838. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15839. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15840. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15841. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15842. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15843. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15844. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15845. this.particles = new Array();
  15846. this._vertexDeclaration = [3, 4, 4];
  15847. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15848. this._stockParticles = new Array();
  15849. this._newPartsExcess = 0;
  15850. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15851. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15852. this._scaledDirection = BABYLON.Vector3.Zero();
  15853. this._scaledGravity = BABYLON.Vector3.Zero();
  15854. this._currentRenderId = -1;
  15855. this._started = false;
  15856. this._stopped = false;
  15857. this._actualFrame = 0;
  15858. this.id = name;
  15859. this._capacity = capacity;
  15860. this._scene = scene;
  15861. this._customEffect = customEffect;
  15862. scene.particleSystems.push(this);
  15863. // VBO
  15864. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15865. var indices = [];
  15866. var index = 0;
  15867. for (var count = 0; count < capacity; count++) {
  15868. indices.push(index);
  15869. indices.push(index + 1);
  15870. indices.push(index + 2);
  15871. indices.push(index);
  15872. indices.push(index + 2);
  15873. indices.push(index + 3);
  15874. index += 4;
  15875. }
  15876. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15877. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15878. // Default behaviors
  15879. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15880. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15881. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15882. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15883. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15884. };
  15885. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15886. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15887. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15888. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15889. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15890. };
  15891. this.updateFunction = function (particles) {
  15892. for (var index = 0; index < particles.length; index++) {
  15893. var particle = particles[index];
  15894. particle.age += _this._scaledUpdateSpeed;
  15895. if (particle.age >= particle.lifeTime) {
  15896. _this.recycleParticle(particle);
  15897. index--;
  15898. continue;
  15899. }
  15900. else {
  15901. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15902. particle.color.addInPlace(_this._scaledColorStep);
  15903. if (particle.color.a < 0)
  15904. particle.color.a = 0;
  15905. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15906. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15907. particle.position.addInPlace(_this._scaledDirection);
  15908. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15909. particle.direction.addInPlace(_this._scaledGravity);
  15910. }
  15911. }
  15912. };
  15913. }
  15914. ParticleSystem.prototype.recycleParticle = function (particle) {
  15915. var lastParticle = this.particles.pop();
  15916. if (lastParticle !== particle) {
  15917. lastParticle.copyTo(particle);
  15918. this._stockParticles.push(lastParticle);
  15919. }
  15920. };
  15921. ParticleSystem.prototype.getCapacity = function () {
  15922. return this._capacity;
  15923. };
  15924. ParticleSystem.prototype.isAlive = function () {
  15925. return this._alive;
  15926. };
  15927. ParticleSystem.prototype.isStarted = function () {
  15928. return this._started;
  15929. };
  15930. ParticleSystem.prototype.start = function () {
  15931. this._started = true;
  15932. this._stopped = false;
  15933. this._actualFrame = 0;
  15934. };
  15935. ParticleSystem.prototype.stop = function () {
  15936. this._stopped = true;
  15937. };
  15938. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15939. var offset = index * 11;
  15940. this._vertices[offset] = particle.position.x;
  15941. this._vertices[offset + 1] = particle.position.y;
  15942. this._vertices[offset + 2] = particle.position.z;
  15943. this._vertices[offset + 3] = particle.color.r;
  15944. this._vertices[offset + 4] = particle.color.g;
  15945. this._vertices[offset + 5] = particle.color.b;
  15946. this._vertices[offset + 6] = particle.color.a;
  15947. this._vertices[offset + 7] = particle.angle;
  15948. this._vertices[offset + 8] = particle.size;
  15949. this._vertices[offset + 9] = offsetX;
  15950. this._vertices[offset + 10] = offsetY;
  15951. };
  15952. ParticleSystem.prototype._update = function (newParticles) {
  15953. // Update current
  15954. this._alive = this.particles.length > 0;
  15955. this.updateFunction(this.particles);
  15956. // Add new ones
  15957. var worldMatrix;
  15958. if (this.emitter.position) {
  15959. worldMatrix = this.emitter.getWorldMatrix();
  15960. }
  15961. else {
  15962. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15963. }
  15964. for (var index = 0; index < newParticles; index++) {
  15965. if (this.particles.length === this._capacity) {
  15966. break;
  15967. }
  15968. if (this._stockParticles.length !== 0) {
  15969. var particle = this._stockParticles.pop();
  15970. particle.age = 0;
  15971. }
  15972. else {
  15973. particle = new BABYLON.Particle();
  15974. }
  15975. this.particles.push(particle);
  15976. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15977. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15978. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15979. particle.size = randomNumber(this.minSize, this.maxSize);
  15980. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15981. this.startPositionFunction(worldMatrix, particle.position);
  15982. var step = randomNumber(0, 1.0);
  15983. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15984. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15985. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15986. }
  15987. };
  15988. ParticleSystem.prototype._getEffect = function () {
  15989. if (this._customEffect) {
  15990. return this._customEffect;
  15991. }
  15992. ;
  15993. var defines = [];
  15994. if (this._scene.clipPlane) {
  15995. defines.push("#define CLIPPLANE");
  15996. }
  15997. // Effect
  15998. var join = defines.join("\n");
  15999. if (this._cachedDefines !== join) {
  16000. this._cachedDefines = join;
  16001. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16002. }
  16003. return this._effect;
  16004. };
  16005. ParticleSystem.prototype.animate = function () {
  16006. if (!this._started)
  16007. return;
  16008. var effect = this._getEffect();
  16009. // Check
  16010. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16011. return;
  16012. if (this._currentRenderId === this._scene.getRenderId()) {
  16013. return;
  16014. }
  16015. this._currentRenderId = this._scene.getRenderId();
  16016. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16017. // determine the number of particles we need to create
  16018. var emitCout;
  16019. if (this.manualEmitCount > -1) {
  16020. emitCout = this.manualEmitCount;
  16021. this.manualEmitCount = 0;
  16022. }
  16023. else {
  16024. emitCout = this.emitRate;
  16025. }
  16026. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16027. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16028. if (this._newPartsExcess > 1.0) {
  16029. newParticles += this._newPartsExcess >> 0;
  16030. this._newPartsExcess -= this._newPartsExcess >> 0;
  16031. }
  16032. this._alive = false;
  16033. if (!this._stopped) {
  16034. this._actualFrame += this._scaledUpdateSpeed;
  16035. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16036. this.stop();
  16037. }
  16038. else {
  16039. newParticles = 0;
  16040. }
  16041. this._update(newParticles);
  16042. // Stopped?
  16043. if (this._stopped) {
  16044. if (!this._alive) {
  16045. this._started = false;
  16046. if (this.disposeOnStop) {
  16047. this._scene._toBeDisposed.push(this);
  16048. }
  16049. }
  16050. }
  16051. // Update VBO
  16052. var offset = 0;
  16053. for (var index = 0; index < this.particles.length; index++) {
  16054. var particle = this.particles[index];
  16055. this._appendParticleVertex(offset++, particle, 0, 0);
  16056. this._appendParticleVertex(offset++, particle, 1, 0);
  16057. this._appendParticleVertex(offset++, particle, 1, 1);
  16058. this._appendParticleVertex(offset++, particle, 0, 1);
  16059. }
  16060. var engine = this._scene.getEngine();
  16061. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16062. };
  16063. ParticleSystem.prototype.render = function () {
  16064. var effect = this._getEffect();
  16065. // Check
  16066. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16067. return 0;
  16068. var engine = this._scene.getEngine();
  16069. // Render
  16070. engine.enableEffect(effect);
  16071. engine.setState(false);
  16072. var viewMatrix = this._scene.getViewMatrix();
  16073. effect.setTexture("diffuseSampler", this.particleTexture);
  16074. effect.setMatrix("view", viewMatrix);
  16075. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16076. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16077. if (this._scene.clipPlane) {
  16078. var clipPlane = this._scene.clipPlane;
  16079. var invView = viewMatrix.clone();
  16080. invView.invert();
  16081. effect.setMatrix("invView", invView);
  16082. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16083. }
  16084. // VBOs
  16085. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16086. // Draw order
  16087. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16088. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16089. }
  16090. else {
  16091. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16092. }
  16093. if (this.forceDepthWrite) {
  16094. engine.setDepthWrite(true);
  16095. }
  16096. engine.draw(true, 0, this.particles.length * 6);
  16097. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16098. return this.particles.length;
  16099. };
  16100. ParticleSystem.prototype.dispose = function () {
  16101. if (this._vertexBuffer) {
  16102. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16103. this._vertexBuffer = null;
  16104. }
  16105. if (this._indexBuffer) {
  16106. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16107. this._indexBuffer = null;
  16108. }
  16109. if (this.particleTexture) {
  16110. this.particleTexture.dispose();
  16111. this.particleTexture = null;
  16112. }
  16113. // Remove from scene
  16114. var index = this._scene.particleSystems.indexOf(this);
  16115. this._scene.particleSystems.splice(index, 1);
  16116. // Callback
  16117. if (this.onDispose) {
  16118. this.onDispose();
  16119. }
  16120. };
  16121. // Clone
  16122. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16123. var result = new ParticleSystem(name, this._capacity, this._scene);
  16124. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16125. if (newEmitter === undefined) {
  16126. newEmitter = this.emitter;
  16127. }
  16128. result.emitter = newEmitter;
  16129. if (this.particleTexture) {
  16130. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16131. }
  16132. result.start();
  16133. return result;
  16134. };
  16135. // Statics
  16136. ParticleSystem.BLENDMODE_ONEONE = 0;
  16137. ParticleSystem.BLENDMODE_STANDARD = 1;
  16138. return ParticleSystem;
  16139. })();
  16140. BABYLON.ParticleSystem = ParticleSystem;
  16141. })(BABYLON || (BABYLON = {}));
  16142. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16143. (function (BABYLON) {
  16144. var Animation = (function () {
  16145. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16146. this.name = name;
  16147. this.targetProperty = targetProperty;
  16148. this.framePerSecond = framePerSecond;
  16149. this.dataType = dataType;
  16150. this.loopMode = loopMode;
  16151. this._offsetsCache = {};
  16152. this._highLimitsCache = {};
  16153. this._stopped = false;
  16154. this.targetPropertyPath = targetProperty.split(".");
  16155. this.dataType = dataType;
  16156. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16157. }
  16158. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16159. var dataType = undefined;
  16160. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16161. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16162. }
  16163. else if (from instanceof BABYLON.Quaternion) {
  16164. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16165. }
  16166. else if (from instanceof BABYLON.Vector3) {
  16167. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16168. }
  16169. else if (from instanceof BABYLON.Vector2) {
  16170. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16171. }
  16172. else if (from instanceof BABYLON.Color3) {
  16173. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16174. }
  16175. if (dataType == undefined) {
  16176. return null;
  16177. }
  16178. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16179. var keys = [];
  16180. keys.push({ frame: 0, value: from });
  16181. keys.push({ frame: totalFrame, value: to });
  16182. animation.setKeys(keys);
  16183. mesh.animations.push(animation);
  16184. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16185. };
  16186. // Methods
  16187. Animation.prototype.isStopped = function () {
  16188. return this._stopped;
  16189. };
  16190. Animation.prototype.getKeys = function () {
  16191. return this._keys;
  16192. };
  16193. Animation.prototype.getEasingFunction = function () {
  16194. return this._easingFunction;
  16195. };
  16196. Animation.prototype.setEasingFunction = function (easingFunction) {
  16197. this._easingFunction = easingFunction;
  16198. };
  16199. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16200. return startValue + (endValue - startValue) * gradient;
  16201. };
  16202. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16203. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16204. };
  16205. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16206. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16207. };
  16208. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16209. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16210. };
  16211. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16212. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16213. };
  16214. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16215. var startScale = new BABYLON.Vector3(0, 0, 0);
  16216. var startRotation = new BABYLON.Quaternion();
  16217. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16218. startValue.decompose(startScale, startRotation, startTranslation);
  16219. var endScale = new BABYLON.Vector3(0, 0, 0);
  16220. var endRotation = new BABYLON.Quaternion();
  16221. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16222. endValue.decompose(endScale, endRotation, endTranslation);
  16223. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16224. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16225. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16226. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16227. return result;
  16228. };
  16229. Animation.prototype.clone = function () {
  16230. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16231. clone.setKeys(this._keys);
  16232. return clone;
  16233. };
  16234. Animation.prototype.setKeys = function (values) {
  16235. this._keys = values.slice(0);
  16236. this._offsetsCache = {};
  16237. this._highLimitsCache = {};
  16238. };
  16239. Animation.prototype._getKeyValue = function (value) {
  16240. if (typeof value === "function") {
  16241. return value();
  16242. }
  16243. return value;
  16244. };
  16245. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16246. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16247. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16248. }
  16249. this.currentFrame = currentFrame;
  16250. // Try to get a hash to find the right key
  16251. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  16252. if (this._keys[startKey].frame >= currentFrame) {
  16253. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16254. startKey--;
  16255. }
  16256. }
  16257. for (var key = startKey; key < this._keys.length; key++) {
  16258. if (this._keys[key + 1].frame >= currentFrame) {
  16259. var startValue = this._getKeyValue(this._keys[key].value);
  16260. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16261. // gradient : percent of currentFrame between the frame inf and the frame sup
  16262. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16263. // check for easingFunction and correction of gradient
  16264. if (this._easingFunction != null) {
  16265. gradient = this._easingFunction.ease(gradient);
  16266. }
  16267. switch (this.dataType) {
  16268. case Animation.ANIMATIONTYPE_FLOAT:
  16269. switch (loopMode) {
  16270. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16271. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16272. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16273. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16274. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16275. }
  16276. break;
  16277. case Animation.ANIMATIONTYPE_QUATERNION:
  16278. var quaternion = null;
  16279. switch (loopMode) {
  16280. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16281. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16282. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16283. break;
  16284. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16285. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16286. break;
  16287. }
  16288. return quaternion;
  16289. case Animation.ANIMATIONTYPE_VECTOR3:
  16290. switch (loopMode) {
  16291. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16292. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16293. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16294. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16295. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16296. }
  16297. case Animation.ANIMATIONTYPE_VECTOR2:
  16298. switch (loopMode) {
  16299. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16300. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16301. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16302. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16303. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16304. }
  16305. case Animation.ANIMATIONTYPE_COLOR3:
  16306. switch (loopMode) {
  16307. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16308. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16309. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16310. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16311. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16312. }
  16313. case Animation.ANIMATIONTYPE_MATRIX:
  16314. switch (loopMode) {
  16315. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16316. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16317. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16318. return startValue;
  16319. }
  16320. default:
  16321. break;
  16322. }
  16323. break;
  16324. }
  16325. }
  16326. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16327. };
  16328. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16329. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16330. this._stopped = true;
  16331. return false;
  16332. }
  16333. var returnValue = true;
  16334. // Adding a start key at frame 0 if missing
  16335. if (this._keys[0].frame !== 0) {
  16336. var newKey = { frame: 0, value: this._keys[0].value };
  16337. this._keys.splice(0, 0, newKey);
  16338. }
  16339. // Check limits
  16340. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16341. from = this._keys[0].frame;
  16342. }
  16343. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16344. to = this._keys[this._keys.length - 1].frame;
  16345. }
  16346. // Compute ratio
  16347. var range = to - from;
  16348. var offsetValue;
  16349. // ratio represents the frame delta between from and to
  16350. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16351. var highLimitValue = 0;
  16352. if (ratio > range && !loop) {
  16353. returnValue = false;
  16354. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16355. }
  16356. else {
  16357. // Get max value if required
  16358. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16359. var keyOffset = to.toString() + from.toString();
  16360. if (!this._offsetsCache[keyOffset]) {
  16361. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16362. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16363. switch (this.dataType) {
  16364. case Animation.ANIMATIONTYPE_FLOAT:
  16365. this._offsetsCache[keyOffset] = toValue - fromValue;
  16366. break;
  16367. case Animation.ANIMATIONTYPE_QUATERNION:
  16368. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16369. break;
  16370. case Animation.ANIMATIONTYPE_VECTOR3:
  16371. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16372. case Animation.ANIMATIONTYPE_VECTOR2:
  16373. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16374. case Animation.ANIMATIONTYPE_COLOR3:
  16375. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16376. default:
  16377. break;
  16378. }
  16379. this._highLimitsCache[keyOffset] = toValue;
  16380. }
  16381. highLimitValue = this._highLimitsCache[keyOffset];
  16382. offsetValue = this._offsetsCache[keyOffset];
  16383. }
  16384. }
  16385. if (offsetValue === undefined) {
  16386. switch (this.dataType) {
  16387. case Animation.ANIMATIONTYPE_FLOAT:
  16388. offsetValue = 0;
  16389. break;
  16390. case Animation.ANIMATIONTYPE_QUATERNION:
  16391. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16392. break;
  16393. case Animation.ANIMATIONTYPE_VECTOR3:
  16394. offsetValue = BABYLON.Vector3.Zero();
  16395. break;
  16396. case Animation.ANIMATIONTYPE_VECTOR2:
  16397. offsetValue = BABYLON.Vector2.Zero();
  16398. break;
  16399. case Animation.ANIMATIONTYPE_COLOR3:
  16400. offsetValue = BABYLON.Color3.Black();
  16401. }
  16402. }
  16403. // Compute value
  16404. var repeatCount = (ratio / range) >> 0;
  16405. var currentFrame = returnValue ? from + ratio % range : to;
  16406. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16407. // Set value
  16408. if (this.targetPropertyPath.length > 1) {
  16409. var property = this._target[this.targetPropertyPath[0]];
  16410. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16411. property = property[this.targetPropertyPath[index]];
  16412. }
  16413. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16414. }
  16415. else {
  16416. this._target[this.targetPropertyPath[0]] = currentValue;
  16417. }
  16418. if (this._target.markAsDirty) {
  16419. this._target.markAsDirty(this.targetProperty);
  16420. }
  16421. if (!returnValue) {
  16422. this._stopped = true;
  16423. }
  16424. return returnValue;
  16425. };
  16426. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16427. get: function () {
  16428. return Animation._ANIMATIONTYPE_FLOAT;
  16429. },
  16430. enumerable: true,
  16431. configurable: true
  16432. });
  16433. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16434. get: function () {
  16435. return Animation._ANIMATIONTYPE_VECTOR3;
  16436. },
  16437. enumerable: true,
  16438. configurable: true
  16439. });
  16440. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16441. get: function () {
  16442. return Animation._ANIMATIONTYPE_VECTOR2;
  16443. },
  16444. enumerable: true,
  16445. configurable: true
  16446. });
  16447. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16448. get: function () {
  16449. return Animation._ANIMATIONTYPE_QUATERNION;
  16450. },
  16451. enumerable: true,
  16452. configurable: true
  16453. });
  16454. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16455. get: function () {
  16456. return Animation._ANIMATIONTYPE_MATRIX;
  16457. },
  16458. enumerable: true,
  16459. configurable: true
  16460. });
  16461. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16462. get: function () {
  16463. return Animation._ANIMATIONTYPE_COLOR3;
  16464. },
  16465. enumerable: true,
  16466. configurable: true
  16467. });
  16468. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16469. get: function () {
  16470. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16471. },
  16472. enumerable: true,
  16473. configurable: true
  16474. });
  16475. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16476. get: function () {
  16477. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16478. },
  16479. enumerable: true,
  16480. configurable: true
  16481. });
  16482. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16483. get: function () {
  16484. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16485. },
  16486. enumerable: true,
  16487. configurable: true
  16488. });
  16489. // Statics
  16490. Animation._ANIMATIONTYPE_FLOAT = 0;
  16491. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16492. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16493. Animation._ANIMATIONTYPE_MATRIX = 3;
  16494. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16495. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16496. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16497. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16498. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16499. return Animation;
  16500. })();
  16501. BABYLON.Animation = Animation;
  16502. })(BABYLON || (BABYLON = {}));
  16503. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16504. (function (BABYLON) {
  16505. var Animatable = (function () {
  16506. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16507. if (fromFrame === void 0) { fromFrame = 0; }
  16508. if (toFrame === void 0) { toFrame = 100; }
  16509. if (loopAnimation === void 0) { loopAnimation = false; }
  16510. if (speedRatio === void 0) { speedRatio = 1.0; }
  16511. this.target = target;
  16512. this.fromFrame = fromFrame;
  16513. this.toFrame = toFrame;
  16514. this.loopAnimation = loopAnimation;
  16515. this.speedRatio = speedRatio;
  16516. this.onAnimationEnd = onAnimationEnd;
  16517. this._animations = new Array();
  16518. this._paused = false;
  16519. this.animationStarted = false;
  16520. if (animations) {
  16521. this.appendAnimations(target, animations);
  16522. }
  16523. this._scene = scene;
  16524. scene._activeAnimatables.push(this);
  16525. }
  16526. // Methods
  16527. Animatable.prototype.appendAnimations = function (target, animations) {
  16528. for (var index = 0; index < animations.length; index++) {
  16529. var animation = animations[index];
  16530. animation._target = target;
  16531. this._animations.push(animation);
  16532. }
  16533. };
  16534. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16535. var animations = this._animations;
  16536. for (var index = 0; index < animations.length; index++) {
  16537. if (animations[index].targetProperty === property) {
  16538. return animations[index];
  16539. }
  16540. }
  16541. return null;
  16542. };
  16543. Animatable.prototype.pause = function () {
  16544. if (this._paused) {
  16545. return;
  16546. }
  16547. this._paused = true;
  16548. };
  16549. Animatable.prototype.restart = function () {
  16550. this._paused = false;
  16551. };
  16552. Animatable.prototype.stop = function () {
  16553. var index = this._scene._activeAnimatables.indexOf(this);
  16554. if (index > -1) {
  16555. this._scene._activeAnimatables.splice(index, 1);
  16556. }
  16557. if (this.onAnimationEnd) {
  16558. this.onAnimationEnd();
  16559. }
  16560. };
  16561. Animatable.prototype._animate = function (delay) {
  16562. if (this._paused) {
  16563. if (!this._pausedDelay) {
  16564. this._pausedDelay = delay;
  16565. }
  16566. return true;
  16567. }
  16568. if (!this._localDelayOffset) {
  16569. this._localDelayOffset = delay;
  16570. }
  16571. else if (this._pausedDelay) {
  16572. this._localDelayOffset += delay - this._pausedDelay;
  16573. this._pausedDelay = null;
  16574. }
  16575. // Animating
  16576. var running = false;
  16577. var animations = this._animations;
  16578. for (var index = 0; index < animations.length; index++) {
  16579. var animation = animations[index];
  16580. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16581. running = running || isRunning;
  16582. }
  16583. if (!running) {
  16584. // Remove from active animatables
  16585. index = this._scene._activeAnimatables.indexOf(this);
  16586. this._scene._activeAnimatables.splice(index, 1);
  16587. }
  16588. if (!running && this.onAnimationEnd) {
  16589. this.onAnimationEnd();
  16590. }
  16591. return running;
  16592. };
  16593. return Animatable;
  16594. })();
  16595. BABYLON.Animatable = Animatable;
  16596. })(BABYLON || (BABYLON = {}));
  16597. //# sourceMappingURL=babylon.animatable.js.map
  16598. var BABYLON;
  16599. (function (BABYLON) {
  16600. var EasingFunction = (function () {
  16601. function EasingFunction() {
  16602. // Properties
  16603. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16604. }
  16605. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16606. get: function () {
  16607. return EasingFunction._EASINGMODE_EASEIN;
  16608. },
  16609. enumerable: true,
  16610. configurable: true
  16611. });
  16612. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16613. get: function () {
  16614. return EasingFunction._EASINGMODE_EASEOUT;
  16615. },
  16616. enumerable: true,
  16617. configurable: true
  16618. });
  16619. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16620. get: function () {
  16621. return EasingFunction._EASINGMODE_EASEINOUT;
  16622. },
  16623. enumerable: true,
  16624. configurable: true
  16625. });
  16626. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16627. var n = Math.min(Math.max(easingMode, 0), 2);
  16628. this._easingMode = n;
  16629. };
  16630. EasingFunction.prototype.getEasingMode = function () {
  16631. return this._easingMode;
  16632. };
  16633. EasingFunction.prototype.easeInCore = function (gradient) {
  16634. throw new Error('You must implement this method');
  16635. };
  16636. EasingFunction.prototype.ease = function (gradient) {
  16637. switch (this._easingMode) {
  16638. case EasingFunction.EASINGMODE_EASEIN:
  16639. return this.easeInCore(gradient);
  16640. case EasingFunction.EASINGMODE_EASEOUT:
  16641. return (1 - this.easeInCore(1 - gradient));
  16642. }
  16643. if (gradient >= 0.5) {
  16644. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16645. }
  16646. return (this.easeInCore(gradient * 2) * 0.5);
  16647. };
  16648. //Statics
  16649. EasingFunction._EASINGMODE_EASEIN = 0;
  16650. EasingFunction._EASINGMODE_EASEOUT = 1;
  16651. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16652. return EasingFunction;
  16653. })();
  16654. BABYLON.EasingFunction = EasingFunction;
  16655. var CircleEase = (function (_super) {
  16656. __extends(CircleEase, _super);
  16657. function CircleEase() {
  16658. _super.apply(this, arguments);
  16659. }
  16660. CircleEase.prototype.easeInCore = function (gradient) {
  16661. gradient = Math.max(0, Math.min(1, gradient));
  16662. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16663. };
  16664. return CircleEase;
  16665. })(EasingFunction);
  16666. BABYLON.CircleEase = CircleEase;
  16667. var BackEase = (function (_super) {
  16668. __extends(BackEase, _super);
  16669. function BackEase(amplitude) {
  16670. if (amplitude === void 0) { amplitude = 1; }
  16671. _super.call(this);
  16672. this.amplitude = amplitude;
  16673. }
  16674. BackEase.prototype.easeInCore = function (gradient) {
  16675. var num = Math.max(0, this.amplitude);
  16676. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16677. };
  16678. return BackEase;
  16679. })(EasingFunction);
  16680. BABYLON.BackEase = BackEase;
  16681. var BounceEase = (function (_super) {
  16682. __extends(BounceEase, _super);
  16683. function BounceEase(bounces, bounciness) {
  16684. if (bounces === void 0) { bounces = 3; }
  16685. if (bounciness === void 0) { bounciness = 2; }
  16686. _super.call(this);
  16687. this.bounces = bounces;
  16688. this.bounciness = bounciness;
  16689. }
  16690. BounceEase.prototype.easeInCore = function (gradient) {
  16691. var y = Math.max(0.0, this.bounces);
  16692. var bounciness = this.bounciness;
  16693. if (bounciness <= 1.0) {
  16694. bounciness = 1.001;
  16695. }
  16696. var num9 = Math.pow(bounciness, y);
  16697. var num5 = 1.0 - bounciness;
  16698. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16699. var num15 = gradient * num4;
  16700. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16701. var num3 = Math.floor(num65);
  16702. var num13 = num3 + 1.0;
  16703. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16704. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16705. var num7 = (num8 + num12) * 0.5;
  16706. var num6 = gradient - num7;
  16707. var num2 = num7 - num8;
  16708. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16709. };
  16710. return BounceEase;
  16711. })(EasingFunction);
  16712. BABYLON.BounceEase = BounceEase;
  16713. var CubicEase = (function (_super) {
  16714. __extends(CubicEase, _super);
  16715. function CubicEase() {
  16716. _super.apply(this, arguments);
  16717. }
  16718. CubicEase.prototype.easeInCore = function (gradient) {
  16719. return (gradient * gradient * gradient);
  16720. };
  16721. return CubicEase;
  16722. })(EasingFunction);
  16723. BABYLON.CubicEase = CubicEase;
  16724. var ElasticEase = (function (_super) {
  16725. __extends(ElasticEase, _super);
  16726. function ElasticEase(oscillations, springiness) {
  16727. if (oscillations === void 0) { oscillations = 3; }
  16728. if (springiness === void 0) { springiness = 3; }
  16729. _super.call(this);
  16730. this.oscillations = oscillations;
  16731. this.springiness = springiness;
  16732. }
  16733. ElasticEase.prototype.easeInCore = function (gradient) {
  16734. var num2;
  16735. var num3 = Math.max(0.0, this.oscillations);
  16736. var num = Math.max(0.0, this.springiness);
  16737. if (num == 0) {
  16738. num2 = gradient;
  16739. }
  16740. else {
  16741. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16742. }
  16743. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16744. };
  16745. return ElasticEase;
  16746. })(EasingFunction);
  16747. BABYLON.ElasticEase = ElasticEase;
  16748. var ExponentialEase = (function (_super) {
  16749. __extends(ExponentialEase, _super);
  16750. function ExponentialEase(exponent) {
  16751. if (exponent === void 0) { exponent = 2; }
  16752. _super.call(this);
  16753. this.exponent = exponent;
  16754. }
  16755. ExponentialEase.prototype.easeInCore = function (gradient) {
  16756. if (this.exponent <= 0) {
  16757. return gradient;
  16758. }
  16759. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16760. };
  16761. return ExponentialEase;
  16762. })(EasingFunction);
  16763. BABYLON.ExponentialEase = ExponentialEase;
  16764. var PowerEase = (function (_super) {
  16765. __extends(PowerEase, _super);
  16766. function PowerEase(power) {
  16767. if (power === void 0) { power = 2; }
  16768. _super.call(this);
  16769. this.power = power;
  16770. }
  16771. PowerEase.prototype.easeInCore = function (gradient) {
  16772. var y = Math.max(0.0, this.power);
  16773. return Math.pow(gradient, y);
  16774. };
  16775. return PowerEase;
  16776. })(EasingFunction);
  16777. BABYLON.PowerEase = PowerEase;
  16778. var QuadraticEase = (function (_super) {
  16779. __extends(QuadraticEase, _super);
  16780. function QuadraticEase() {
  16781. _super.apply(this, arguments);
  16782. }
  16783. QuadraticEase.prototype.easeInCore = function (gradient) {
  16784. return (gradient * gradient);
  16785. };
  16786. return QuadraticEase;
  16787. })(EasingFunction);
  16788. BABYLON.QuadraticEase = QuadraticEase;
  16789. var QuarticEase = (function (_super) {
  16790. __extends(QuarticEase, _super);
  16791. function QuarticEase() {
  16792. _super.apply(this, arguments);
  16793. }
  16794. QuarticEase.prototype.easeInCore = function (gradient) {
  16795. return (gradient * gradient * gradient * gradient);
  16796. };
  16797. return QuarticEase;
  16798. })(EasingFunction);
  16799. BABYLON.QuarticEase = QuarticEase;
  16800. var QuinticEase = (function (_super) {
  16801. __extends(QuinticEase, _super);
  16802. function QuinticEase() {
  16803. _super.apply(this, arguments);
  16804. }
  16805. QuinticEase.prototype.easeInCore = function (gradient) {
  16806. return (gradient * gradient * gradient * gradient * gradient);
  16807. };
  16808. return QuinticEase;
  16809. })(EasingFunction);
  16810. BABYLON.QuinticEase = QuinticEase;
  16811. var SineEase = (function (_super) {
  16812. __extends(SineEase, _super);
  16813. function SineEase() {
  16814. _super.apply(this, arguments);
  16815. }
  16816. SineEase.prototype.easeInCore = function (gradient) {
  16817. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16818. };
  16819. return SineEase;
  16820. })(EasingFunction);
  16821. BABYLON.SineEase = SineEase;
  16822. var BezierCurveEase = (function (_super) {
  16823. __extends(BezierCurveEase, _super);
  16824. function BezierCurveEase(x1, y1, x2, y2) {
  16825. if (x1 === void 0) { x1 = 0; }
  16826. if (y1 === void 0) { y1 = 0; }
  16827. if (x2 === void 0) { x2 = 1; }
  16828. if (y2 === void 0) { y2 = 1; }
  16829. _super.call(this);
  16830. this.x1 = x1;
  16831. this.y1 = y1;
  16832. this.x2 = x2;
  16833. this.y2 = y2;
  16834. }
  16835. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16836. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16837. };
  16838. return BezierCurveEase;
  16839. })(EasingFunction);
  16840. BABYLON.BezierCurveEase = BezierCurveEase;
  16841. })(BABYLON || (BABYLON = {}));
  16842. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16843. (function (BABYLON) {
  16844. var Octree = (function () {
  16845. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16846. if (maxDepth === void 0) { maxDepth = 2; }
  16847. this.maxDepth = maxDepth;
  16848. this.dynamicContent = new Array();
  16849. this._maxBlockCapacity = maxBlockCapacity || 64;
  16850. this._selectionContent = new BABYLON.SmartArray(1024);
  16851. this._creationFunc = creationFunc;
  16852. }
  16853. // Methods
  16854. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16855. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16856. };
  16857. Octree.prototype.addMesh = function (entry) {
  16858. for (var index = 0; index < this.blocks.length; index++) {
  16859. var block = this.blocks[index];
  16860. block.addEntry(entry);
  16861. }
  16862. };
  16863. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16864. this._selectionContent.reset();
  16865. for (var index = 0; index < this.blocks.length; index++) {
  16866. var block = this.blocks[index];
  16867. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16868. }
  16869. if (allowDuplicate) {
  16870. this._selectionContent.concat(this.dynamicContent);
  16871. }
  16872. else {
  16873. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16874. }
  16875. return this._selectionContent;
  16876. };
  16877. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16878. this._selectionContent.reset();
  16879. for (var index = 0; index < this.blocks.length; index++) {
  16880. var block = this.blocks[index];
  16881. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16882. }
  16883. if (allowDuplicate) {
  16884. this._selectionContent.concat(this.dynamicContent);
  16885. }
  16886. else {
  16887. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16888. }
  16889. return this._selectionContent;
  16890. };
  16891. Octree.prototype.intersectsRay = function (ray) {
  16892. this._selectionContent.reset();
  16893. for (var index = 0; index < this.blocks.length; index++) {
  16894. var block = this.blocks[index];
  16895. block.intersectsRay(ray, this._selectionContent);
  16896. }
  16897. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16898. return this._selectionContent;
  16899. };
  16900. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16901. target.blocks = new Array();
  16902. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16903. for (var x = 0; x < 2; x++) {
  16904. for (var y = 0; y < 2; y++) {
  16905. for (var z = 0; z < 2; z++) {
  16906. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16907. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16908. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16909. block.addEntries(entries);
  16910. target.blocks.push(block);
  16911. }
  16912. }
  16913. }
  16914. };
  16915. Octree.CreationFuncForMeshes = function (entry, block) {
  16916. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16917. block.entries.push(entry);
  16918. }
  16919. };
  16920. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16921. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16922. block.entries.push(entry);
  16923. }
  16924. };
  16925. return Octree;
  16926. })();
  16927. BABYLON.Octree = Octree;
  16928. })(BABYLON || (BABYLON = {}));
  16929. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16930. (function (BABYLON) {
  16931. var OctreeBlock = (function () {
  16932. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16933. this.entries = new Array();
  16934. this._boundingVectors = new Array();
  16935. this._capacity = capacity;
  16936. this._depth = depth;
  16937. this._maxDepth = maxDepth;
  16938. this._creationFunc = creationFunc;
  16939. this._minPoint = minPoint;
  16940. this._maxPoint = maxPoint;
  16941. this._boundingVectors.push(minPoint.clone());
  16942. this._boundingVectors.push(maxPoint.clone());
  16943. this._boundingVectors.push(minPoint.clone());
  16944. this._boundingVectors[2].x = maxPoint.x;
  16945. this._boundingVectors.push(minPoint.clone());
  16946. this._boundingVectors[3].y = maxPoint.y;
  16947. this._boundingVectors.push(minPoint.clone());
  16948. this._boundingVectors[4].z = maxPoint.z;
  16949. this._boundingVectors.push(maxPoint.clone());
  16950. this._boundingVectors[5].z = minPoint.z;
  16951. this._boundingVectors.push(maxPoint.clone());
  16952. this._boundingVectors[6].x = minPoint.x;
  16953. this._boundingVectors.push(maxPoint.clone());
  16954. this._boundingVectors[7].y = minPoint.y;
  16955. }
  16956. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16957. // Property
  16958. get: function () {
  16959. return this._capacity;
  16960. },
  16961. enumerable: true,
  16962. configurable: true
  16963. });
  16964. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16965. get: function () {
  16966. return this._minPoint;
  16967. },
  16968. enumerable: true,
  16969. configurable: true
  16970. });
  16971. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16972. get: function () {
  16973. return this._maxPoint;
  16974. },
  16975. enumerable: true,
  16976. configurable: true
  16977. });
  16978. // Methods
  16979. OctreeBlock.prototype.addEntry = function (entry) {
  16980. if (this.blocks) {
  16981. for (var index = 0; index < this.blocks.length; index++) {
  16982. var block = this.blocks[index];
  16983. block.addEntry(entry);
  16984. }
  16985. return;
  16986. }
  16987. this._creationFunc(entry, this);
  16988. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16989. this.createInnerBlocks();
  16990. }
  16991. };
  16992. OctreeBlock.prototype.addEntries = function (entries) {
  16993. for (var index = 0; index < entries.length; index++) {
  16994. var mesh = entries[index];
  16995. this.addEntry(mesh);
  16996. }
  16997. };
  16998. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16999. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17000. if (this.blocks) {
  17001. for (var index = 0; index < this.blocks.length; index++) {
  17002. var block = this.blocks[index];
  17003. block.select(frustumPlanes, selection, allowDuplicate);
  17004. }
  17005. return;
  17006. }
  17007. if (allowDuplicate) {
  17008. selection.concat(this.entries);
  17009. }
  17010. else {
  17011. selection.concatWithNoDuplicate(this.entries);
  17012. }
  17013. }
  17014. };
  17015. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17016. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17017. if (this.blocks) {
  17018. for (var index = 0; index < this.blocks.length; index++) {
  17019. var block = this.blocks[index];
  17020. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17021. }
  17022. return;
  17023. }
  17024. if (allowDuplicate) {
  17025. selection.concat(this.entries);
  17026. }
  17027. else {
  17028. selection.concatWithNoDuplicate(this.entries);
  17029. }
  17030. }
  17031. };
  17032. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17033. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17034. if (this.blocks) {
  17035. for (var index = 0; index < this.blocks.length; index++) {
  17036. var block = this.blocks[index];
  17037. block.intersectsRay(ray, selection);
  17038. }
  17039. return;
  17040. }
  17041. selection.concatWithNoDuplicate(this.entries);
  17042. }
  17043. };
  17044. OctreeBlock.prototype.createInnerBlocks = function () {
  17045. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17046. };
  17047. return OctreeBlock;
  17048. })();
  17049. BABYLON.OctreeBlock = OctreeBlock;
  17050. })(BABYLON || (BABYLON = {}));
  17051. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17052. (function (BABYLON) {
  17053. var Bone = (function () {
  17054. function Bone(name, skeleton, parentBone, matrix) {
  17055. this.name = name;
  17056. this.children = new Array();
  17057. this.animations = new Array();
  17058. this._worldTransform = new BABYLON.Matrix();
  17059. this._absoluteTransform = new BABYLON.Matrix();
  17060. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17061. this._skeleton = skeleton;
  17062. this._matrix = matrix;
  17063. this._baseMatrix = matrix;
  17064. skeleton.bones.push(this);
  17065. if (parentBone) {
  17066. this._parent = parentBone;
  17067. parentBone.children.push(this);
  17068. }
  17069. else {
  17070. this._parent = null;
  17071. }
  17072. this._updateDifferenceMatrix();
  17073. }
  17074. // Members
  17075. Bone.prototype.getParent = function () {
  17076. return this._parent;
  17077. };
  17078. Bone.prototype.getLocalMatrix = function () {
  17079. return this._matrix;
  17080. };
  17081. Bone.prototype.getBaseMatrix = function () {
  17082. return this._baseMatrix;
  17083. };
  17084. Bone.prototype.getWorldMatrix = function () {
  17085. return this._worldTransform;
  17086. };
  17087. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17088. return this._invertedAbsoluteTransform;
  17089. };
  17090. Bone.prototype.getAbsoluteMatrix = function () {
  17091. var matrix = this._matrix.clone();
  17092. var parent = this._parent;
  17093. while (parent) {
  17094. matrix = matrix.multiply(parent.getLocalMatrix());
  17095. parent = parent.getParent();
  17096. }
  17097. return matrix;
  17098. };
  17099. // Methods
  17100. Bone.prototype.updateMatrix = function (matrix) {
  17101. this._matrix = matrix;
  17102. this._skeleton._markAsDirty();
  17103. this._updateDifferenceMatrix();
  17104. };
  17105. Bone.prototype._updateDifferenceMatrix = function () {
  17106. if (this._parent) {
  17107. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17108. }
  17109. else {
  17110. this._absoluteTransform.copyFrom(this._matrix);
  17111. }
  17112. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17113. for (var index = 0; index < this.children.length; index++) {
  17114. this.children[index]._updateDifferenceMatrix();
  17115. }
  17116. };
  17117. Bone.prototype.markAsDirty = function () {
  17118. this._skeleton._markAsDirty();
  17119. };
  17120. return Bone;
  17121. })();
  17122. BABYLON.Bone = Bone;
  17123. })(BABYLON || (BABYLON = {}));
  17124. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17125. (function (BABYLON) {
  17126. var Skeleton = (function () {
  17127. function Skeleton(name, id, scene) {
  17128. this.name = name;
  17129. this.id = id;
  17130. this.bones = new Array();
  17131. this._isDirty = true;
  17132. this._identity = BABYLON.Matrix.Identity();
  17133. this.bones = [];
  17134. this._scene = scene;
  17135. scene.skeletons.push(this);
  17136. }
  17137. // Members
  17138. Skeleton.prototype.getTransformMatrices = function () {
  17139. return this._transformMatrices;
  17140. };
  17141. // Methods
  17142. Skeleton.prototype._markAsDirty = function () {
  17143. this._isDirty = true;
  17144. };
  17145. Skeleton.prototype.prepare = function () {
  17146. if (!this._isDirty) {
  17147. return;
  17148. }
  17149. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17150. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17151. }
  17152. for (var index = 0; index < this.bones.length; index++) {
  17153. var bone = this.bones[index];
  17154. var parentBone = bone.getParent();
  17155. if (parentBone) {
  17156. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17157. }
  17158. else {
  17159. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17160. }
  17161. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17162. }
  17163. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17164. this._isDirty = false;
  17165. this._scene._activeBones += this.bones.length;
  17166. };
  17167. Skeleton.prototype.getAnimatables = function () {
  17168. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17169. this._animatables = [];
  17170. for (var index = 0; index < this.bones.length; index++) {
  17171. this._animatables.push(this.bones[index]);
  17172. }
  17173. }
  17174. return this._animatables;
  17175. };
  17176. Skeleton.prototype.clone = function (name, id) {
  17177. var result = new Skeleton(name, id || name, this._scene);
  17178. for (var index = 0; index < this.bones.length; index++) {
  17179. var source = this.bones[index];
  17180. var parentBone = null;
  17181. if (source.getParent()) {
  17182. var parentIndex = this.bones.indexOf(source.getParent());
  17183. parentBone = result.bones[parentIndex];
  17184. }
  17185. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17186. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17187. }
  17188. return result;
  17189. };
  17190. return Skeleton;
  17191. })();
  17192. BABYLON.Skeleton = Skeleton;
  17193. })(BABYLON || (BABYLON = {}));
  17194. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17195. (function (BABYLON) {
  17196. var PostProcess = (function () {
  17197. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17198. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17199. this.name = name;
  17200. this.width = -1;
  17201. this.height = -1;
  17202. this._reusable = false;
  17203. this._textures = new BABYLON.SmartArray(2);
  17204. this._currentRenderTextureInd = 0;
  17205. if (camera != null) {
  17206. this._camera = camera;
  17207. this._scene = camera.getScene();
  17208. camera.attachPostProcess(this);
  17209. this._engine = this._scene.getEngine();
  17210. }
  17211. else {
  17212. this._engine = engine;
  17213. }
  17214. this._renderRatio = ratio;
  17215. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17216. this._reusable = reusable || false;
  17217. samplers = samplers || [];
  17218. samplers.push("textureSampler");
  17219. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17220. }
  17221. PostProcess.prototype.isReusable = function () {
  17222. return this._reusable;
  17223. };
  17224. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17225. camera = camera || this._camera;
  17226. var scene = camera.getScene();
  17227. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17228. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17229. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17230. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17231. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17232. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17233. if (this._textures.length > 0) {
  17234. for (var i = 0; i < this._textures.length; i++) {
  17235. this._engine._releaseTexture(this._textures.data[i]);
  17236. }
  17237. this._textures.reset();
  17238. }
  17239. this.width = desiredWidth;
  17240. this.height = desiredHeight;
  17241. 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 }));
  17242. if (this._reusable) {
  17243. 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 }));
  17244. }
  17245. if (this.onSizeChanged) {
  17246. this.onSizeChanged();
  17247. }
  17248. }
  17249. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17250. if (this.onActivate) {
  17251. this.onActivate(camera);
  17252. }
  17253. // Clear
  17254. if (this.clearColor) {
  17255. this._engine.clear(this.clearColor, true, true);
  17256. }
  17257. else {
  17258. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17259. }
  17260. if (this._reusable) {
  17261. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17262. }
  17263. };
  17264. PostProcess.prototype.apply = function () {
  17265. // Check
  17266. if (!this._effect.isReady())
  17267. return null;
  17268. // States
  17269. this._engine.enableEffect(this._effect);
  17270. this._engine.setState(false);
  17271. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17272. this._engine.setDepthBuffer(false);
  17273. this._engine.setDepthWrite(false);
  17274. // Texture
  17275. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17276. // Parameters
  17277. if (this.onApply) {
  17278. this.onApply(this._effect);
  17279. }
  17280. return this._effect;
  17281. };
  17282. PostProcess.prototype.dispose = function (camera) {
  17283. camera = camera || this._camera;
  17284. if (this._textures.length > 0) {
  17285. for (var i = 0; i < this._textures.length; i++) {
  17286. this._engine._releaseTexture(this._textures.data[i]);
  17287. }
  17288. this._textures.reset();
  17289. }
  17290. if (!camera) {
  17291. return;
  17292. }
  17293. camera.detachPostProcess(this);
  17294. var index = camera._postProcesses.indexOf(this);
  17295. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17296. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17297. }
  17298. };
  17299. return PostProcess;
  17300. })();
  17301. BABYLON.PostProcess = PostProcess;
  17302. })(BABYLON || (BABYLON = {}));
  17303. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17304. (function (BABYLON) {
  17305. var PostProcessManager = (function () {
  17306. function PostProcessManager(scene) {
  17307. this._vertexDeclaration = [2];
  17308. this._vertexStrideSize = 2 * 4;
  17309. this._scene = scene;
  17310. // VBO
  17311. var vertices = [];
  17312. vertices.push(1, 1);
  17313. vertices.push(-1, 1);
  17314. vertices.push(-1, -1);
  17315. vertices.push(1, -1);
  17316. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17317. // Indices
  17318. var indices = [];
  17319. indices.push(0);
  17320. indices.push(1);
  17321. indices.push(2);
  17322. indices.push(0);
  17323. indices.push(2);
  17324. indices.push(3);
  17325. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17326. }
  17327. // Methods
  17328. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17329. var postProcesses = this._scene.activeCamera._postProcesses;
  17330. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17331. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17332. return false;
  17333. }
  17334. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17335. return true;
  17336. };
  17337. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17338. var engine = this._scene.getEngine();
  17339. for (var index = 0; index < postProcesses.length; index++) {
  17340. if (index < postProcesses.length - 1) {
  17341. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17342. }
  17343. else {
  17344. if (targetTexture) {
  17345. engine.bindFramebuffer(targetTexture);
  17346. }
  17347. else {
  17348. engine.restoreDefaultFramebuffer();
  17349. }
  17350. }
  17351. var pp = postProcesses[index];
  17352. var effect = pp.apply();
  17353. if (effect) {
  17354. if (pp.onBeforeRender) {
  17355. pp.onBeforeRender(effect);
  17356. }
  17357. // VBOs
  17358. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17359. // Draw order
  17360. engine.draw(true, 0, 6);
  17361. }
  17362. }
  17363. // Restore depth buffer
  17364. engine.setDepthBuffer(true);
  17365. engine.setDepthWrite(true);
  17366. };
  17367. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17368. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17369. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17370. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17371. return;
  17372. }
  17373. var engine = this._scene.getEngine();
  17374. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17375. if (index < postProcessesTakenIndices.length - 1) {
  17376. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17377. }
  17378. else {
  17379. if (targetTexture) {
  17380. engine.bindFramebuffer(targetTexture);
  17381. }
  17382. else {
  17383. engine.restoreDefaultFramebuffer();
  17384. }
  17385. }
  17386. if (doNotPresent) {
  17387. break;
  17388. }
  17389. var pp = postProcesses[postProcessesTakenIndices[index]];
  17390. var effect = pp.apply();
  17391. if (effect) {
  17392. if (pp.onBeforeRender) {
  17393. pp.onBeforeRender(effect);
  17394. }
  17395. // VBOs
  17396. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17397. // Draw order
  17398. engine.draw(true, 0, 6);
  17399. }
  17400. }
  17401. // Restore depth buffer
  17402. engine.setDepthBuffer(true);
  17403. engine.setDepthWrite(true);
  17404. };
  17405. PostProcessManager.prototype.dispose = function () {
  17406. if (this._vertexBuffer) {
  17407. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17408. this._vertexBuffer = null;
  17409. }
  17410. if (this._indexBuffer) {
  17411. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17412. this._indexBuffer = null;
  17413. }
  17414. };
  17415. return PostProcessManager;
  17416. })();
  17417. BABYLON.PostProcessManager = PostProcessManager;
  17418. })(BABYLON || (BABYLON = {}));
  17419. //# sourceMappingURL=babylon.postProcessManager.js.map
  17420. var BABYLON;
  17421. (function (BABYLON) {
  17422. var PassPostProcess = (function (_super) {
  17423. __extends(PassPostProcess, _super);
  17424. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17425. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17426. }
  17427. return PassPostProcess;
  17428. })(BABYLON.PostProcess);
  17429. BABYLON.PassPostProcess = PassPostProcess;
  17430. })(BABYLON || (BABYLON = {}));
  17431. //# sourceMappingURL=babylon.passPostProcess.js.map
  17432. var BABYLON;
  17433. (function (BABYLON) {
  17434. var BlurPostProcess = (function (_super) {
  17435. __extends(BlurPostProcess, _super);
  17436. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17437. var _this = this;
  17438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17439. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17440. this.direction = direction;
  17441. this.blurWidth = blurWidth;
  17442. this.onApply = function (effect) {
  17443. effect.setFloat2("screenSize", _this.width, _this.height);
  17444. effect.setVector2("direction", _this.direction);
  17445. effect.setFloat("blurWidth", _this.blurWidth);
  17446. };
  17447. }
  17448. return BlurPostProcess;
  17449. })(BABYLON.PostProcess);
  17450. BABYLON.BlurPostProcess = BlurPostProcess;
  17451. })(BABYLON || (BABYLON = {}));
  17452. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17453. var BABYLON;
  17454. (function (BABYLON) {
  17455. var FilterPostProcess = (function (_super) {
  17456. __extends(FilterPostProcess, _super);
  17457. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17458. var _this = this;
  17459. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17460. this.kernelMatrix = kernelMatrix;
  17461. this.onApply = function (effect) {
  17462. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17463. };
  17464. }
  17465. return FilterPostProcess;
  17466. })(BABYLON.PostProcess);
  17467. BABYLON.FilterPostProcess = FilterPostProcess;
  17468. })(BABYLON || (BABYLON = {}));
  17469. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17470. var BABYLON;
  17471. (function (BABYLON) {
  17472. var RefractionPostProcess = (function (_super) {
  17473. __extends(RefractionPostProcess, _super);
  17474. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17475. var _this = this;
  17476. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17477. this.color = color;
  17478. this.depth = depth;
  17479. this.colorLevel = colorLevel;
  17480. this.onActivate = function (cam) {
  17481. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17482. };
  17483. this.onApply = function (effect) {
  17484. effect.setColor3("baseColor", _this.color);
  17485. effect.setFloat("depth", _this.depth);
  17486. effect.setFloat("colorLevel", _this.colorLevel);
  17487. effect.setTexture("refractionSampler", _this._refRexture);
  17488. };
  17489. }
  17490. // Methods
  17491. RefractionPostProcess.prototype.dispose = function (camera) {
  17492. if (this._refRexture) {
  17493. this._refRexture.dispose();
  17494. }
  17495. _super.prototype.dispose.call(this, camera);
  17496. };
  17497. return RefractionPostProcess;
  17498. })(BABYLON.PostProcess);
  17499. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17500. })(BABYLON || (BABYLON = {}));
  17501. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17502. var BABYLON;
  17503. (function (BABYLON) {
  17504. var BlackAndWhitePostProcess = (function (_super) {
  17505. __extends(BlackAndWhitePostProcess, _super);
  17506. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17507. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17508. }
  17509. return BlackAndWhitePostProcess;
  17510. })(BABYLON.PostProcess);
  17511. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17512. })(BABYLON || (BABYLON = {}));
  17513. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17514. var BABYLON;
  17515. (function (BABYLON) {
  17516. var ConvolutionPostProcess = (function (_super) {
  17517. __extends(ConvolutionPostProcess, _super);
  17518. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17519. var _this = this;
  17520. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17521. this.kernel = kernel;
  17522. this.onApply = function (effect) {
  17523. effect.setFloat2("screenSize", _this.width, _this.height);
  17524. effect.setArray("kernel", _this.kernel);
  17525. };
  17526. }
  17527. // Statics
  17528. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17529. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17530. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17531. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17532. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17533. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17534. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17535. return ConvolutionPostProcess;
  17536. })(BABYLON.PostProcess);
  17537. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17538. })(BABYLON || (BABYLON = {}));
  17539. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17540. var BABYLON;
  17541. (function (BABYLON) {
  17542. var FxaaPostProcess = (function (_super) {
  17543. __extends(FxaaPostProcess, _super);
  17544. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17545. var _this = this;
  17546. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17547. this.onSizeChanged = function () {
  17548. _this.texelWidth = 1.0 / _this.width;
  17549. _this.texelHeight = 1.0 / _this.height;
  17550. };
  17551. this.onApply = function (effect) {
  17552. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17553. };
  17554. }
  17555. return FxaaPostProcess;
  17556. })(BABYLON.PostProcess);
  17557. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17558. })(BABYLON || (BABYLON = {}));
  17559. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17560. (function (BABYLON) {
  17561. var LensFlare = (function () {
  17562. function LensFlare(size, position, color, imgUrl, system) {
  17563. this.size = size;
  17564. this.position = position;
  17565. this.dispose = function () {
  17566. if (this.texture) {
  17567. this.texture.dispose();
  17568. }
  17569. // Remove from scene
  17570. var index = this._system.lensFlares.indexOf(this);
  17571. this._system.lensFlares.splice(index, 1);
  17572. };
  17573. this.color = color || new BABYLON.Color3(1, 1, 1);
  17574. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17575. this._system = system;
  17576. system.lensFlares.push(this);
  17577. }
  17578. return LensFlare;
  17579. })();
  17580. BABYLON.LensFlare = LensFlare;
  17581. })(BABYLON || (BABYLON = {}));
  17582. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17583. (function (BABYLON) {
  17584. var LensFlareSystem = (function () {
  17585. function LensFlareSystem(name, emitter, scene) {
  17586. this.name = name;
  17587. this.lensFlares = new Array();
  17588. this.borderLimit = 300;
  17589. this._vertexDeclaration = [2];
  17590. this._vertexStrideSize = 2 * 4;
  17591. this._isEnabled = true;
  17592. this._scene = scene;
  17593. this._emitter = emitter;
  17594. scene.lensFlareSystems.push(this);
  17595. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17596. // VBO
  17597. var vertices = [];
  17598. vertices.push(1, 1);
  17599. vertices.push(-1, 1);
  17600. vertices.push(-1, -1);
  17601. vertices.push(1, -1);
  17602. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17603. // Indices
  17604. var indices = [];
  17605. indices.push(0);
  17606. indices.push(1);
  17607. indices.push(2);
  17608. indices.push(0);
  17609. indices.push(2);
  17610. indices.push(3);
  17611. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17612. // Effects
  17613. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17614. }
  17615. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17616. get: function () {
  17617. return this._isEnabled;
  17618. },
  17619. set: function (value) {
  17620. this._isEnabled = value;
  17621. },
  17622. enumerable: true,
  17623. configurable: true
  17624. });
  17625. LensFlareSystem.prototype.getScene = function () {
  17626. return this._scene;
  17627. };
  17628. LensFlareSystem.prototype.getEmitter = function () {
  17629. return this._emitter;
  17630. };
  17631. LensFlareSystem.prototype.getEmitterPosition = function () {
  17632. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17633. };
  17634. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17635. var position = this.getEmitterPosition();
  17636. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17637. this._positionX = position.x;
  17638. this._positionY = position.y;
  17639. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17640. if (position.z > 0) {
  17641. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17642. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17643. return true;
  17644. }
  17645. }
  17646. return false;
  17647. };
  17648. LensFlareSystem.prototype._isVisible = function () {
  17649. if (!this._isEnabled) {
  17650. return false;
  17651. }
  17652. var emitterPosition = this.getEmitterPosition();
  17653. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17654. var distance = direction.length();
  17655. direction.normalize();
  17656. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17657. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17658. return !pickInfo.hit || pickInfo.distance > distance;
  17659. };
  17660. LensFlareSystem.prototype.render = function () {
  17661. if (!this._effect.isReady())
  17662. return false;
  17663. var engine = this._scene.getEngine();
  17664. var viewport = this._scene.activeCamera.viewport;
  17665. var globalViewport = viewport.toGlobal(engine);
  17666. // Position
  17667. if (!this.computeEffectivePosition(globalViewport)) {
  17668. return false;
  17669. }
  17670. // Visibility
  17671. if (!this._isVisible()) {
  17672. return false;
  17673. }
  17674. // Intensity
  17675. var awayX;
  17676. var awayY;
  17677. if (this._positionX < this.borderLimit + globalViewport.x) {
  17678. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17679. }
  17680. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17681. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17682. }
  17683. else {
  17684. awayX = 0;
  17685. }
  17686. if (this._positionY < this.borderLimit + globalViewport.y) {
  17687. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17688. }
  17689. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17690. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17691. }
  17692. else {
  17693. awayY = 0;
  17694. }
  17695. var away = (awayX > awayY) ? awayX : awayY;
  17696. if (away > this.borderLimit) {
  17697. away = this.borderLimit;
  17698. }
  17699. var intensity = 1.0 - (away / this.borderLimit);
  17700. if (intensity < 0) {
  17701. return false;
  17702. }
  17703. if (intensity > 1.0) {
  17704. intensity = 1.0;
  17705. }
  17706. // Position
  17707. var centerX = globalViewport.x + globalViewport.width / 2;
  17708. var centerY = globalViewport.y + globalViewport.height / 2;
  17709. var distX = centerX - this._positionX;
  17710. var distY = centerY - this._positionY;
  17711. // Effects
  17712. engine.enableEffect(this._effect);
  17713. engine.setState(false);
  17714. engine.setDepthBuffer(false);
  17715. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17716. // VBOs
  17717. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17718. for (var index = 0; index < this.lensFlares.length; index++) {
  17719. var flare = this.lensFlares[index];
  17720. var x = centerX - (distX * flare.position);
  17721. var y = centerY - (distY * flare.position);
  17722. var cw = flare.size;
  17723. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17724. var cx = 2 * (x / globalViewport.width) - 1.0;
  17725. var cy = 1.0 - 2 * (y / globalViewport.height);
  17726. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17727. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17728. // Texture
  17729. this._effect.setTexture("textureSampler", flare.texture);
  17730. // Color
  17731. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17732. // Draw order
  17733. engine.draw(true, 0, 6);
  17734. }
  17735. engine.setDepthBuffer(true);
  17736. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17737. return true;
  17738. };
  17739. LensFlareSystem.prototype.dispose = function () {
  17740. if (this._vertexBuffer) {
  17741. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17742. this._vertexBuffer = null;
  17743. }
  17744. if (this._indexBuffer) {
  17745. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17746. this._indexBuffer = null;
  17747. }
  17748. while (this.lensFlares.length) {
  17749. this.lensFlares[0].dispose();
  17750. }
  17751. // Remove from scene
  17752. var index = this._scene.lensFlareSystems.indexOf(this);
  17753. this._scene.lensFlareSystems.splice(index, 1);
  17754. };
  17755. return LensFlareSystem;
  17756. })();
  17757. BABYLON.LensFlareSystem = LensFlareSystem;
  17758. })(BABYLON || (BABYLON = {}));
  17759. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17760. (function (BABYLON) {
  17761. var IntersectionInfo = (function () {
  17762. function IntersectionInfo(bu, bv, distance) {
  17763. this.bu = bu;
  17764. this.bv = bv;
  17765. this.distance = distance;
  17766. this.faceId = 0;
  17767. this.subMeshId = 0;
  17768. }
  17769. return IntersectionInfo;
  17770. })();
  17771. BABYLON.IntersectionInfo = IntersectionInfo;
  17772. var PickingInfo = (function () {
  17773. function PickingInfo() {
  17774. this.hit = false;
  17775. this.distance = 0;
  17776. this.pickedPoint = null;
  17777. this.pickedMesh = null;
  17778. this.bu = 0;
  17779. this.bv = 0;
  17780. this.faceId = -1;
  17781. this.subMeshId = 0;
  17782. }
  17783. // Methods
  17784. PickingInfo.prototype.getNormal = function () {
  17785. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17786. return null;
  17787. }
  17788. var indices = this.pickedMesh.getIndices();
  17789. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17790. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17791. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17792. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17793. normal0 = normal0.scale(this.bu);
  17794. normal1 = normal1.scale(this.bv);
  17795. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17796. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17797. };
  17798. PickingInfo.prototype.getTextureCoordinates = function () {
  17799. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17800. return null;
  17801. }
  17802. var indices = this.pickedMesh.getIndices();
  17803. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17804. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17805. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17806. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17807. uv0 = uv0.scale(this.bu);
  17808. uv1 = uv1.scale(this.bv);
  17809. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17810. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17811. };
  17812. return PickingInfo;
  17813. })();
  17814. BABYLON.PickingInfo = PickingInfo;
  17815. })(BABYLON || (BABYLON = {}));
  17816. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17817. (function (BABYLON) {
  17818. var FilesInput = (function () {
  17819. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17820. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17821. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17822. this._engine = p_engine;
  17823. this._canvas = p_canvas;
  17824. this._currentScene = p_scene;
  17825. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17826. this._progressCallback = p_progressCallback;
  17827. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17828. this._textureLoadingCallback = p_textureLoadingCallback;
  17829. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17830. }
  17831. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17832. var _this = this;
  17833. if (p_elementToMonitor) {
  17834. this._elementToMonitor = p_elementToMonitor;
  17835. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17836. _this.drag(e);
  17837. }, false);
  17838. this._elementToMonitor.addEventListener("dragover", function (e) {
  17839. _this.drag(e);
  17840. }, false);
  17841. this._elementToMonitor.addEventListener("drop", function (e) {
  17842. _this.drop(e);
  17843. }, false);
  17844. }
  17845. };
  17846. FilesInput.prototype.renderFunction = function () {
  17847. if (this._additionnalRenderLoopLogicCallback) {
  17848. this._additionnalRenderLoopLogicCallback();
  17849. }
  17850. if (this._currentScene) {
  17851. if (this._textureLoadingCallback) {
  17852. var remaining = this._currentScene.getWaitingItemsCount();
  17853. if (remaining > 0) {
  17854. this._textureLoadingCallback(remaining);
  17855. }
  17856. }
  17857. this._currentScene.render();
  17858. }
  17859. };
  17860. FilesInput.prototype.drag = function (e) {
  17861. e.stopPropagation();
  17862. e.preventDefault();
  17863. };
  17864. FilesInput.prototype.drop = function (eventDrop) {
  17865. eventDrop.stopPropagation();
  17866. eventDrop.preventDefault();
  17867. this.loadFiles(eventDrop);
  17868. };
  17869. FilesInput.prototype.loadFiles = function (event) {
  17870. if (this._startingProcessingFilesCallback)
  17871. this._startingProcessingFilesCallback();
  17872. // Handling data transfer via drag'n'drop
  17873. if (event && event.dataTransfer && event.dataTransfer.files) {
  17874. this._filesToLoad = event.dataTransfer.files;
  17875. }
  17876. // Handling files from input files
  17877. if (event && event.target && event.target.files) {
  17878. this._filesToLoad = event.target.files;
  17879. }
  17880. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17881. for (var i = 0; i < this._filesToLoad.length; i++) {
  17882. switch (this._filesToLoad[i].type) {
  17883. case "image/jpeg":
  17884. case "image/png":
  17885. case "image/bmp":
  17886. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17887. break;
  17888. case "image/targa":
  17889. case "image/vnd.ms-dds":
  17890. case "audio/wav":
  17891. case "audio/x-wav":
  17892. case "audio/mp3":
  17893. case "audio/mpeg":
  17894. case "audio/mpeg3":
  17895. case "audio/x-mpeg-3":
  17896. case "audio/ogg":
  17897. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17898. break;
  17899. default:
  17900. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  17901. this._sceneFileToLoad = this._filesToLoad[i];
  17902. }
  17903. break;
  17904. }
  17905. }
  17906. this.reload();
  17907. }
  17908. };
  17909. FilesInput.prototype.reload = function () {
  17910. var _this = this;
  17911. var that = this;
  17912. // If a ".babylon" file has been provided
  17913. if (this._sceneFileToLoad) {
  17914. if (this._currentScene) {
  17915. this._engine.stopRenderLoop();
  17916. this._currentScene.dispose();
  17917. }
  17918. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17919. that._currentScene = newScene;
  17920. // Wait for textures and shaders to be ready
  17921. that._currentScene.executeWhenReady(function () {
  17922. // Attach camera to canvas inputs
  17923. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17924. that._currentScene.createDefaultCameraOrLight();
  17925. }
  17926. that._currentScene.activeCamera.attachControl(that._canvas);
  17927. if (that._sceneLoadedCallback) {
  17928. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17929. }
  17930. that._engine.runRenderLoop(function () {
  17931. that.renderFunction();
  17932. });
  17933. });
  17934. }, function (progress) {
  17935. if (_this._progressCallback) {
  17936. _this._progressCallback(progress);
  17937. }
  17938. });
  17939. }
  17940. else {
  17941. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17942. }
  17943. };
  17944. FilesInput.FilesTextures = new Array();
  17945. FilesInput.FilesToLoad = new Array();
  17946. return FilesInput;
  17947. })();
  17948. BABYLON.FilesInput = FilesInput;
  17949. })(BABYLON || (BABYLON = {}));
  17950. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17951. (function (BABYLON) {
  17952. var OimoJSPlugin = (function () {
  17953. function OimoJSPlugin() {
  17954. this._registeredMeshes = [];
  17955. /**
  17956. * Update the body position according to the mesh position
  17957. * @param mesh
  17958. */
  17959. this.updateBodyPosition = function (mesh) {
  17960. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17961. var registeredMesh = this._registeredMeshes[index];
  17962. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17963. var body = registeredMesh.body.body;
  17964. mesh.computeWorldMatrix(true);
  17965. var center = mesh.getBoundingInfo().boundingBox.center;
  17966. body.setPosition(center.x, center.y, center.z);
  17967. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17968. return;
  17969. }
  17970. // Case where the parent has been updated
  17971. if (registeredMesh.mesh.parent === mesh) {
  17972. mesh.computeWorldMatrix(true);
  17973. registeredMesh.mesh.computeWorldMatrix(true);
  17974. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17975. var absoluteRotation = mesh.rotation;
  17976. body = registeredMesh.body.body;
  17977. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17978. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17979. return;
  17980. }
  17981. }
  17982. };
  17983. }
  17984. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17985. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17986. };
  17987. OimoJSPlugin.prototype.initialize = function (iterations) {
  17988. this._world = new OIMO.World();
  17989. this._world.clear();
  17990. };
  17991. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17992. this._world.gravity = gravity;
  17993. };
  17994. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17995. var body = null;
  17996. this.unregisterMesh(mesh);
  17997. mesh.computeWorldMatrix(true);
  17998. var initialRotation = null;
  17999. if (mesh.rotationQuaternion) {
  18000. initialRotation = mesh.rotationQuaternion.clone();
  18001. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18002. mesh.computeWorldMatrix(true);
  18003. }
  18004. var bbox = mesh.getBoundingInfo().boundingBox;
  18005. // The delta between the mesh position and the mesh bounding box center
  18006. var deltaPosition = mesh.position.subtract(bbox.center);
  18007. // Transform delta position with the rotation
  18008. if (initialRotation) {
  18009. var m = new BABYLON.Matrix();
  18010. initialRotation.toRotationMatrix(m);
  18011. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18012. }
  18013. switch (impostor) {
  18014. case BABYLON.PhysicsEngine.SphereImpostor:
  18015. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18016. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18017. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18018. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18019. body = new OIMO.Body({
  18020. type: 'sphere',
  18021. size: [size],
  18022. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18023. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18024. move: options.mass != 0,
  18025. config: [options.mass, options.friction, options.restitution],
  18026. world: this._world
  18027. });
  18028. break;
  18029. case BABYLON.PhysicsEngine.PlaneImpostor:
  18030. case BABYLON.PhysicsEngine.CylinderImpostor:
  18031. case BABYLON.PhysicsEngine.BoxImpostor:
  18032. var min = bbox.minimumWorld;
  18033. var max = bbox.maximumWorld;
  18034. var box = max.subtract(min);
  18035. var sizeX = this._checkWithEpsilon(box.x);
  18036. var sizeY = this._checkWithEpsilon(box.y);
  18037. var sizeZ = this._checkWithEpsilon(box.z);
  18038. body = new OIMO.Body({
  18039. type: 'box',
  18040. size: [sizeX, sizeY, sizeZ],
  18041. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18042. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18043. move: options.mass != 0,
  18044. config: [options.mass, options.friction, options.restitution],
  18045. world: this._world
  18046. });
  18047. break;
  18048. }
  18049. //If quaternion was set as the rotation of the object
  18050. if (initialRotation) {
  18051. //We have to access the rigid body's properties to set the quaternion.
  18052. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18053. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18054. //update the internal rotation matrix
  18055. body.body.syncShapes();
  18056. }
  18057. this._registeredMeshes.push({
  18058. mesh: mesh,
  18059. body: body,
  18060. delta: deltaPosition
  18061. });
  18062. return body;
  18063. };
  18064. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18065. var types = [], sizes = [], positions = [], rotations = [];
  18066. var initialMesh = parts[0].mesh;
  18067. for (var index = 0; index < parts.length; index++) {
  18068. var part = parts[index];
  18069. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18070. types.push(bodyParameters.type);
  18071. sizes.push.apply(sizes, bodyParameters.size);
  18072. positions.push.apply(positions, bodyParameters.pos);
  18073. rotations.push.apply(rotations, bodyParameters.rot);
  18074. }
  18075. var body = new OIMO.Body({
  18076. type: types,
  18077. size: sizes,
  18078. pos: positions,
  18079. rot: rotations,
  18080. move: options.mass != 0,
  18081. config: [options.mass, options.friction, options.restitution],
  18082. world: this._world
  18083. });
  18084. this._registeredMeshes.push({
  18085. mesh: initialMesh,
  18086. body: body
  18087. });
  18088. return body;
  18089. };
  18090. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18091. var bodyParameters = null;
  18092. var mesh = part.mesh;
  18093. // We need the bounding box/sphere info to compute the physics body
  18094. mesh.computeWorldMatrix();
  18095. switch (part.impostor) {
  18096. case BABYLON.PhysicsEngine.SphereImpostor:
  18097. var bbox = mesh.getBoundingInfo().boundingBox;
  18098. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18099. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18100. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18101. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18102. bodyParameters = {
  18103. type: 'sphere',
  18104. /* bug with oimo : sphere needs 3 sizes in this case */
  18105. size: [size, -1, -1],
  18106. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18107. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18108. };
  18109. break;
  18110. case BABYLON.PhysicsEngine.PlaneImpostor:
  18111. case BABYLON.PhysicsEngine.BoxImpostor:
  18112. bbox = mesh.getBoundingInfo().boundingBox;
  18113. var min = bbox.minimumWorld;
  18114. var max = bbox.maximumWorld;
  18115. var box = max.subtract(min);
  18116. var sizeX = this._checkWithEpsilon(box.x);
  18117. var sizeY = this._checkWithEpsilon(box.y);
  18118. var sizeZ = this._checkWithEpsilon(box.z);
  18119. var relativePosition = mesh.position;
  18120. bodyParameters = {
  18121. type: 'box',
  18122. size: [sizeX, sizeY, sizeZ],
  18123. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18124. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18125. };
  18126. break;
  18127. }
  18128. return bodyParameters;
  18129. };
  18130. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18131. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18132. var registeredMesh = this._registeredMeshes[index];
  18133. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18134. if (registeredMesh.body) {
  18135. this._world.removeRigidBody(registeredMesh.body.body);
  18136. this._unbindBody(registeredMesh.body);
  18137. }
  18138. this._registeredMeshes.splice(index, 1);
  18139. return;
  18140. }
  18141. }
  18142. };
  18143. OimoJSPlugin.prototype._unbindBody = function (body) {
  18144. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18145. var registeredMesh = this._registeredMeshes[index];
  18146. if (registeredMesh.body === body) {
  18147. registeredMesh.body = null;
  18148. }
  18149. }
  18150. };
  18151. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18152. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18153. var registeredMesh = this._registeredMeshes[index];
  18154. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18155. // Get object mass to have a behaviour similar to cannon.js
  18156. var mass = registeredMesh.body.body.massInfo.mass;
  18157. // The force is scaled with the mass of object
  18158. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18159. return;
  18160. }
  18161. }
  18162. };
  18163. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18164. var body1 = null, body2 = null;
  18165. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18166. var registeredMesh = this._registeredMeshes[index];
  18167. if (registeredMesh.mesh === mesh1) {
  18168. body1 = registeredMesh.body.body;
  18169. }
  18170. else if (registeredMesh.mesh === mesh2) {
  18171. body2 = registeredMesh.body.body;
  18172. }
  18173. }
  18174. if (!body1 || !body2) {
  18175. return false;
  18176. }
  18177. if (!options) {
  18178. options = {};
  18179. }
  18180. new OIMO.Link({
  18181. type: options.type,
  18182. body1: body1,
  18183. body2: body2,
  18184. min: options.min,
  18185. max: options.max,
  18186. axe1: options.axe1,
  18187. axe2: options.axe2,
  18188. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18189. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18190. collision: options.collision,
  18191. spring: options.spring,
  18192. world: this._world
  18193. });
  18194. return true;
  18195. };
  18196. OimoJSPlugin.prototype.dispose = function () {
  18197. this._world.clear();
  18198. while (this._registeredMeshes.length) {
  18199. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18200. }
  18201. };
  18202. OimoJSPlugin.prototype.isSupported = function () {
  18203. return OIMO !== undefined;
  18204. };
  18205. OimoJSPlugin.prototype._getLastShape = function (body) {
  18206. var lastShape = body.shapes;
  18207. while (lastShape.next) {
  18208. lastShape = lastShape.next;
  18209. }
  18210. return lastShape;
  18211. };
  18212. OimoJSPlugin.prototype.runOneStep = function (time) {
  18213. this._world.step();
  18214. // Update the position of all registered meshes
  18215. var i = this._registeredMeshes.length;
  18216. var m;
  18217. while (i--) {
  18218. var body = this._registeredMeshes[i].body.body;
  18219. var mesh = this._registeredMeshes[i].mesh;
  18220. var delta = this._registeredMeshes[i].delta;
  18221. if (!body.sleeping) {
  18222. if (body.shapes.next) {
  18223. var parentShape = this._getLastShape(body);
  18224. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18225. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18226. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18227. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18228. if (!mesh.rotationQuaternion) {
  18229. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18230. }
  18231. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18232. mesh.computeWorldMatrix();
  18233. }
  18234. else {
  18235. m = body.getMatrix();
  18236. mtx = BABYLON.Matrix.FromArray(m);
  18237. // Body position
  18238. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18239. if (!delta) {
  18240. mesh.position.x = bodyX;
  18241. mesh.position.y = bodyY;
  18242. mesh.position.z = bodyZ;
  18243. }
  18244. else {
  18245. mesh.position.x = bodyX + delta.x;
  18246. mesh.position.y = bodyY + delta.y;
  18247. mesh.position.z = bodyZ + delta.z;
  18248. }
  18249. if (!mesh.rotationQuaternion) {
  18250. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18251. }
  18252. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18253. mesh.computeWorldMatrix();
  18254. }
  18255. }
  18256. }
  18257. };
  18258. return OimoJSPlugin;
  18259. })();
  18260. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18261. })(BABYLON || (BABYLON = {}));
  18262. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18263. (function (BABYLON) {
  18264. var PhysicsEngine = (function () {
  18265. function PhysicsEngine(plugin) {
  18266. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18267. }
  18268. PhysicsEngine.prototype._initialize = function (gravity) {
  18269. this._currentPlugin.initialize();
  18270. this._setGravity(gravity);
  18271. };
  18272. PhysicsEngine.prototype._runOneStep = function (delta) {
  18273. if (delta > 0.1) {
  18274. delta = 0.1;
  18275. }
  18276. else if (delta <= 0) {
  18277. delta = 1.0 / 60.0;
  18278. }
  18279. this._currentPlugin.runOneStep(delta);
  18280. };
  18281. PhysicsEngine.prototype._setGravity = function (gravity) {
  18282. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18283. this._currentPlugin.setGravity(this.gravity);
  18284. };
  18285. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18286. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18287. };
  18288. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18289. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18290. };
  18291. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18292. this._currentPlugin.unregisterMesh(mesh);
  18293. };
  18294. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18295. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18296. };
  18297. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18298. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18299. };
  18300. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18301. this._currentPlugin.updateBodyPosition(mesh);
  18302. };
  18303. PhysicsEngine.prototype.dispose = function () {
  18304. this._currentPlugin.dispose();
  18305. };
  18306. PhysicsEngine.prototype.isSupported = function () {
  18307. return this._currentPlugin.isSupported();
  18308. };
  18309. // Statics
  18310. PhysicsEngine.NoImpostor = 0;
  18311. PhysicsEngine.SphereImpostor = 1;
  18312. PhysicsEngine.BoxImpostor = 2;
  18313. PhysicsEngine.PlaneImpostor = 3;
  18314. PhysicsEngine.MeshImpostor = 4;
  18315. PhysicsEngine.CapsuleImpostor = 5;
  18316. PhysicsEngine.ConeImpostor = 6;
  18317. PhysicsEngine.CylinderImpostor = 7;
  18318. PhysicsEngine.ConvexHullImpostor = 8;
  18319. PhysicsEngine.Epsilon = 0.001;
  18320. return PhysicsEngine;
  18321. })();
  18322. BABYLON.PhysicsEngine = PhysicsEngine;
  18323. })(BABYLON || (BABYLON = {}));
  18324. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18325. (function (BABYLON) {
  18326. var serializeLight = function (light) {
  18327. var serializationObject = {};
  18328. serializationObject.name = light.name;
  18329. serializationObject.id = light.id;
  18330. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18331. if (light instanceof BABYLON.PointLight) {
  18332. serializationObject.type = 0;
  18333. serializationObject.position = light.position.asArray();
  18334. }
  18335. else if (light instanceof BABYLON.DirectionalLight) {
  18336. serializationObject.type = 1;
  18337. var directionalLight = light;
  18338. serializationObject.position = directionalLight.position.asArray();
  18339. serializationObject.direction = directionalLight.direction.asArray();
  18340. }
  18341. else if (light instanceof BABYLON.SpotLight) {
  18342. serializationObject.type = 2;
  18343. var spotLight = light;
  18344. serializationObject.position = spotLight.position.asArray();
  18345. serializationObject.direction = spotLight.position.asArray();
  18346. serializationObject.angle = spotLight.angle;
  18347. serializationObject.exponent = spotLight.exponent;
  18348. }
  18349. else if (light instanceof BABYLON.HemisphericLight) {
  18350. serializationObject.type = 3;
  18351. var hemisphericLight = light;
  18352. serializationObject.direction = hemisphericLight.direction.asArray();
  18353. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18354. }
  18355. if (light.intensity) {
  18356. serializationObject.intensity = light.intensity;
  18357. }
  18358. serializationObject.range = light.range;
  18359. serializationObject.diffuse = light.diffuse.asArray();
  18360. serializationObject.specular = light.specular.asArray();
  18361. return serializationObject;
  18362. };
  18363. var serializeFresnelParameter = function (fresnelParameter) {
  18364. var serializationObject = {};
  18365. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18366. serializationObject.leftColor = fresnelParameter.leftColor;
  18367. serializationObject.rightColor = fresnelParameter.rightColor;
  18368. serializationObject.bias = fresnelParameter.bias;
  18369. serializationObject.power = fresnelParameter.power;
  18370. return serializationObject;
  18371. };
  18372. var appendAnimations = function (source, destination) {
  18373. if (source.animations) {
  18374. destination.animations = [];
  18375. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18376. var animation = source.animations[animationIndex];
  18377. destination.animations.push(serializeAnimation(animation));
  18378. }
  18379. }
  18380. };
  18381. var serializeCamera = function (camera) {
  18382. var serializationObject = {};
  18383. serializationObject.name = camera.name;
  18384. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18385. serializationObject.id = camera.id;
  18386. serializationObject.position = camera.position.asArray();
  18387. // Parent
  18388. if (camera.parent) {
  18389. serializationObject.parentId = camera.parent.id;
  18390. }
  18391. serializationObject.fov = camera.fov;
  18392. serializationObject.minZ = camera.minZ;
  18393. serializationObject.maxZ = camera.maxZ;
  18394. serializationObject.inertia = camera.inertia;
  18395. //setting the type
  18396. if (camera instanceof BABYLON.FreeCamera) {
  18397. serializationObject.type = "FreeCamera";
  18398. }
  18399. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18400. serializationObject.type = "ArcRotateCamera";
  18401. }
  18402. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18403. serializationObject.type = "AnaglyphArcRotateCamera";
  18404. }
  18405. else if (camera instanceof BABYLON.GamepadCamera) {
  18406. serializationObject.type = "GamepadCamera";
  18407. }
  18408. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18409. serializationObject.type = "AnaglyphFreeCamera";
  18410. }
  18411. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18412. serializationObject.type = "DeviceOrientationCamera";
  18413. }
  18414. else if (camera instanceof BABYLON.FollowCamera) {
  18415. serializationObject.type = "FollowCamera";
  18416. }
  18417. else if (camera instanceof BABYLON.OculusCamera) {
  18418. serializationObject.type = "OculusCamera";
  18419. }
  18420. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18421. serializationObject.type = "OculusGamepadCamera";
  18422. }
  18423. else if (camera instanceof BABYLON.TouchCamera) {
  18424. serializationObject.type = "TouchCamera";
  18425. }
  18426. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18427. serializationObject.type = "VirtualJoysticksCamera";
  18428. }
  18429. else if (camera instanceof BABYLON.WebVRCamera) {
  18430. serializationObject.type = "WebVRCamera";
  18431. }
  18432. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18433. serializationObject.type = "VRDeviceOrientationCamera";
  18434. }
  18435. //special properties of specific cameras
  18436. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18437. var arcCamera = camera;
  18438. serializationObject.alpha = arcCamera.alpha;
  18439. serializationObject.beta = arcCamera.beta;
  18440. serializationObject.radius = arcCamera.radius;
  18441. if (arcCamera.target && arcCamera.target.id) {
  18442. serializationObject.lockedTargetId = arcCamera.target.id;
  18443. }
  18444. }
  18445. else if (camera instanceof BABYLON.FollowCamera) {
  18446. var followCam = camera;
  18447. serializationObject.radius = followCam.radius;
  18448. serializationObject.heightOffset = followCam.heightOffset;
  18449. serializationObject.rotationOffset = followCam.rotationOffset;
  18450. }
  18451. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18452. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  18453. if (camera['_eyeSpace'] !== undefined) {
  18454. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18455. }
  18456. }
  18457. //general properties that not all cameras have. The [] is due to typescript's type safety
  18458. if (camera['speed'] !== undefined) {
  18459. serializationObject.speed = camera['speed'];
  18460. }
  18461. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18462. serializationObject.target = camera['target'].asArray();
  18463. }
  18464. // Target
  18465. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18466. serializationObject.rotation = camera['rotation'].asArray();
  18467. }
  18468. // Locked target
  18469. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18470. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18471. }
  18472. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18473. serializationObject.applyGravity = camera['applyGravity'] || false;
  18474. if (camera['ellipsoid']) {
  18475. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18476. }
  18477. // Animations
  18478. appendAnimations(camera, serializationObject);
  18479. // Layer mask
  18480. serializationObject.layerMask = camera.layerMask;
  18481. return serializationObject;
  18482. };
  18483. var serializeAnimation = function (animation) {
  18484. var serializationObject = {};
  18485. serializationObject.name = animation.name;
  18486. serializationObject.property = animation.targetProperty;
  18487. serializationObject.framePerSecond = animation.framePerSecond;
  18488. serializationObject.dataType = animation.dataType;
  18489. serializationObject.loopBehavior = animation.loopMode;
  18490. var dataType = animation.dataType;
  18491. serializationObject.keys = [];
  18492. var keys = animation.getKeys();
  18493. for (var index = 0; index < keys.length; index++) {
  18494. var animationKey = keys[index];
  18495. var key = {};
  18496. key.frame = animationKey.frame;
  18497. switch (dataType) {
  18498. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18499. key.values = [animationKey.value];
  18500. break;
  18501. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18502. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18503. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18504. key.values = animationKey.value.asArray();
  18505. break;
  18506. }
  18507. serializationObject.keys.push(key);
  18508. }
  18509. return serializationObject;
  18510. };
  18511. var serializeMultiMaterial = function (material) {
  18512. var serializationObject = {};
  18513. serializationObject.name = material.name;
  18514. serializationObject.id = material.id;
  18515. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18516. serializationObject.materials = [];
  18517. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18518. var subMat = material.subMaterials[matIndex];
  18519. if (subMat) {
  18520. serializationObject.materials.push(subMat.id);
  18521. }
  18522. else {
  18523. serializationObject.materials.push(null);
  18524. }
  18525. }
  18526. return serializationObject;
  18527. };
  18528. var serializeMaterial = function (material) {
  18529. var serializationObject = {};
  18530. serializationObject.name = material.name;
  18531. serializationObject.ambient = material.ambientColor.asArray();
  18532. serializationObject.diffuse = material.diffuseColor.asArray();
  18533. serializationObject.specular = material.specularColor.asArray();
  18534. serializationObject.specularPower = material.specularPower;
  18535. serializationObject.emissive = material.emissiveColor.asArray();
  18536. serializationObject.alpha = material.alpha;
  18537. serializationObject.id = material.id;
  18538. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18539. serializationObject.backFaceCulling = material.backFaceCulling;
  18540. if (material.diffuseTexture) {
  18541. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18542. }
  18543. if (material.diffuseFresnelParameters) {
  18544. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18545. }
  18546. if (material.ambientTexture) {
  18547. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18548. }
  18549. if (material.opacityTexture) {
  18550. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18551. }
  18552. if (material.opacityFresnelParameters) {
  18553. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18554. }
  18555. if (material.reflectionTexture) {
  18556. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18557. }
  18558. if (material.reflectionFresnelParameters) {
  18559. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18560. }
  18561. if (material.emissiveTexture) {
  18562. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18563. }
  18564. if (material.emissiveFresnelParameters) {
  18565. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18566. }
  18567. if (material.specularTexture) {
  18568. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18569. }
  18570. if (material.bumpTexture) {
  18571. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18572. }
  18573. return serializationObject;
  18574. };
  18575. var serializeTexture = function (texture) {
  18576. var serializationObject = {};
  18577. if (!texture.name) {
  18578. return null;
  18579. }
  18580. if (texture instanceof BABYLON.CubeTexture) {
  18581. serializationObject.name = texture.name;
  18582. serializationObject.hasAlpha = texture.hasAlpha;
  18583. serializationObject.level = texture.level;
  18584. serializationObject.coordinatesMode = texture.coordinatesMode;
  18585. return serializationObject;
  18586. }
  18587. if (texture instanceof BABYLON.MirrorTexture) {
  18588. var mirrorTexture = texture;
  18589. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18590. serializationObject.renderList = [];
  18591. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18592. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18593. }
  18594. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18595. }
  18596. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18597. var renderTargetTexture = texture;
  18598. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18599. serializationObject.renderList = [];
  18600. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18601. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18602. }
  18603. }
  18604. var regularTexture = texture;
  18605. serializationObject.name = texture.name;
  18606. serializationObject.hasAlpha = texture.hasAlpha;
  18607. serializationObject.level = texture.level;
  18608. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18609. serializationObject.coordinatesMode = texture.coordinatesMode;
  18610. serializationObject.uOffset = regularTexture.uOffset;
  18611. serializationObject.vOffset = regularTexture.vOffset;
  18612. serializationObject.uScale = regularTexture.uScale;
  18613. serializationObject.vScale = regularTexture.vScale;
  18614. serializationObject.uAng = regularTexture.uAng;
  18615. serializationObject.vAng = regularTexture.vAng;
  18616. serializationObject.wAng = regularTexture.wAng;
  18617. serializationObject.wrapU = texture.wrapU;
  18618. serializationObject.wrapV = texture.wrapV;
  18619. // Animations
  18620. appendAnimations(texture, serializationObject);
  18621. return serializationObject;
  18622. };
  18623. var serializeSkeleton = function (skeleton) {
  18624. var serializationObject = {};
  18625. serializationObject.name = skeleton.name;
  18626. serializationObject.id = skeleton.id;
  18627. serializationObject.bones = [];
  18628. for (var index = 0; index < skeleton.bones.length; index++) {
  18629. var bone = skeleton.bones[index];
  18630. var serializedBone = {
  18631. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18632. name: bone.name,
  18633. matrix: bone.getLocalMatrix().toArray()
  18634. };
  18635. serializationObject.bones.push(serializedBone);
  18636. if (bone.animations && bone.animations.length > 0) {
  18637. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18638. }
  18639. }
  18640. return serializationObject;
  18641. };
  18642. var serializeParticleSystem = function (particleSystem) {
  18643. var serializationObject = {};
  18644. serializationObject.emitterId = particleSystem.emitter.id;
  18645. serializationObject.capacity = particleSystem.getCapacity();
  18646. if (particleSystem.particleTexture) {
  18647. serializationObject.textureName = particleSystem.particleTexture.name;
  18648. }
  18649. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18650. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18651. serializationObject.minSize = particleSystem.minSize;
  18652. serializationObject.maxSize = particleSystem.maxSize;
  18653. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18654. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18655. serializationObject.emitRate = particleSystem.emitRate;
  18656. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18657. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18658. serializationObject.gravity = particleSystem.gravity.asArray();
  18659. serializationObject.direction1 = particleSystem.direction1.asArray();
  18660. serializationObject.direction2 = particleSystem.direction2.asArray();
  18661. serializationObject.color1 = particleSystem.color1.asArray();
  18662. serializationObject.color2 = particleSystem.color2.asArray();
  18663. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18664. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18665. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18666. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18667. serializationObject.blendMode = particleSystem.blendMode;
  18668. return serializationObject;
  18669. };
  18670. var serializeLensFlareSystem = function (lensFlareSystem) {
  18671. var serializationObject = {};
  18672. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18673. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18674. serializationObject.flares = [];
  18675. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18676. var flare = lensFlareSystem.lensFlares[index];
  18677. serializationObject.flares.push({
  18678. size: flare.size,
  18679. position: flare.position,
  18680. color: flare.color.asArray(),
  18681. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18682. });
  18683. }
  18684. return serializationObject;
  18685. };
  18686. var serializeShadowGenerator = function (light) {
  18687. var serializationObject = {};
  18688. var shadowGenerator = light.getShadowGenerator();
  18689. serializationObject.lightId = light.id;
  18690. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18691. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18692. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18693. serializationObject.renderList = [];
  18694. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18695. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18696. serializationObject.renderList.push(mesh.id);
  18697. }
  18698. return serializationObject;
  18699. };
  18700. var serializedGeometries = [];
  18701. var serializeGeometry = function (geometry, serializationGeometries) {
  18702. if (serializedGeometries[geometry.id]) {
  18703. return;
  18704. }
  18705. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18706. serializationGeometries.boxes.push(serializeBox(geometry));
  18707. }
  18708. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18709. serializationGeometries.spheres.push(serializeSphere(geometry));
  18710. }
  18711. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18712. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18713. }
  18714. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18715. serializationGeometries.toruses.push(serializeTorus(geometry));
  18716. }
  18717. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18718. serializationGeometries.grounds.push(serializeGround(geometry));
  18719. }
  18720. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18721. serializationGeometries.planes.push(serializePlane(geometry));
  18722. }
  18723. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18724. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18725. }
  18726. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18727. throw new Error("Unknow primitive type");
  18728. }
  18729. else {
  18730. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18731. }
  18732. serializedGeometries[geometry.id] = true;
  18733. };
  18734. var serializeGeometryBase = function (geometry) {
  18735. var serializationObject = {};
  18736. serializationObject.id = geometry.id;
  18737. if (BABYLON.Tags.HasTags(geometry)) {
  18738. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18739. }
  18740. return serializationObject;
  18741. };
  18742. var serializeVertexData = function (vertexData) {
  18743. var serializationObject = serializeGeometryBase(vertexData);
  18744. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18745. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18746. }
  18747. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18748. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18749. }
  18750. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18751. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18752. }
  18753. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18754. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18755. }
  18756. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18757. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18758. }
  18759. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18760. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18761. serializationObject.matricesIndices._isExpanded = true;
  18762. }
  18763. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18764. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18765. }
  18766. serializationObject.indices = vertexData.getIndices();
  18767. return serializationObject;
  18768. };
  18769. var serializePrimitive = function (primitive) {
  18770. var serializationObject = serializeGeometryBase(primitive);
  18771. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18772. return serializationObject;
  18773. };
  18774. var serializeBox = function (box) {
  18775. var serializationObject = serializePrimitive(box);
  18776. serializationObject.size = box.size;
  18777. return serializationObject;
  18778. };
  18779. var serializeSphere = function (sphere) {
  18780. var serializationObject = serializePrimitive(sphere);
  18781. serializationObject.segments = sphere.segments;
  18782. serializationObject.diameter = sphere.diameter;
  18783. return serializationObject;
  18784. };
  18785. var serializeCylinder = function (cylinder) {
  18786. var serializationObject = serializePrimitive(cylinder);
  18787. serializationObject.height = cylinder.height;
  18788. serializationObject.diameterTop = cylinder.diameterTop;
  18789. serializationObject.diameterBottom = cylinder.diameterBottom;
  18790. serializationObject.tessellation = cylinder.tessellation;
  18791. return serializationObject;
  18792. };
  18793. var serializeTorus = function (torus) {
  18794. var serializationObject = serializePrimitive(torus);
  18795. serializationObject.diameter = torus.diameter;
  18796. serializationObject.thickness = torus.thickness;
  18797. serializationObject.tessellation = torus.tessellation;
  18798. return serializationObject;
  18799. };
  18800. var serializeGround = function (ground) {
  18801. var serializationObject = serializePrimitive(ground);
  18802. serializationObject.width = ground.width;
  18803. serializationObject.height = ground.height;
  18804. serializationObject.subdivisions = ground.subdivisions;
  18805. return serializationObject;
  18806. };
  18807. var serializePlane = function (plane) {
  18808. var serializationObject = serializePrimitive(plane);
  18809. serializationObject.size = plane.size;
  18810. return serializationObject;
  18811. };
  18812. var serializeTorusKnot = function (torusKnot) {
  18813. var serializationObject = serializePrimitive(torusKnot);
  18814. serializationObject.radius = torusKnot.radius;
  18815. serializationObject.tube = torusKnot.tube;
  18816. serializationObject.radialSegments = torusKnot.radialSegments;
  18817. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18818. serializationObject.p = torusKnot.p;
  18819. serializationObject.q = torusKnot.q;
  18820. return serializationObject;
  18821. };
  18822. var serializeMesh = function (mesh, serializationScene) {
  18823. var serializationObject = {};
  18824. serializationObject.name = mesh.name;
  18825. serializationObject.id = mesh.id;
  18826. if (BABYLON.Tags.HasTags(mesh)) {
  18827. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18828. }
  18829. serializationObject.position = mesh.position.asArray();
  18830. if (mesh.rotationQuaternion) {
  18831. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18832. }
  18833. else if (mesh.rotation) {
  18834. serializationObject.rotation = mesh.rotation.asArray();
  18835. }
  18836. serializationObject.scaling = mesh.scaling.asArray();
  18837. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18838. serializationObject.isEnabled = mesh.isEnabled();
  18839. serializationObject.isVisible = mesh.isVisible;
  18840. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18841. serializationObject.pickable = mesh.isPickable;
  18842. serializationObject.receiveShadows = mesh.receiveShadows;
  18843. serializationObject.billboardMode = mesh.billboardMode;
  18844. serializationObject.visibility = mesh.visibility;
  18845. serializationObject.checkCollisions = mesh.checkCollisions;
  18846. // Parent
  18847. if (mesh.parent) {
  18848. serializationObject.parentId = mesh.parent.id;
  18849. }
  18850. // Geometry
  18851. var geometry = mesh._geometry;
  18852. if (geometry) {
  18853. var geometryId = geometry.id;
  18854. serializationObject.geometryId = geometryId;
  18855. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18856. // 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
  18857. serializeGeometry(geometry, serializationScene.geometries);
  18858. }
  18859. // SubMeshes
  18860. serializationObject.subMeshes = [];
  18861. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18862. var subMesh = mesh.subMeshes[subIndex];
  18863. serializationObject.subMeshes.push({
  18864. materialIndex: subMesh.materialIndex,
  18865. verticesStart: subMesh.verticesStart,
  18866. verticesCount: subMesh.verticesCount,
  18867. indexStart: subMesh.indexStart,
  18868. indexCount: subMesh.indexCount
  18869. });
  18870. }
  18871. }
  18872. // Material
  18873. if (mesh.material) {
  18874. serializationObject.materialId = mesh.material.id;
  18875. }
  18876. else {
  18877. mesh.material = null;
  18878. }
  18879. // Skeleton
  18880. if (mesh.skeleton) {
  18881. serializationObject.skeletonId = mesh.skeleton.id;
  18882. }
  18883. // Physics
  18884. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18885. serializationObject.physicsMass = mesh.getPhysicsMass();
  18886. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18887. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18888. switch (mesh.getPhysicsImpostor()) {
  18889. case BABYLON.PhysicsEngine.BoxImpostor:
  18890. serializationObject.physicsImpostor = 1;
  18891. break;
  18892. case BABYLON.PhysicsEngine.SphereImpostor:
  18893. serializationObject.physicsImpostor = 2;
  18894. break;
  18895. }
  18896. }
  18897. // Instances
  18898. serializationObject.instances = [];
  18899. for (var index = 0; index < mesh.instances.length; index++) {
  18900. var instance = mesh.instances[index];
  18901. var serializationInstance = {
  18902. name: instance.name,
  18903. position: instance.position,
  18904. rotation: instance.rotation,
  18905. rotationQuaternion: instance.rotationQuaternion,
  18906. scaling: instance.scaling
  18907. };
  18908. serializationObject.instances.push(serializationInstance);
  18909. // Animations
  18910. appendAnimations(instance, serializationInstance);
  18911. }
  18912. // Animations
  18913. appendAnimations(mesh, serializationObject);
  18914. // Layer mask
  18915. serializationObject.layerMask = mesh.layerMask;
  18916. return serializationObject;
  18917. };
  18918. var SceneSerializer = (function () {
  18919. function SceneSerializer() {
  18920. }
  18921. SceneSerializer.Serialize = function (scene) {
  18922. var serializationObject = {};
  18923. // Scene
  18924. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18925. serializationObject.autoClear = scene.autoClear;
  18926. serializationObject.clearColor = scene.clearColor.asArray();
  18927. serializationObject.ambientColor = scene.ambientColor.asArray();
  18928. serializationObject.gravity = scene.gravity.asArray();
  18929. // Fog
  18930. if (scene.fogMode && scene.fogMode !== 0) {
  18931. serializationObject.fogMode = scene.fogMode;
  18932. serializationObject.fogColor = scene.fogColor.asArray();
  18933. serializationObject.fogStart = scene.fogStart;
  18934. serializationObject.fogEnd = scene.fogEnd;
  18935. serializationObject.fogDensity = scene.fogDensity;
  18936. }
  18937. // Lights
  18938. serializationObject.lights = [];
  18939. for (var index = 0; index < scene.lights.length; index++) {
  18940. var light = scene.lights[index];
  18941. serializationObject.lights.push(serializeLight(light));
  18942. }
  18943. // Cameras
  18944. serializationObject.cameras = [];
  18945. for (index = 0; index < scene.cameras.length; index++) {
  18946. var camera = scene.cameras[index];
  18947. serializationObject.cameras.push(serializeCamera(camera));
  18948. }
  18949. if (scene.activeCamera) {
  18950. serializationObject.activeCameraID = scene.activeCamera.id;
  18951. }
  18952. // Materials
  18953. serializationObject.materials = [];
  18954. serializationObject.multiMaterials = [];
  18955. for (index = 0; index < scene.materials.length; index++) {
  18956. var material = scene.materials[index];
  18957. if (material instanceof BABYLON.StandardMaterial) {
  18958. serializationObject.materials.push(serializeMaterial(material));
  18959. }
  18960. else if (material instanceof BABYLON.MultiMaterial) {
  18961. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18962. }
  18963. }
  18964. // Skeletons
  18965. serializationObject.skeletons = [];
  18966. for (index = 0; index < scene.skeletons.length; index++) {
  18967. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18968. }
  18969. // Geometries
  18970. serializationObject.geometries = {};
  18971. serializationObject.geometries.boxes = [];
  18972. serializationObject.geometries.spheres = [];
  18973. serializationObject.geometries.cylinders = [];
  18974. serializationObject.geometries.toruses = [];
  18975. serializationObject.geometries.grounds = [];
  18976. serializationObject.geometries.planes = [];
  18977. serializationObject.geometries.torusKnots = [];
  18978. serializationObject.geometries.vertexData = [];
  18979. serializedGeometries = [];
  18980. var geometries = scene.getGeometries();
  18981. for (index = 0; index < geometries.length; index++) {
  18982. var geometry = geometries[index];
  18983. if (geometry.isReady()) {
  18984. serializeGeometry(geometry, serializationObject.geometries);
  18985. }
  18986. }
  18987. // Meshes
  18988. serializationObject.meshes = [];
  18989. for (index = 0; index < scene.meshes.length; index++) {
  18990. var abstractMesh = scene.meshes[index];
  18991. if (abstractMesh instanceof BABYLON.Mesh) {
  18992. var mesh = abstractMesh;
  18993. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18994. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18995. }
  18996. }
  18997. }
  18998. // Particles Systems
  18999. serializationObject.particleSystems = [];
  19000. for (index = 0; index < scene.particleSystems.length; index++) {
  19001. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19002. }
  19003. // Lens flares
  19004. serializationObject.lensFlareSystems = [];
  19005. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19006. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19007. }
  19008. // Shadows
  19009. serializationObject.shadowGenerators = [];
  19010. for (index = 0; index < scene.lights.length; index++) {
  19011. light = scene.lights[index];
  19012. if (light.getShadowGenerator()) {
  19013. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19014. }
  19015. }
  19016. return serializationObject;
  19017. };
  19018. return SceneSerializer;
  19019. })();
  19020. BABYLON.SceneSerializer = SceneSerializer;
  19021. })(BABYLON || (BABYLON = {}));
  19022. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19023. (function (BABYLON) {
  19024. var SceneLoader = (function () {
  19025. function SceneLoader() {
  19026. }
  19027. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19028. get: function () {
  19029. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19030. },
  19031. set: function (value) {
  19032. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19033. },
  19034. enumerable: true,
  19035. configurable: true
  19036. });
  19037. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19038. get: function () {
  19039. return SceneLoader._ShowLoadingScreen;
  19040. },
  19041. set: function (value) {
  19042. SceneLoader._ShowLoadingScreen = value;
  19043. },
  19044. enumerable: true,
  19045. configurable: true
  19046. });
  19047. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19048. var dotPosition = sceneFilename.lastIndexOf(".");
  19049. var queryStringPosition = sceneFilename.indexOf("?");
  19050. if (queryStringPosition === -1) {
  19051. queryStringPosition = sceneFilename.length;
  19052. }
  19053. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19054. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19055. var plugin = this._registeredPlugins[index];
  19056. if (plugin.extensions.indexOf(extension) !== -1) {
  19057. return plugin;
  19058. }
  19059. }
  19060. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19061. };
  19062. // Public functions
  19063. SceneLoader.RegisterPlugin = function (plugin) {
  19064. plugin.extensions = plugin.extensions.toLowerCase();
  19065. SceneLoader._registeredPlugins.push(plugin);
  19066. };
  19067. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19068. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19069. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19070. return;
  19071. }
  19072. var manifestChecked = function (success) {
  19073. scene.database = database;
  19074. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19075. var importMeshFromData = function (data) {
  19076. var meshes = [];
  19077. var particleSystems = [];
  19078. var skeletons = [];
  19079. try {
  19080. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19081. if (onerror) {
  19082. onerror(scene, 'unable to load the scene');
  19083. }
  19084. return;
  19085. }
  19086. }
  19087. catch (e) {
  19088. if (onerror) {
  19089. onerror(scene, e);
  19090. }
  19091. return;
  19092. }
  19093. if (onsuccess) {
  19094. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19095. onsuccess(meshes, particleSystems, skeletons);
  19096. }
  19097. };
  19098. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19099. // Direct load
  19100. importMeshFromData(sceneFilename.substr(5));
  19101. return;
  19102. }
  19103. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19104. importMeshFromData(data);
  19105. }, progressCallBack, database);
  19106. };
  19107. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19108. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19109. };
  19110. /**
  19111. * Load a scene
  19112. * @param rootUrl a string that defines the root url for scene and resources
  19113. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19114. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19115. */
  19116. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19117. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19118. };
  19119. /**
  19120. * Append a scene
  19121. * @param rootUrl a string that defines the root url for scene and resources
  19122. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19123. * @param scene is the instance of BABYLON.Scene to append to
  19124. */
  19125. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19126. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19127. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19128. return;
  19129. }
  19130. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19131. var database;
  19132. if (SceneLoader.ShowLoadingScreen) {
  19133. scene.getEngine().displayLoadingUI();
  19134. }
  19135. var loadSceneFromData = function (data) {
  19136. scene.database = database;
  19137. if (!plugin.load(scene, data, rootUrl)) {
  19138. if (onerror) {
  19139. onerror(scene);
  19140. }
  19141. scene.getEngine().hideLoadingUI();
  19142. return;
  19143. }
  19144. if (onsuccess) {
  19145. onsuccess(scene);
  19146. }
  19147. if (SceneLoader.ShowLoadingScreen) {
  19148. scene.executeWhenReady(function () {
  19149. scene.getEngine().hideLoadingUI();
  19150. });
  19151. }
  19152. };
  19153. var manifestChecked = function (success) {
  19154. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19155. };
  19156. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19157. // Direct load
  19158. loadSceneFromData(sceneFilename.substr(5));
  19159. return;
  19160. }
  19161. if (rootUrl.indexOf("file:") === -1) {
  19162. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19163. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19164. }
  19165. else {
  19166. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19167. }
  19168. };
  19169. // Flags
  19170. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19171. SceneLoader._ShowLoadingScreen = true;
  19172. // Members
  19173. SceneLoader._registeredPlugins = new Array();
  19174. return SceneLoader;
  19175. })();
  19176. BABYLON.SceneLoader = SceneLoader;
  19177. ;
  19178. })(BABYLON || (BABYLON = {}));
  19179. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19180. (function (BABYLON) {
  19181. var Internals;
  19182. (function (Internals) {
  19183. var checkColors4 = function (colors, count) {
  19184. // Check if color3 was used
  19185. if (colors.length === count * 3) {
  19186. var colors4 = [];
  19187. for (var index = 0; index < colors.length; index += 3) {
  19188. var newIndex = (index / 3) * 4;
  19189. colors4[newIndex] = colors[index];
  19190. colors4[newIndex + 1] = colors[index + 1];
  19191. colors4[newIndex + 2] = colors[index + 2];
  19192. colors4[newIndex + 3] = 1.0;
  19193. }
  19194. return colors4;
  19195. }
  19196. return colors;
  19197. };
  19198. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19199. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19200. texture.name = parsedTexture.name;
  19201. texture.hasAlpha = parsedTexture.hasAlpha;
  19202. texture.level = parsedTexture.level;
  19203. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19204. return texture;
  19205. };
  19206. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19207. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19208. return null;
  19209. }
  19210. if (parsedTexture.isCube) {
  19211. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19212. }
  19213. var texture;
  19214. if (parsedTexture.mirrorPlane) {
  19215. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19216. texture._waitingRenderList = parsedTexture.renderList;
  19217. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19218. }
  19219. else if (parsedTexture.isRenderTarget) {
  19220. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19221. texture._waitingRenderList = parsedTexture.renderList;
  19222. }
  19223. else {
  19224. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19225. }
  19226. texture.name = parsedTexture.name;
  19227. texture.hasAlpha = parsedTexture.hasAlpha;
  19228. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19229. texture.level = parsedTexture.level;
  19230. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19231. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19232. texture.uOffset = parsedTexture.uOffset;
  19233. texture.vOffset = parsedTexture.vOffset;
  19234. texture.uScale = parsedTexture.uScale;
  19235. texture.vScale = parsedTexture.vScale;
  19236. texture.uAng = parsedTexture.uAng;
  19237. texture.vAng = parsedTexture.vAng;
  19238. texture.wAng = parsedTexture.wAng;
  19239. texture.wrapU = parsedTexture.wrapU;
  19240. texture.wrapV = parsedTexture.wrapV;
  19241. // Animations
  19242. if (parsedTexture.animations) {
  19243. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19244. var parsedAnimation = parsedTexture.animations[animationIndex];
  19245. texture.animations.push(parseAnimation(parsedAnimation));
  19246. }
  19247. }
  19248. return texture;
  19249. };
  19250. var parseSkeleton = function (parsedSkeleton, scene) {
  19251. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19252. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19253. var parsedBone = parsedSkeleton.bones[index];
  19254. var parentBone = null;
  19255. if (parsedBone.parentBoneIndex > -1) {
  19256. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19257. }
  19258. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19259. if (parsedBone.animation) {
  19260. bone.animations.push(parseAnimation(parsedBone.animation));
  19261. }
  19262. }
  19263. return skeleton;
  19264. };
  19265. var parseFresnelParameters = function (parsedFresnelParameters) {
  19266. var fresnelParameters = new BABYLON.FresnelParameters();
  19267. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19268. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19269. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19270. fresnelParameters.bias = parsedFresnelParameters.bias;
  19271. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19272. return fresnelParameters;
  19273. };
  19274. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19275. var material;
  19276. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19277. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19278. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19279. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19280. material.specularPower = parsedMaterial.specularPower;
  19281. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19282. material.alpha = parsedMaterial.alpha;
  19283. material.id = parsedMaterial.id;
  19284. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19285. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19286. material.wireframe = parsedMaterial.wireframe;
  19287. if (parsedMaterial.diffuseTexture) {
  19288. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19289. }
  19290. if (parsedMaterial.diffuseFresnelParameters) {
  19291. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19292. }
  19293. if (parsedMaterial.ambientTexture) {
  19294. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19295. }
  19296. if (parsedMaterial.opacityTexture) {
  19297. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19298. }
  19299. if (parsedMaterial.opacityFresnelParameters) {
  19300. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19301. }
  19302. if (parsedMaterial.reflectionTexture) {
  19303. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19304. }
  19305. if (parsedMaterial.reflectionFresnelParameters) {
  19306. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19307. }
  19308. if (parsedMaterial.emissiveTexture) {
  19309. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19310. }
  19311. if (parsedMaterial.emissiveFresnelParameters) {
  19312. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19313. }
  19314. if (parsedMaterial.specularTexture) {
  19315. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19316. }
  19317. if (parsedMaterial.bumpTexture) {
  19318. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19319. }
  19320. return material;
  19321. };
  19322. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19323. for (var index = 0; index < parsedData.materials.length; index++) {
  19324. var parsedMaterial = parsedData.materials[index];
  19325. if (parsedMaterial.id === id) {
  19326. return parseMaterial(parsedMaterial, scene, rootUrl);
  19327. }
  19328. }
  19329. return null;
  19330. };
  19331. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19332. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19333. multiMaterial.id = parsedMultiMaterial.id;
  19334. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19335. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19336. var subMatId = parsedMultiMaterial.materials[matIndex];
  19337. if (subMatId) {
  19338. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19339. }
  19340. else {
  19341. multiMaterial.subMaterials.push(null);
  19342. }
  19343. }
  19344. return multiMaterial;
  19345. };
  19346. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19347. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19348. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19349. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19350. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19351. var parsedFlare = parsedLensFlareSystem.flares[index];
  19352. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19353. }
  19354. return lensFlareSystem;
  19355. };
  19356. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19357. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19358. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19359. if (parsedParticleSystem.textureName) {
  19360. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19361. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19362. }
  19363. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19364. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19365. particleSystem.minSize = parsedParticleSystem.minSize;
  19366. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19367. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19368. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19369. particleSystem.emitter = emitter;
  19370. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19371. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19372. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19373. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19374. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19375. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19376. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19377. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19378. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19379. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19380. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19381. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19382. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19383. particleSystem.start();
  19384. return particleSystem;
  19385. };
  19386. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19387. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19388. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19389. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19390. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19391. shadowGenerator.getShadowMap().renderList.push(mesh);
  19392. }
  19393. if (parsedShadowGenerator.usePoissonSampling) {
  19394. shadowGenerator.usePoissonSampling = true;
  19395. }
  19396. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19397. shadowGenerator.useVarianceShadowMap = true;
  19398. }
  19399. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19400. shadowGenerator.useBlurVarianceShadowMap = true;
  19401. if (parsedShadowGenerator.blurScale) {
  19402. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19403. }
  19404. if (parsedShadowGenerator.blurBoxOffset) {
  19405. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19406. }
  19407. }
  19408. if (parsedShadowGenerator.bias !== undefined) {
  19409. shadowGenerator.bias = parsedShadowGenerator.bias;
  19410. }
  19411. return shadowGenerator;
  19412. };
  19413. var parseAnimation = function (parsedAnimation) {
  19414. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19415. var dataType = parsedAnimation.dataType;
  19416. var keys = [];
  19417. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19418. var key = parsedAnimation.keys[index];
  19419. var data;
  19420. switch (dataType) {
  19421. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19422. data = key.values[0];
  19423. break;
  19424. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19425. data = BABYLON.Quaternion.FromArray(key.values);
  19426. break;
  19427. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19428. data = BABYLON.Matrix.FromArray(key.values);
  19429. break;
  19430. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19431. default:
  19432. data = BABYLON.Vector3.FromArray(key.values);
  19433. break;
  19434. }
  19435. keys.push({
  19436. frame: key.frame,
  19437. value: data
  19438. });
  19439. }
  19440. animation.setKeys(keys);
  19441. return animation;
  19442. };
  19443. var parseLight = function (parsedLight, scene) {
  19444. var light;
  19445. switch (parsedLight.type) {
  19446. case 0:
  19447. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19448. break;
  19449. case 1:
  19450. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19451. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19452. break;
  19453. case 2:
  19454. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19455. break;
  19456. case 3:
  19457. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19458. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19459. break;
  19460. }
  19461. light.id = parsedLight.id;
  19462. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19463. if (parsedLight.intensity !== undefined) {
  19464. light.intensity = parsedLight.intensity;
  19465. }
  19466. if (parsedLight.range) {
  19467. light.range = parsedLight.range;
  19468. }
  19469. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19470. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19471. if (parsedLight.excludedMeshesIds) {
  19472. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19473. }
  19474. // Parent
  19475. if (parsedLight.parentId) {
  19476. light._waitingParentId = parsedLight.parentId;
  19477. }
  19478. if (parsedLight.includedOnlyMeshesIds) {
  19479. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19480. }
  19481. // Animations
  19482. if (parsedLight.animations) {
  19483. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19484. var parsedAnimation = parsedLight.animations[animationIndex];
  19485. light.animations.push(parseAnimation(parsedAnimation));
  19486. }
  19487. }
  19488. if (parsedLight.autoAnimate) {
  19489. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19490. }
  19491. };
  19492. var parseCamera = function (parsedCamera, scene) {
  19493. var camera;
  19494. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19495. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19496. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19497. var alpha = parsedCamera.alpha;
  19498. var beta = parsedCamera.beta;
  19499. var radius = parsedCamera.radius;
  19500. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19501. var eye_space = parsedCamera.eye_space;
  19502. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19503. }
  19504. else {
  19505. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19506. }
  19507. }
  19508. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19509. eye_space = parsedCamera.eye_space;
  19510. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19511. }
  19512. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19513. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19514. }
  19515. else if (parsedCamera.type === "FollowCamera") {
  19516. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19517. camera.heightOffset = parsedCamera.heightOffset;
  19518. camera.radius = parsedCamera.radius;
  19519. camera.rotationOffset = parsedCamera.rotationOffset;
  19520. if (lockedTargetMesh)
  19521. camera.target = lockedTargetMesh;
  19522. }
  19523. else if (parsedCamera.type === "GamepadCamera") {
  19524. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19525. }
  19526. else if (parsedCamera.type === "OculusCamera") {
  19527. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19528. }
  19529. else if (parsedCamera.type === "OculusGamepadCamera") {
  19530. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19531. }
  19532. else if (parsedCamera.type === "TouchCamera") {
  19533. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19534. }
  19535. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19536. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19537. }
  19538. else if (parsedCamera.type === "WebVRCamera") {
  19539. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19540. }
  19541. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19542. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19543. }
  19544. else {
  19545. // Free Camera is the default value
  19546. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19547. }
  19548. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19549. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19550. camera.lockedTarget = lockedTargetMesh;
  19551. }
  19552. camera.id = parsedCamera.id;
  19553. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19554. // Parent
  19555. if (parsedCamera.parentId) {
  19556. camera._waitingParentId = parsedCamera.parentId;
  19557. }
  19558. // Target
  19559. if (parsedCamera.target) {
  19560. if (camera.setTarget) {
  19561. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19562. }
  19563. else {
  19564. //For ArcRotate
  19565. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19566. }
  19567. }
  19568. else {
  19569. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19570. }
  19571. camera.fov = parsedCamera.fov;
  19572. camera.minZ = parsedCamera.minZ;
  19573. camera.maxZ = parsedCamera.maxZ;
  19574. camera.speed = parsedCamera.speed;
  19575. camera.inertia = parsedCamera.inertia;
  19576. camera.checkCollisions = parsedCamera.checkCollisions;
  19577. camera.applyGravity = parsedCamera.applyGravity;
  19578. if (parsedCamera.ellipsoid) {
  19579. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19580. }
  19581. // Animations
  19582. if (parsedCamera.animations) {
  19583. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19584. var parsedAnimation = parsedCamera.animations[animationIndex];
  19585. camera.animations.push(parseAnimation(parsedAnimation));
  19586. }
  19587. }
  19588. if (parsedCamera.autoAnimate) {
  19589. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19590. }
  19591. // Layer Mask
  19592. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19593. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19594. }
  19595. else {
  19596. camera.layerMask = 0xFFFFFFFF;
  19597. }
  19598. return camera;
  19599. };
  19600. var parseGeometry = function (parsedGeometry, scene) {
  19601. var id = parsedGeometry.id;
  19602. return scene.getGeometryByID(id);
  19603. };
  19604. var parseBox = function (parsedBox, scene) {
  19605. if (parseGeometry(parsedBox, scene)) {
  19606. return null; // null since geometry could be something else than a box...
  19607. }
  19608. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19609. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19610. scene.pushGeometry(box, true);
  19611. return box;
  19612. };
  19613. var parseSphere = function (parsedSphere, scene) {
  19614. if (parseGeometry(parsedSphere, scene)) {
  19615. return null; // null since geometry could be something else than a sphere...
  19616. }
  19617. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19618. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19619. scene.pushGeometry(sphere, true);
  19620. return sphere;
  19621. };
  19622. var parseCylinder = function (parsedCylinder, scene) {
  19623. if (parseGeometry(parsedCylinder, scene)) {
  19624. return null; // null since geometry could be something else than a cylinder...
  19625. }
  19626. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19627. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19628. scene.pushGeometry(cylinder, true);
  19629. return cylinder;
  19630. };
  19631. var parseTorus = function (parsedTorus, scene) {
  19632. if (parseGeometry(parsedTorus, scene)) {
  19633. return null; // null since geometry could be something else than a torus...
  19634. }
  19635. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19636. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19637. scene.pushGeometry(torus, true);
  19638. return torus;
  19639. };
  19640. var parseGround = function (parsedGround, scene) {
  19641. if (parseGeometry(parsedGround, scene)) {
  19642. return null; // null since geometry could be something else than a ground...
  19643. }
  19644. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19645. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19646. scene.pushGeometry(ground, true);
  19647. return ground;
  19648. };
  19649. var parsePlane = function (parsedPlane, scene) {
  19650. if (parseGeometry(parsedPlane, scene)) {
  19651. return null; // null since geometry could be something else than a plane...
  19652. }
  19653. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19654. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19655. scene.pushGeometry(plane, true);
  19656. return plane;
  19657. };
  19658. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19659. if (parseGeometry(parsedTorusKnot, scene)) {
  19660. return null; // null since geometry could be something else than a torusKnot...
  19661. }
  19662. 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);
  19663. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19664. scene.pushGeometry(torusKnot, true);
  19665. return torusKnot;
  19666. };
  19667. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19668. if (parseGeometry(parsedVertexData, scene)) {
  19669. return null; // null since geometry could be a primitive
  19670. }
  19671. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19672. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19673. if (parsedVertexData.delayLoadingFile) {
  19674. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19675. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19676. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19677. geometry._delayInfo = [];
  19678. if (parsedVertexData.hasUVs) {
  19679. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19680. }
  19681. if (parsedVertexData.hasUVs2) {
  19682. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19683. }
  19684. if (parsedVertexData.hasColors) {
  19685. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19686. }
  19687. if (parsedVertexData.hasMatricesIndices) {
  19688. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19689. }
  19690. if (parsedVertexData.hasMatricesWeights) {
  19691. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19692. }
  19693. geometry._delayLoadingFunction = importVertexData;
  19694. }
  19695. else {
  19696. importVertexData(parsedVertexData, geometry);
  19697. }
  19698. scene.pushGeometry(geometry, true);
  19699. return geometry;
  19700. };
  19701. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19702. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19703. mesh.id = parsedMesh.id;
  19704. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19705. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19706. if (parsedMesh.rotationQuaternion) {
  19707. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19708. }
  19709. else if (parsedMesh.rotation) {
  19710. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19711. }
  19712. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19713. if (parsedMesh.localMatrix) {
  19714. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19715. }
  19716. else if (parsedMesh.pivotMatrix) {
  19717. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19718. }
  19719. mesh.setEnabled(parsedMesh.isEnabled);
  19720. mesh.isVisible = parsedMesh.isVisible;
  19721. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19722. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19723. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19724. if (parsedMesh.applyFog !== undefined) {
  19725. mesh.applyFog = parsedMesh.applyFog;
  19726. }
  19727. if (parsedMesh.pickable !== undefined) {
  19728. mesh.isPickable = parsedMesh.pickable;
  19729. }
  19730. if (parsedMesh.alphaIndex !== undefined) {
  19731. mesh.alphaIndex = parsedMesh.alphaIndex;
  19732. }
  19733. mesh.receiveShadows = parsedMesh.receiveShadows;
  19734. mesh.billboardMode = parsedMesh.billboardMode;
  19735. if (parsedMesh.visibility !== undefined) {
  19736. mesh.visibility = parsedMesh.visibility;
  19737. }
  19738. mesh.checkCollisions = parsedMesh.checkCollisions;
  19739. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19740. // Parent
  19741. if (parsedMesh.parentId) {
  19742. mesh._waitingParentId = parsedMesh.parentId;
  19743. }
  19744. // Actions
  19745. if (parsedMesh.actions !== undefined) {
  19746. mesh._waitingActions = parsedMesh.actions;
  19747. }
  19748. // Geometry
  19749. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19750. if (parsedMesh.delayLoadingFile) {
  19751. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19752. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19753. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19754. if (parsedMesh._binaryInfo) {
  19755. mesh._binaryInfo = parsedMesh._binaryInfo;
  19756. }
  19757. mesh._delayInfo = [];
  19758. if (parsedMesh.hasUVs) {
  19759. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19760. }
  19761. if (parsedMesh.hasUVs2) {
  19762. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19763. }
  19764. if (parsedMesh.hasColors) {
  19765. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19766. }
  19767. if (parsedMesh.hasMatricesIndices) {
  19768. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19769. }
  19770. if (parsedMesh.hasMatricesWeights) {
  19771. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19772. }
  19773. mesh._delayLoadingFunction = importGeometry;
  19774. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19775. mesh._checkDelayState();
  19776. }
  19777. }
  19778. else {
  19779. importGeometry(parsedMesh, mesh);
  19780. }
  19781. // Material
  19782. if (parsedMesh.materialId) {
  19783. mesh.setMaterialByID(parsedMesh.materialId);
  19784. }
  19785. else {
  19786. mesh.material = null;
  19787. }
  19788. // Skeleton
  19789. if (parsedMesh.skeletonId > -1) {
  19790. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19791. }
  19792. // Physics
  19793. if (parsedMesh.physicsImpostor) {
  19794. if (!scene.isPhysicsEnabled()) {
  19795. scene.enablePhysics();
  19796. }
  19797. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19798. }
  19799. // Animations
  19800. if (parsedMesh.animations) {
  19801. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19802. var parsedAnimation = parsedMesh.animations[animationIndex];
  19803. mesh.animations.push(parseAnimation(parsedAnimation));
  19804. }
  19805. }
  19806. if (parsedMesh.autoAnimate) {
  19807. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19808. }
  19809. // Layer Mask
  19810. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19811. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19812. }
  19813. else {
  19814. mesh.layerMask = 0xFFFFFFFF;
  19815. }
  19816. // Instances
  19817. if (parsedMesh.instances) {
  19818. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19819. var parsedInstance = parsedMesh.instances[index];
  19820. var instance = mesh.createInstance(parsedInstance.name);
  19821. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19822. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19823. if (parsedInstance.rotationQuaternion) {
  19824. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19825. }
  19826. else if (parsedInstance.rotation) {
  19827. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19828. }
  19829. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19830. instance.checkCollisions = mesh.checkCollisions;
  19831. if (parsedMesh.animations) {
  19832. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19833. parsedAnimation = parsedMesh.animations[animationIndex];
  19834. instance.animations.push(parseAnimation(parsedAnimation));
  19835. }
  19836. }
  19837. }
  19838. }
  19839. return mesh;
  19840. };
  19841. var parseActions = function (parsedActions, object, scene) {
  19842. var actionManager = new BABYLON.ActionManager(scene);
  19843. if (object === null)
  19844. scene.actionManager = actionManager;
  19845. else
  19846. object.actionManager = actionManager;
  19847. // instanciate a new object
  19848. var instanciate = function (name, params) {
  19849. var newInstance = Object.create(BABYLON[name].prototype);
  19850. newInstance.constructor.apply(newInstance, params);
  19851. return newInstance;
  19852. };
  19853. var parseParameter = function (name, value, target, propertyPath) {
  19854. if (propertyPath === null) {
  19855. // String, boolean or float
  19856. var floatValue = parseFloat(value);
  19857. if (value === "true" || value === "false")
  19858. return value === "true";
  19859. else
  19860. return isNaN(floatValue) ? value : floatValue;
  19861. }
  19862. var effectiveTarget = propertyPath.split(".");
  19863. var values = value.split(",");
  19864. for (var i = 0; i < effectiveTarget.length; i++) {
  19865. target = target[effectiveTarget[i]];
  19866. }
  19867. // Return appropriate value with its type
  19868. if (target instanceof Boolean)
  19869. return values[0] === "true";
  19870. if (target instanceof String)
  19871. return values[0];
  19872. // Parameters with multiple values such as Vector3 etc.
  19873. var split = new Array();
  19874. for (var i = 0; i < values.length; i++)
  19875. split.push(parseFloat(values[i]));
  19876. if (target instanceof BABYLON.Vector3)
  19877. return BABYLON.Vector3.FromArray(split);
  19878. if (target instanceof BABYLON.Vector4)
  19879. return BABYLON.Vector4.FromArray(split);
  19880. if (target instanceof BABYLON.Color3)
  19881. return BABYLON.Color3.FromArray(split);
  19882. if (target instanceof BABYLON.Color4)
  19883. return BABYLON.Color4.FromArray(split);
  19884. return parseFloat(values[0]);
  19885. };
  19886. // traverse graph per trigger
  19887. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19888. if (combineArray === void 0) { combineArray = null; }
  19889. if (parsedAction.detached)
  19890. return;
  19891. var parameters = new Array();
  19892. var target = null;
  19893. var propertyPath = null;
  19894. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19895. // Parameters
  19896. if (parsedAction.type === 2)
  19897. parameters.push(actionManager);
  19898. else
  19899. parameters.push(trigger);
  19900. if (combine) {
  19901. var actions = new Array();
  19902. for (var j = 0; j < parsedAction.combine.length; j++) {
  19903. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19904. }
  19905. parameters.push(actions);
  19906. }
  19907. else {
  19908. for (var i = 0; i < parsedAction.properties.length; i++) {
  19909. var value = parsedAction.properties[i].value;
  19910. var name = parsedAction.properties[i].name;
  19911. if (name === "target")
  19912. value = target = scene.getNodeByName(value);
  19913. else if (name === "parent")
  19914. value = scene.getNodeByName(value);
  19915. else if (name === "sound")
  19916. value = scene.getSoundByName(value);
  19917. else if (name !== "propertyPath") {
  19918. if (parsedAction.type === 2 && name === "operator")
  19919. value = BABYLON.ValueCondition[value];
  19920. else
  19921. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19922. }
  19923. else {
  19924. propertyPath = value;
  19925. }
  19926. parameters.push(value);
  19927. }
  19928. }
  19929. parameters.push(condition);
  19930. // If interpolate value action
  19931. if (parsedAction.name === "InterpolateValueAction") {
  19932. var param = parameters[parameters.length - 2];
  19933. parameters[parameters.length - 1] = param;
  19934. parameters[parameters.length - 2] = condition;
  19935. }
  19936. // Action or condition(s) and not CombineAction
  19937. var newAction = instanciate(parsedAction.name, parameters);
  19938. if (combineArray === null) {
  19939. if (newAction instanceof BABYLON.Condition) {
  19940. condition = newAction;
  19941. newAction = action;
  19942. }
  19943. else {
  19944. condition = null;
  19945. if (action)
  19946. action.then(newAction);
  19947. else
  19948. actionManager.registerAction(newAction);
  19949. }
  19950. }
  19951. else {
  19952. combineArray.push(newAction);
  19953. }
  19954. for (var i = 0; i < parsedAction.children.length; i++)
  19955. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19956. };
  19957. for (var i = 0; i < parsedActions.children.length; i++) {
  19958. var triggerParams;
  19959. var trigger = parsedActions.children[i];
  19960. if (trigger.properties.length > 0) {
  19961. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19962. }
  19963. else
  19964. triggerParams = BABYLON.ActionManager[trigger.name];
  19965. for (var j = 0; j < trigger.children.length; j++) {
  19966. if (!trigger.detached)
  19967. traverse(trigger.children[j], triggerParams, null, null);
  19968. }
  19969. }
  19970. };
  19971. var parseSound = function (parsedSound, scene, rootUrl) {
  19972. var soundName = parsedSound.name;
  19973. var soundUrl = rootUrl + soundName;
  19974. var options = {
  19975. autoplay: parsedSound.autoplay,
  19976. loop: parsedSound.loop,
  19977. volume: parsedSound.volume,
  19978. spatialSound: parsedSound.spatialSound,
  19979. maxDistance: parsedSound.maxDistance,
  19980. rolloffFactor: parsedSound.rolloffFactor,
  19981. refDistance: parsedSound.refDistance,
  19982. distanceModel: parsedSound.distanceModel,
  19983. playbackRate: parsedSound.playbackRate
  19984. };
  19985. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19986. scene._removePendingData(newSound);
  19987. }, options);
  19988. scene._addPendingData(newSound);
  19989. if (parsedSound.position) {
  19990. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19991. newSound.setPosition(soundPosition);
  19992. }
  19993. if (parsedSound.isDirectional) {
  19994. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19995. if (parsedSound.localDirectionToMesh) {
  19996. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19997. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19998. }
  19999. }
  20000. if (parsedSound.connectedMeshId) {
  20001. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20002. if (connectedMesh) {
  20003. newSound.attachToMesh(connectedMesh);
  20004. }
  20005. }
  20006. };
  20007. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20008. names = (names instanceof Array) ? names : [names];
  20009. for (var i in names) {
  20010. if (mesh.name === names[i]) {
  20011. hierarchyIds.push(mesh.id);
  20012. return true;
  20013. }
  20014. }
  20015. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20016. hierarchyIds.push(mesh.id);
  20017. return true;
  20018. }
  20019. return false;
  20020. };
  20021. var importVertexData = function (parsedVertexData, geometry) {
  20022. var vertexData = new BABYLON.VertexData();
  20023. // positions
  20024. var positions = parsedVertexData.positions;
  20025. if (positions) {
  20026. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20027. }
  20028. // normals
  20029. var normals = parsedVertexData.normals;
  20030. if (normals) {
  20031. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20032. }
  20033. // uvs
  20034. var uvs = parsedVertexData.uvs;
  20035. if (uvs) {
  20036. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20037. }
  20038. // uv2s
  20039. var uv2s = parsedVertexData.uv2s;
  20040. if (uv2s) {
  20041. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20042. }
  20043. // colors
  20044. var colors = parsedVertexData.colors;
  20045. if (colors) {
  20046. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20047. }
  20048. // matricesIndices
  20049. var matricesIndices = parsedVertexData.matricesIndices;
  20050. if (matricesIndices) {
  20051. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20052. }
  20053. // matricesWeights
  20054. var matricesWeights = parsedVertexData.matricesWeights;
  20055. if (matricesWeights) {
  20056. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20057. }
  20058. // indices
  20059. var indices = parsedVertexData.indices;
  20060. if (indices) {
  20061. vertexData.indices = indices;
  20062. }
  20063. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20064. };
  20065. var importGeometry = function (parsedGeometry, mesh) {
  20066. var scene = mesh.getScene();
  20067. // Geometry
  20068. var geometryId = parsedGeometry.geometryId;
  20069. if (geometryId) {
  20070. var geometry = scene.getGeometryByID(geometryId);
  20071. if (geometry) {
  20072. geometry.applyToMesh(mesh);
  20073. }
  20074. }
  20075. else if (parsedGeometry instanceof ArrayBuffer) {
  20076. var binaryInfo = mesh._binaryInfo;
  20077. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20078. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20079. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20080. }
  20081. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20082. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20083. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20084. }
  20085. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20086. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20087. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20088. }
  20089. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20090. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20091. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20092. }
  20093. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20094. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20095. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20096. }
  20097. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20098. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20099. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20100. }
  20101. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20102. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20103. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20104. }
  20105. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20106. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20107. mesh.setIndices(indicesData);
  20108. }
  20109. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20110. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20111. mesh.subMeshes = [];
  20112. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20113. var materialIndex = subMeshesData[(i * 5) + 0];
  20114. var verticesStart = subMeshesData[(i * 5) + 1];
  20115. var verticesCount = subMeshesData[(i * 5) + 2];
  20116. var indexStart = subMeshesData[(i * 5) + 3];
  20117. var indexCount = subMeshesData[(i * 5) + 4];
  20118. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20119. }
  20120. }
  20121. }
  20122. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20123. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20124. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20125. if (parsedGeometry.uvs) {
  20126. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20127. }
  20128. if (parsedGeometry.uvs2) {
  20129. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20130. }
  20131. if (parsedGeometry.colors) {
  20132. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20133. }
  20134. if (parsedGeometry.matricesIndices) {
  20135. if (!parsedGeometry.matricesIndices._isExpanded) {
  20136. var floatIndices = [];
  20137. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20138. var matricesIndex = parsedGeometry.matricesIndices[i];
  20139. floatIndices.push(matricesIndex & 0x000000FF);
  20140. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20141. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20142. floatIndices.push(matricesIndex >> 24);
  20143. }
  20144. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20145. }
  20146. else {
  20147. delete parsedGeometry.matricesIndices._isExpanded;
  20148. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20149. }
  20150. }
  20151. if (parsedGeometry.matricesWeights) {
  20152. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20153. }
  20154. mesh.setIndices(parsedGeometry.indices);
  20155. // SubMeshes
  20156. if (parsedGeometry.subMeshes) {
  20157. mesh.subMeshes = [];
  20158. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20159. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20160. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20161. }
  20162. }
  20163. }
  20164. // Flat shading
  20165. if (mesh._shouldGenerateFlatShading) {
  20166. mesh.convertToFlatShadedMesh();
  20167. delete mesh._shouldGenerateFlatShading;
  20168. }
  20169. // Update
  20170. mesh.computeWorldMatrix(true);
  20171. // Octree
  20172. if (scene._selectionOctree) {
  20173. scene._selectionOctree.addMesh(mesh);
  20174. }
  20175. };
  20176. BABYLON.SceneLoader.RegisterPlugin({
  20177. extensions: ".babylon",
  20178. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20179. var parsedData = JSON.parse(data);
  20180. var loadedSkeletonsIds = [];
  20181. var loadedMaterialsIds = [];
  20182. var hierarchyIds = [];
  20183. for (var index = 0; index < parsedData.meshes.length; index++) {
  20184. var parsedMesh = parsedData.meshes[index];
  20185. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20186. if (meshesNames instanceof Array) {
  20187. // Remove found mesh name from list.
  20188. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20189. }
  20190. // Material ?
  20191. if (parsedMesh.materialId) {
  20192. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20193. if (!materialFound) {
  20194. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20195. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20196. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20197. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20198. var subMatId = parsedMultiMaterial.materials[matIndex];
  20199. loadedMaterialsIds.push(subMatId);
  20200. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20201. }
  20202. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20203. parseMultiMaterial(parsedMultiMaterial, scene);
  20204. materialFound = true;
  20205. break;
  20206. }
  20207. }
  20208. }
  20209. if (!materialFound) {
  20210. loadedMaterialsIds.push(parsedMesh.materialId);
  20211. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20212. }
  20213. }
  20214. // Skeleton ?
  20215. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20216. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20217. if (!skeletonAlreadyLoaded) {
  20218. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20219. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20220. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20221. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20222. loadedSkeletonsIds.push(parsedSkeleton.id);
  20223. }
  20224. }
  20225. }
  20226. }
  20227. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20228. meshes.push(mesh);
  20229. }
  20230. }
  20231. for (index = 0; index < scene.meshes.length; index++) {
  20232. var currentMesh = scene.meshes[index];
  20233. if (currentMesh._waitingParentId) {
  20234. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20235. currentMesh._waitingParentId = undefined;
  20236. }
  20237. }
  20238. // Particles
  20239. if (parsedData.particleSystems) {
  20240. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20241. var parsedParticleSystem = parsedData.particleSystems[index];
  20242. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20243. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20244. }
  20245. }
  20246. }
  20247. return true;
  20248. },
  20249. load: function (scene, data, rootUrl) {
  20250. var parsedData = JSON.parse(data);
  20251. // Scene
  20252. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20253. scene.autoClear = parsedData.autoClear;
  20254. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20255. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20256. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20257. // Fog
  20258. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20259. scene.fogMode = parsedData.fogMode;
  20260. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20261. scene.fogStart = parsedData.fogStart;
  20262. scene.fogEnd = parsedData.fogEnd;
  20263. scene.fogDensity = parsedData.fogDensity;
  20264. }
  20265. for (var index = 0; index < parsedData.lights.length; index++) {
  20266. var parsedLight = parsedData.lights[index];
  20267. parseLight(parsedLight, scene);
  20268. }
  20269. // Materials
  20270. if (parsedData.materials) {
  20271. for (index = 0; index < parsedData.materials.length; index++) {
  20272. var parsedMaterial = parsedData.materials[index];
  20273. parseMaterial(parsedMaterial, scene, rootUrl);
  20274. }
  20275. }
  20276. if (parsedData.multiMaterials) {
  20277. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20278. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20279. parseMultiMaterial(parsedMultiMaterial, scene);
  20280. }
  20281. }
  20282. // Skeletons
  20283. if (parsedData.skeletons) {
  20284. for (index = 0; index < parsedData.skeletons.length; index++) {
  20285. var parsedSkeleton = parsedData.skeletons[index];
  20286. parseSkeleton(parsedSkeleton, scene);
  20287. }
  20288. }
  20289. // Geometries
  20290. var geometries = parsedData.geometries;
  20291. if (geometries) {
  20292. // Boxes
  20293. var boxes = geometries.boxes;
  20294. if (boxes) {
  20295. for (index = 0; index < boxes.length; index++) {
  20296. var parsedBox = boxes[index];
  20297. parseBox(parsedBox, scene);
  20298. }
  20299. }
  20300. // Spheres
  20301. var spheres = geometries.spheres;
  20302. if (spheres) {
  20303. for (index = 0; index < spheres.length; index++) {
  20304. var parsedSphere = spheres[index];
  20305. parseSphere(parsedSphere, scene);
  20306. }
  20307. }
  20308. // Cylinders
  20309. var cylinders = geometries.cylinders;
  20310. if (cylinders) {
  20311. for (index = 0; index < cylinders.length; index++) {
  20312. var parsedCylinder = cylinders[index];
  20313. parseCylinder(parsedCylinder, scene);
  20314. }
  20315. }
  20316. // Toruses
  20317. var toruses = geometries.toruses;
  20318. if (toruses) {
  20319. for (index = 0; index < toruses.length; index++) {
  20320. var parsedTorus = toruses[index];
  20321. parseTorus(parsedTorus, scene);
  20322. }
  20323. }
  20324. // Grounds
  20325. var grounds = geometries.grounds;
  20326. if (grounds) {
  20327. for (index = 0; index < grounds.length; index++) {
  20328. var parsedGround = grounds[index];
  20329. parseGround(parsedGround, scene);
  20330. }
  20331. }
  20332. // Planes
  20333. var planes = geometries.planes;
  20334. if (planes) {
  20335. for (index = 0; index < planes.length; index++) {
  20336. var parsedPlane = planes[index];
  20337. parsePlane(parsedPlane, scene);
  20338. }
  20339. }
  20340. // TorusKnots
  20341. var torusKnots = geometries.torusKnots;
  20342. if (torusKnots) {
  20343. for (index = 0; index < torusKnots.length; index++) {
  20344. var parsedTorusKnot = torusKnots[index];
  20345. parseTorusKnot(parsedTorusKnot, scene);
  20346. }
  20347. }
  20348. // VertexData
  20349. var vertexData = geometries.vertexData;
  20350. if (vertexData) {
  20351. for (index = 0; index < vertexData.length; index++) {
  20352. var parsedVertexData = vertexData[index];
  20353. parseVertexData(parsedVertexData, scene, rootUrl);
  20354. }
  20355. }
  20356. }
  20357. for (index = 0; index < parsedData.meshes.length; index++) {
  20358. var parsedMesh = parsedData.meshes[index];
  20359. parseMesh(parsedMesh, scene, rootUrl);
  20360. }
  20361. for (index = 0; index < parsedData.cameras.length; index++) {
  20362. var parsedCamera = parsedData.cameras[index];
  20363. parseCamera(parsedCamera, scene);
  20364. }
  20365. if (parsedData.activeCameraID) {
  20366. scene.setActiveCameraByID(parsedData.activeCameraID);
  20367. }
  20368. for (index = 0; index < scene.cameras.length; index++) {
  20369. var camera = scene.cameras[index];
  20370. if (camera._waitingParentId) {
  20371. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20372. camera._waitingParentId = undefined;
  20373. }
  20374. }
  20375. for (index = 0; index < scene.lights.length; index++) {
  20376. var light = scene.lights[index];
  20377. if (light._waitingParentId) {
  20378. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20379. light._waitingParentId = undefined;
  20380. }
  20381. }
  20382. // Sounds
  20383. if (parsedData.sounds) {
  20384. for (index = 0; index < parsedData.sounds.length; index++) {
  20385. var parsedSound = parsedData.sounds[index];
  20386. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20387. parseSound(parsedSound, scene, rootUrl);
  20388. }
  20389. else {
  20390. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20391. }
  20392. }
  20393. }
  20394. for (index = 0; index < scene.meshes.length; index++) {
  20395. var mesh = scene.meshes[index];
  20396. if (mesh._waitingParentId) {
  20397. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20398. mesh._waitingParentId = undefined;
  20399. }
  20400. if (mesh._waitingActions) {
  20401. parseActions(mesh._waitingActions, mesh, scene);
  20402. mesh._waitingActions = undefined;
  20403. }
  20404. }
  20405. // Particles Systems
  20406. if (parsedData.particleSystems) {
  20407. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20408. var parsedParticleSystem = parsedData.particleSystems[index];
  20409. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20410. }
  20411. }
  20412. // Lens flares
  20413. if (parsedData.lensFlareSystems) {
  20414. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20415. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20416. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20417. }
  20418. }
  20419. // Shadows
  20420. if (parsedData.shadowGenerators) {
  20421. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20422. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20423. parseShadowGenerator(parsedShadowGenerator, scene);
  20424. }
  20425. }
  20426. // Actions (scene)
  20427. if (parsedData.actions) {
  20428. parseActions(parsedData.actions, null, scene);
  20429. }
  20430. // Finish
  20431. return true;
  20432. }
  20433. });
  20434. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20435. })(BABYLON || (BABYLON = {}));
  20436. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20437. (function (BABYLON) {
  20438. // Unique ID when we import meshes from Babylon to CSG
  20439. var currentCSGMeshId = 0;
  20440. // # class Vertex
  20441. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20442. // one to provide additional features like texture coordinates and vertex
  20443. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20444. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20445. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20446. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20447. // is not used anywhere else.
  20448. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20449. var Vertex = (function () {
  20450. function Vertex(pos, normal, uv) {
  20451. this.pos = pos;
  20452. this.normal = normal;
  20453. this.uv = uv;
  20454. }
  20455. Vertex.prototype.clone = function () {
  20456. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20457. };
  20458. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20459. // orientation of a polygon is flipped.
  20460. Vertex.prototype.flip = function () {
  20461. this.normal = this.normal.scale(-1);
  20462. };
  20463. // Create a new vertex between this vertex and `other` by linearly
  20464. // interpolating all properties using a parameter of `t`. Subclasses should
  20465. // override this to interpolate additional properties.
  20466. Vertex.prototype.interpolate = function (other, t) {
  20467. 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));
  20468. };
  20469. return Vertex;
  20470. })();
  20471. // # class Plane
  20472. // Represents a plane in 3D space.
  20473. var Plane = (function () {
  20474. function Plane(normal, w) {
  20475. this.normal = normal;
  20476. this.w = w;
  20477. }
  20478. Plane.FromPoints = function (a, b, c) {
  20479. var v0 = c.subtract(a);
  20480. var v1 = b.subtract(a);
  20481. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20482. return null;
  20483. }
  20484. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20485. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20486. };
  20487. Plane.prototype.clone = function () {
  20488. return new Plane(this.normal.clone(), this.w);
  20489. };
  20490. Plane.prototype.flip = function () {
  20491. this.normal.scaleInPlace(-1);
  20492. this.w = -this.w;
  20493. };
  20494. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20495. // fragments in the appropriate lists. Coplanar polygons go into either
  20496. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20497. // respect to this plane. Polygons in front or in back of this plane go into
  20498. // either `front` or `back`.
  20499. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20500. var COPLANAR = 0;
  20501. var FRONT = 1;
  20502. var BACK = 2;
  20503. var SPANNING = 3;
  20504. // Classify each point as well as the entire polygon into one of the above
  20505. // four classes.
  20506. var polygonType = 0;
  20507. var types = [];
  20508. for (var i = 0; i < polygon.vertices.length; i++) {
  20509. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20510. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20511. polygonType |= type;
  20512. types.push(type);
  20513. }
  20514. switch (polygonType) {
  20515. case COPLANAR:
  20516. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20517. break;
  20518. case FRONT:
  20519. front.push(polygon);
  20520. break;
  20521. case BACK:
  20522. back.push(polygon);
  20523. break;
  20524. case SPANNING:
  20525. var f = [], b = [];
  20526. for (i = 0; i < polygon.vertices.length; i++) {
  20527. var j = (i + 1) % polygon.vertices.length;
  20528. var ti = types[i], tj = types[j];
  20529. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20530. if (ti != BACK)
  20531. f.push(vi);
  20532. if (ti != FRONT)
  20533. b.push(ti != BACK ? vi.clone() : vi);
  20534. if ((ti | tj) == SPANNING) {
  20535. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20536. var v = vi.interpolate(vj, t);
  20537. f.push(v);
  20538. b.push(v.clone());
  20539. }
  20540. }
  20541. if (f.length >= 3) {
  20542. var poly = new Polygon(f, polygon.shared);
  20543. if (poly.plane)
  20544. front.push(poly);
  20545. }
  20546. if (b.length >= 3) {
  20547. poly = new Polygon(b, polygon.shared);
  20548. if (poly.plane)
  20549. back.push(poly);
  20550. }
  20551. break;
  20552. }
  20553. };
  20554. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20555. // point is on the plane.
  20556. Plane.EPSILON = 1e-5;
  20557. return Plane;
  20558. })();
  20559. // # class Polygon
  20560. // Represents a convex polygon. The vertices used to initialize a polygon must
  20561. // be coplanar and form a convex loop.
  20562. //
  20563. // Each convex polygon has a `shared` property, which is shared between all
  20564. // polygons that are clones of each other or were split from the same polygon.
  20565. // This can be used to define per-polygon properties (such as surface color).
  20566. var Polygon = (function () {
  20567. function Polygon(vertices, shared) {
  20568. this.vertices = vertices;
  20569. this.shared = shared;
  20570. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20571. }
  20572. Polygon.prototype.clone = function () {
  20573. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20574. return new Polygon(vertices, this.shared);
  20575. };
  20576. Polygon.prototype.flip = function () {
  20577. this.vertices.reverse().map(function (v) {
  20578. v.flip();
  20579. });
  20580. this.plane.flip();
  20581. };
  20582. return Polygon;
  20583. })();
  20584. // # class Node
  20585. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20586. // by picking a polygon to split along. That polygon (and all other coplanar
  20587. // polygons) are added directly to that node and the other polygons are added to
  20588. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20589. // no distinction between internal and leaf nodes.
  20590. var Node = (function () {
  20591. function Node(polygons) {
  20592. this.plane = null;
  20593. this.front = null;
  20594. this.back = null;
  20595. this.polygons = [];
  20596. if (polygons) {
  20597. this.build(polygons);
  20598. }
  20599. }
  20600. Node.prototype.clone = function () {
  20601. var node = new Node();
  20602. node.plane = this.plane && this.plane.clone();
  20603. node.front = this.front && this.front.clone();
  20604. node.back = this.back && this.back.clone();
  20605. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20606. return node;
  20607. };
  20608. // Convert solid space to empty space and empty space to solid space.
  20609. Node.prototype.invert = function () {
  20610. for (var i = 0; i < this.polygons.length; i++) {
  20611. this.polygons[i].flip();
  20612. }
  20613. if (this.plane) {
  20614. this.plane.flip();
  20615. }
  20616. if (this.front) {
  20617. this.front.invert();
  20618. }
  20619. if (this.back) {
  20620. this.back.invert();
  20621. }
  20622. var temp = this.front;
  20623. this.front = this.back;
  20624. this.back = temp;
  20625. };
  20626. // Recursively remove all polygons in `polygons` that are inside this BSP
  20627. // tree.
  20628. Node.prototype.clipPolygons = function (polygons) {
  20629. if (!this.plane)
  20630. return polygons.slice();
  20631. var front = [], back = [];
  20632. for (var i = 0; i < polygons.length; i++) {
  20633. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20634. }
  20635. if (this.front) {
  20636. front = this.front.clipPolygons(front);
  20637. }
  20638. if (this.back) {
  20639. back = this.back.clipPolygons(back);
  20640. }
  20641. else {
  20642. back = [];
  20643. }
  20644. return front.concat(back);
  20645. };
  20646. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20647. // `bsp`.
  20648. Node.prototype.clipTo = function (bsp) {
  20649. this.polygons = bsp.clipPolygons(this.polygons);
  20650. if (this.front)
  20651. this.front.clipTo(bsp);
  20652. if (this.back)
  20653. this.back.clipTo(bsp);
  20654. };
  20655. // Return a list of all polygons in this BSP tree.
  20656. Node.prototype.allPolygons = function () {
  20657. var polygons = this.polygons.slice();
  20658. if (this.front)
  20659. polygons = polygons.concat(this.front.allPolygons());
  20660. if (this.back)
  20661. polygons = polygons.concat(this.back.allPolygons());
  20662. return polygons;
  20663. };
  20664. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20665. // new polygons are filtered down to the bottom of the tree and become new
  20666. // nodes there. Each set of polygons is partitioned using the first polygon
  20667. // (no heuristic is used to pick a good split).
  20668. Node.prototype.build = function (polygons) {
  20669. if (!polygons.length)
  20670. return;
  20671. if (!this.plane)
  20672. this.plane = polygons[0].plane.clone();
  20673. var front = [], back = [];
  20674. for (var i = 0; i < polygons.length; i++) {
  20675. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20676. }
  20677. if (front.length) {
  20678. if (!this.front)
  20679. this.front = new Node();
  20680. this.front.build(front);
  20681. }
  20682. if (back.length) {
  20683. if (!this.back)
  20684. this.back = new Node();
  20685. this.back.build(back);
  20686. }
  20687. };
  20688. return Node;
  20689. })();
  20690. var CSG = (function () {
  20691. function CSG() {
  20692. this.polygons = new Array();
  20693. }
  20694. // Convert BABYLON.Mesh to BABYLON.CSG
  20695. CSG.FromMesh = function (mesh) {
  20696. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20697. if (mesh instanceof BABYLON.Mesh) {
  20698. mesh.computeWorldMatrix(true);
  20699. var matrix = mesh.getWorldMatrix();
  20700. var meshPosition = mesh.position.clone();
  20701. var meshRotation = mesh.rotation.clone();
  20702. var meshScaling = mesh.scaling.clone();
  20703. }
  20704. else {
  20705. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20706. }
  20707. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20708. var subMeshes = mesh.subMeshes;
  20709. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20710. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20711. vertices = [];
  20712. for (var j = 0; j < 3; j++) {
  20713. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20714. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20715. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20716. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20717. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20718. vertex = new Vertex(position, normal, uv);
  20719. vertices.push(vertex);
  20720. }
  20721. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20722. // To handle the case of degenerated triangle
  20723. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20724. if (polygon.plane)
  20725. polygons.push(polygon);
  20726. }
  20727. }
  20728. var csg = CSG.FromPolygons(polygons);
  20729. csg.matrix = matrix;
  20730. csg.position = meshPosition;
  20731. csg.rotation = meshRotation;
  20732. csg.scaling = meshScaling;
  20733. currentCSGMeshId++;
  20734. return csg;
  20735. };
  20736. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20737. CSG.FromPolygons = function (polygons) {
  20738. var csg = new BABYLON.CSG();
  20739. csg.polygons = polygons;
  20740. return csg;
  20741. };
  20742. CSG.prototype.clone = function () {
  20743. var csg = new BABYLON.CSG();
  20744. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20745. csg.copyTransformAttributes(this);
  20746. return csg;
  20747. };
  20748. CSG.prototype.toPolygons = function () {
  20749. return this.polygons;
  20750. };
  20751. CSG.prototype.union = function (csg) {
  20752. var a = new Node(this.clone().polygons);
  20753. var b = new Node(csg.clone().polygons);
  20754. a.clipTo(b);
  20755. b.clipTo(a);
  20756. b.invert();
  20757. b.clipTo(a);
  20758. b.invert();
  20759. a.build(b.allPolygons());
  20760. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20761. };
  20762. CSG.prototype.unionInPlace = function (csg) {
  20763. var a = new Node(this.polygons);
  20764. var b = new Node(csg.polygons);
  20765. a.clipTo(b);
  20766. b.clipTo(a);
  20767. b.invert();
  20768. b.clipTo(a);
  20769. b.invert();
  20770. a.build(b.allPolygons());
  20771. this.polygons = a.allPolygons();
  20772. };
  20773. CSG.prototype.subtract = function (csg) {
  20774. var a = new Node(this.clone().polygons);
  20775. var b = new Node(csg.clone().polygons);
  20776. a.invert();
  20777. a.clipTo(b);
  20778. b.clipTo(a);
  20779. b.invert();
  20780. b.clipTo(a);
  20781. b.invert();
  20782. a.build(b.allPolygons());
  20783. a.invert();
  20784. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20785. };
  20786. CSG.prototype.subtractInPlace = function (csg) {
  20787. var a = new Node(this.polygons);
  20788. var b = new Node(csg.polygons);
  20789. a.invert();
  20790. a.clipTo(b);
  20791. b.clipTo(a);
  20792. b.invert();
  20793. b.clipTo(a);
  20794. b.invert();
  20795. a.build(b.allPolygons());
  20796. a.invert();
  20797. this.polygons = a.allPolygons();
  20798. };
  20799. CSG.prototype.intersect = function (csg) {
  20800. var a = new Node(this.clone().polygons);
  20801. var b = new Node(csg.clone().polygons);
  20802. a.invert();
  20803. b.clipTo(a);
  20804. b.invert();
  20805. a.clipTo(b);
  20806. b.clipTo(a);
  20807. a.build(b.allPolygons());
  20808. a.invert();
  20809. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20810. };
  20811. CSG.prototype.intersectInPlace = function (csg) {
  20812. var a = new Node(this.polygons);
  20813. var b = new Node(csg.polygons);
  20814. a.invert();
  20815. b.clipTo(a);
  20816. b.invert();
  20817. a.clipTo(b);
  20818. b.clipTo(a);
  20819. a.build(b.allPolygons());
  20820. a.invert();
  20821. this.polygons = a.allPolygons();
  20822. };
  20823. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20824. // not modified.
  20825. CSG.prototype.inverse = function () {
  20826. var csg = this.clone();
  20827. csg.inverseInPlace();
  20828. return csg;
  20829. };
  20830. CSG.prototype.inverseInPlace = function () {
  20831. this.polygons.map(function (p) {
  20832. p.flip();
  20833. });
  20834. };
  20835. // This is used to keep meshes transformations so they can be restored
  20836. // when we build back a Babylon Mesh
  20837. // NB : All CSG operations are performed in world coordinates
  20838. CSG.prototype.copyTransformAttributes = function (csg) {
  20839. this.matrix = csg.matrix;
  20840. this.position = csg.position;
  20841. this.rotation = csg.rotation;
  20842. this.scaling = csg.scaling;
  20843. return this;
  20844. };
  20845. // Build Raw mesh from CSG
  20846. // Coordinates here are in world space
  20847. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20848. var matrix = this.matrix.clone();
  20849. matrix.invert();
  20850. 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;
  20851. if (keepSubMeshes) {
  20852. // Sort Polygons, since subMeshes are indices range
  20853. polygons.sort(function (a, b) {
  20854. if (a.shared.meshId === b.shared.meshId) {
  20855. return a.shared.subMeshId - b.shared.subMeshId;
  20856. }
  20857. else {
  20858. return a.shared.meshId - b.shared.meshId;
  20859. }
  20860. });
  20861. }
  20862. for (var i = 0, il = polygons.length; i < il; i++) {
  20863. polygon = polygons[i];
  20864. // Building SubMeshes
  20865. if (!subMesh_dict[polygon.shared.meshId]) {
  20866. subMesh_dict[polygon.shared.meshId] = {};
  20867. }
  20868. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20869. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20870. indexStart: +Infinity,
  20871. indexEnd: -Infinity,
  20872. materialIndex: polygon.shared.materialIndex
  20873. };
  20874. }
  20875. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20876. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20877. polygonIndices[0] = 0;
  20878. polygonIndices[1] = j - 1;
  20879. polygonIndices[2] = j;
  20880. for (var k = 0; k < 3; k++) {
  20881. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20882. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20883. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20884. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20885. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20886. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20887. // Check if 2 points can be merged
  20888. 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)) {
  20889. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20890. uvs.push(uv.x, uv.y);
  20891. normals.push(normal.x, normal.y, normal.z);
  20892. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20893. }
  20894. indices.push(vertex_idx);
  20895. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20896. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20897. currentIndex++;
  20898. }
  20899. }
  20900. }
  20901. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20902. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20903. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20904. mesh.setIndices(indices);
  20905. if (keepSubMeshes) {
  20906. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20907. var materialIndexOffset = 0, materialMaxIndex;
  20908. mesh.subMeshes.length = 0;
  20909. for (var m in subMesh_dict) {
  20910. materialMaxIndex = -1;
  20911. for (var sm in subMesh_dict[m]) {
  20912. subMesh_obj = subMesh_dict[m][sm];
  20913. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20914. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20915. }
  20916. materialIndexOffset += ++materialMaxIndex;
  20917. }
  20918. }
  20919. return mesh;
  20920. };
  20921. // Build Mesh from CSG taking material and transforms into account
  20922. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20923. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20924. mesh.material = material;
  20925. mesh.position.copyFrom(this.position);
  20926. mesh.rotation.copyFrom(this.rotation);
  20927. mesh.scaling.copyFrom(this.scaling);
  20928. mesh.computeWorldMatrix(true);
  20929. return mesh;
  20930. };
  20931. return CSG;
  20932. })();
  20933. BABYLON.CSG = CSG;
  20934. })(BABYLON || (BABYLON = {}));
  20935. //# sourceMappingURL=babylon.csg.js.map
  20936. var BABYLON;
  20937. (function (BABYLON) {
  20938. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20939. __extends(OculusDistortionCorrectionPostProcess, _super);
  20940. //ANY
  20941. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20942. var _this = this;
  20943. _super.call(this, name, "oculusDistortionCorrection", [
  20944. 'LensCenter',
  20945. 'Scale',
  20946. 'ScaleIn',
  20947. 'HmdWarpParam'
  20948. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20949. this._isRightEye = isRightEye;
  20950. this._distortionFactors = cameraSettings.DistortionK;
  20951. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20952. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20953. this.onSizeChanged = function () {
  20954. _this.aspectRatio = _this.width * .5 / _this.height;
  20955. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20956. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20957. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20958. };
  20959. this.onApply = function (effect) {
  20960. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20961. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20962. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20963. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20964. };
  20965. }
  20966. return OculusDistortionCorrectionPostProcess;
  20967. })(BABYLON.PostProcess);
  20968. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20969. })(BABYLON || (BABYLON = {}));
  20970. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20971. // 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
  20972. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20973. var BABYLON;
  20974. (function (BABYLON) {
  20975. (function (JoystickAxis) {
  20976. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20977. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20978. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20979. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20980. var JoystickAxis = BABYLON.JoystickAxis;
  20981. var VirtualJoystick = (function () {
  20982. function VirtualJoystick(leftJoystick) {
  20983. var _this = this;
  20984. if (leftJoystick) {
  20985. this._leftJoystick = true;
  20986. }
  20987. else {
  20988. this._leftJoystick = false;
  20989. }
  20990. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20991. VirtualJoystick._globalJoystickIndex++;
  20992. // By default left & right arrow keys are moving the X
  20993. // and up & down keys are moving the Y
  20994. this._axisTargetedByLeftAndRight = 0 /* X */;
  20995. this._axisTargetedByUpAndDown = 1 /* Y */;
  20996. this.reverseLeftRight = false;
  20997. this.reverseUpDown = false;
  20998. // collections of pointers
  20999. this._touches = new BABYLON.VirtualJoystick.Collection();
  21000. this.deltaPosition = BABYLON.Vector3.Zero();
  21001. this._joystickSensibility = 25;
  21002. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21003. this._rotationSpeed = 25;
  21004. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21005. this._rotateOnAxisRelativeToMesh = false;
  21006. // injecting a canvas element on top of the canvas 3D game
  21007. if (!VirtualJoystick.vjCanvas) {
  21008. window.addEventListener("resize", function () {
  21009. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21010. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21011. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21012. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21013. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21014. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21015. }, false);
  21016. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21017. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21018. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21019. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21020. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21021. VirtualJoystick.vjCanvas.style.width = "100%";
  21022. VirtualJoystick.vjCanvas.style.height = "100%";
  21023. VirtualJoystick.vjCanvas.style.position = "absolute";
  21024. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21025. VirtualJoystick.vjCanvas.style.top = "0px";
  21026. VirtualJoystick.vjCanvas.style.left = "0px";
  21027. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21028. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21029. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21030. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21031. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21032. document.body.appendChild(VirtualJoystick.vjCanvas);
  21033. }
  21034. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21035. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21036. this.pressed = false;
  21037. // default joystick color
  21038. this._joystickColor = "cyan";
  21039. this._joystickPointerID = -1;
  21040. // current joystick position
  21041. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21042. // origin joystick position
  21043. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21044. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21045. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21046. _this._onPointerDown(evt);
  21047. }, false);
  21048. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21049. _this._onPointerMove(evt);
  21050. }, false);
  21051. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21052. _this._onPointerUp(evt);
  21053. }, false);
  21054. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21055. _this._onPointerUp(evt);
  21056. }, false);
  21057. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21058. evt.preventDefault(); // Disables system menu
  21059. }, false);
  21060. requestAnimationFrame(function () {
  21061. _this._drawVirtualJoystick();
  21062. });
  21063. }
  21064. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21065. this._joystickSensibility = newJoystickSensibility;
  21066. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21067. };
  21068. VirtualJoystick.prototype._onPointerDown = function (e) {
  21069. var positionOnScreenCondition;
  21070. e.preventDefault();
  21071. if (this._leftJoystick === true) {
  21072. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21073. }
  21074. else {
  21075. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21076. }
  21077. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21078. // First contact will be dedicated to the virtual joystick
  21079. this._joystickPointerID = e.pointerId;
  21080. this._joystickPointerStartPos.x = e.clientX;
  21081. this._joystickPointerStartPos.y = e.clientY;
  21082. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21083. this._deltaJoystickVector.x = 0;
  21084. this._deltaJoystickVector.y = 0;
  21085. this.pressed = true;
  21086. this._touches.add(e.pointerId.toString(), e);
  21087. }
  21088. else {
  21089. // You can only trigger the action buttons with a joystick declared
  21090. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21091. this._action();
  21092. this._touches.add(e.pointerId.toString(), e);
  21093. }
  21094. }
  21095. };
  21096. VirtualJoystick.prototype._onPointerMove = function (e) {
  21097. // If the current pointer is the one associated to the joystick (first touch contact)
  21098. if (this._joystickPointerID == e.pointerId) {
  21099. this._joystickPointerPos.x = e.clientX;
  21100. this._joystickPointerPos.y = e.clientY;
  21101. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21102. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21103. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21104. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21105. switch (this._axisTargetedByLeftAndRight) {
  21106. case 0 /* X */:
  21107. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21108. break;
  21109. case 1 /* Y */:
  21110. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21111. break;
  21112. case 2 /* Z */:
  21113. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21114. break;
  21115. }
  21116. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21117. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21118. switch (this._axisTargetedByUpAndDown) {
  21119. case 0 /* X */:
  21120. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21121. break;
  21122. case 1 /* Y */:
  21123. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21124. break;
  21125. case 2 /* Z */:
  21126. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21127. break;
  21128. }
  21129. }
  21130. else {
  21131. if (this._touches.item(e.pointerId.toString())) {
  21132. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21133. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21134. }
  21135. }
  21136. };
  21137. VirtualJoystick.prototype._onPointerUp = function (e) {
  21138. this._clearCanvas();
  21139. if (this._joystickPointerID == e.pointerId) {
  21140. this._joystickPointerID = -1;
  21141. this.pressed = false;
  21142. }
  21143. this._deltaJoystickVector.x = 0;
  21144. this._deltaJoystickVector.y = 0;
  21145. this._touches.remove(e.pointerId.toString());
  21146. };
  21147. /**
  21148. * Change the color of the virtual joystick
  21149. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21150. */
  21151. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21152. this._joystickColor = newColor;
  21153. };
  21154. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21155. this._action = action;
  21156. };
  21157. // Define which axis you'd like to control for left & right
  21158. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21159. switch (axis) {
  21160. case 0 /* X */:
  21161. case 1 /* Y */:
  21162. case 2 /* Z */:
  21163. this._axisTargetedByLeftAndRight = axis;
  21164. break;
  21165. default:
  21166. this._axisTargetedByLeftAndRight = 0 /* X */;
  21167. break;
  21168. }
  21169. };
  21170. // Define which axis you'd like to control for up & down
  21171. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21172. switch (axis) {
  21173. case 0 /* X */:
  21174. case 1 /* Y */:
  21175. case 2 /* Z */:
  21176. this._axisTargetedByUpAndDown = axis;
  21177. break;
  21178. default:
  21179. this._axisTargetedByUpAndDown = 1 /* Y */;
  21180. break;
  21181. }
  21182. };
  21183. VirtualJoystick.prototype._clearCanvas = function () {
  21184. if (this._leftJoystick) {
  21185. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21186. }
  21187. else {
  21188. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21189. }
  21190. };
  21191. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21192. var _this = this;
  21193. if (this.pressed) {
  21194. this._clearCanvas();
  21195. this._touches.forEach(function (touch) {
  21196. if (touch.pointerId === _this._joystickPointerID) {
  21197. VirtualJoystick.vjCanvasContext.beginPath();
  21198. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21199. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21200. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21201. VirtualJoystick.vjCanvasContext.stroke();
  21202. VirtualJoystick.vjCanvasContext.beginPath();
  21203. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21204. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21205. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21206. VirtualJoystick.vjCanvasContext.stroke();
  21207. VirtualJoystick.vjCanvasContext.beginPath();
  21208. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21209. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21210. VirtualJoystick.vjCanvasContext.stroke();
  21211. }
  21212. else {
  21213. VirtualJoystick.vjCanvasContext.beginPath();
  21214. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21215. VirtualJoystick.vjCanvasContext.beginPath();
  21216. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21217. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21218. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21219. VirtualJoystick.vjCanvasContext.stroke();
  21220. }
  21221. ;
  21222. });
  21223. }
  21224. requestAnimationFrame(function () {
  21225. _this._drawVirtualJoystick();
  21226. });
  21227. };
  21228. VirtualJoystick.prototype.releaseCanvas = function () {
  21229. if (VirtualJoystick.vjCanvas) {
  21230. document.body.removeChild(VirtualJoystick.vjCanvas);
  21231. VirtualJoystick.vjCanvas = null;
  21232. }
  21233. };
  21234. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21235. VirtualJoystick._globalJoystickIndex = 0;
  21236. return VirtualJoystick;
  21237. })();
  21238. BABYLON.VirtualJoystick = VirtualJoystick;
  21239. })(BABYLON || (BABYLON = {}));
  21240. var BABYLON;
  21241. (function (BABYLON) {
  21242. var VirtualJoystick;
  21243. (function (VirtualJoystick) {
  21244. var Collection = (function () {
  21245. function Collection() {
  21246. this._count = 0;
  21247. this._collection = new Array();
  21248. }
  21249. Collection.prototype.Count = function () {
  21250. return this._count;
  21251. };
  21252. Collection.prototype.add = function (key, item) {
  21253. if (this._collection[key] != undefined) {
  21254. return undefined;
  21255. }
  21256. this._collection[key] = item;
  21257. return ++this._count;
  21258. };
  21259. Collection.prototype.remove = function (key) {
  21260. if (this._collection[key] == undefined) {
  21261. return undefined;
  21262. }
  21263. delete this._collection[key];
  21264. return --this._count;
  21265. };
  21266. Collection.prototype.item = function (key) {
  21267. return this._collection[key];
  21268. };
  21269. Collection.prototype.forEach = function (block) {
  21270. var key;
  21271. for (key in this._collection) {
  21272. if (this._collection.hasOwnProperty(key)) {
  21273. block(this._collection[key]);
  21274. }
  21275. }
  21276. };
  21277. return Collection;
  21278. })();
  21279. VirtualJoystick.Collection = Collection;
  21280. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  21281. })(BABYLON || (BABYLON = {}));
  21282. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21283. var BABYLON;
  21284. (function (BABYLON) {
  21285. var OculusRiftDevKit2013_Metric = {
  21286. HResolution: 1280,
  21287. VResolution: 800,
  21288. HScreenSize: 0.149759993,
  21289. VScreenSize: 0.0935999975,
  21290. VScreenCenter: 0.0467999987,
  21291. EyeToScreenDistance: 0.0410000011,
  21292. LensSeparationDistance: 0.0635000020,
  21293. InterpupillaryDistance: 0.0640000030,
  21294. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21295. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21296. PostProcessScaleFactor: 1.714605507808412,
  21297. LensCenterOffset: 0.151976421
  21298. };
  21299. var _OculusInnerCamera = (function (_super) {
  21300. __extends(_OculusInnerCamera, _super);
  21301. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21302. _super.call(this, name, position, scene);
  21303. this._workMatrix = new BABYLON.Matrix();
  21304. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21305. // Constants
  21306. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21307. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21308. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21309. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21310. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21311. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21312. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21313. // Postprocess
  21314. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21315. }
  21316. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21317. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21318. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21319. return this._projectionMatrix;
  21320. };
  21321. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21322. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21323. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21324. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21325. // Computing target and final matrix
  21326. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21327. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21328. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21329. return this._viewMatrix;
  21330. };
  21331. return _OculusInnerCamera;
  21332. })(BABYLON.FreeCamera);
  21333. var OculusCamera = (function (_super) {
  21334. __extends(OculusCamera, _super);
  21335. function OculusCamera(name, position, scene) {
  21336. _super.call(this, name, position, scene);
  21337. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21338. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21339. this.subCameras.push(this._leftCamera);
  21340. this.subCameras.push(this._rightCamera);
  21341. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21342. }
  21343. OculusCamera.prototype._update = function () {
  21344. this._leftCamera.position.copyFrom(this.position);
  21345. this._rightCamera.position.copyFrom(this.position);
  21346. this._updateCamera(this._leftCamera);
  21347. this._updateCamera(this._rightCamera);
  21348. _super.prototype._update.call(this);
  21349. };
  21350. OculusCamera.prototype._updateCamera = function (camera) {
  21351. camera.minZ = this.minZ;
  21352. camera.maxZ = this.maxZ;
  21353. camera.rotation.x = this.rotation.x;
  21354. camera.rotation.y = this.rotation.y;
  21355. camera.rotation.z = this.rotation.z;
  21356. };
  21357. // Oculus events
  21358. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21359. var yaw = evt.alpha / 180 * Math.PI;
  21360. var pitch = evt.beta / 180 * Math.PI;
  21361. var roll = evt.gamma / 180 * Math.PI;
  21362. if (!this._offsetOrientation) {
  21363. this._offsetOrientation = {
  21364. yaw: yaw,
  21365. pitch: pitch,
  21366. roll: roll
  21367. };
  21368. return;
  21369. }
  21370. else {
  21371. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21372. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21373. this.rotation.z += this._offsetOrientation.roll - roll;
  21374. this._offsetOrientation.yaw = yaw;
  21375. this._offsetOrientation.pitch = pitch;
  21376. this._offsetOrientation.roll = roll;
  21377. }
  21378. };
  21379. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21380. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21381. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21382. };
  21383. OculusCamera.prototype.detachControl = function (element) {
  21384. _super.prototype.detachControl.call(this, element);
  21385. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21386. };
  21387. return OculusCamera;
  21388. })(BABYLON.FreeCamera);
  21389. BABYLON.OculusCamera = OculusCamera;
  21390. })(BABYLON || (BABYLON = {}));
  21391. //# sourceMappingURL=babylon.oculusCamera.js.map
  21392. var BABYLON;
  21393. (function (BABYLON) {
  21394. var OculusRiftDevKit2013_Metric = {
  21395. HResolution: 1280,
  21396. VResolution: 800,
  21397. HScreenSize: 0.149759993,
  21398. VScreenSize: 0.0935999975,
  21399. VScreenCenter: 0.0467999987,
  21400. EyeToScreenDistance: 0.0410000011,
  21401. LensSeparationDistance: 0.0635000020,
  21402. InterpupillaryDistance: 0.0640000030,
  21403. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21404. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21405. PostProcessScaleFactor: 1.714605507808412,
  21406. LensCenterOffset: 0.151976421
  21407. };
  21408. var _OculusInnerGamepadCamera = (function (_super) {
  21409. __extends(_OculusInnerGamepadCamera, _super);
  21410. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21411. _super.call(this, name, position, scene);
  21412. this._workMatrix = new BABYLON.Matrix();
  21413. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21414. // Constants
  21415. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21416. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21417. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21418. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21419. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21420. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21421. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21422. // Postprocess
  21423. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21424. }
  21425. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21426. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21427. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21428. return this._projectionMatrix;
  21429. };
  21430. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21431. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21432. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21433. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21434. // Computing target and final matrix
  21435. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21436. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21437. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21438. return this._viewMatrix;
  21439. };
  21440. return _OculusInnerGamepadCamera;
  21441. })(BABYLON.FreeCamera);
  21442. var OculusGamepadCamera = (function (_super) {
  21443. __extends(OculusGamepadCamera, _super);
  21444. function OculusGamepadCamera(name, position, scene) {
  21445. var _this = this;
  21446. _super.call(this, name, position, scene);
  21447. this.angularSensibility = 200;
  21448. this.moveSensibility = 75;
  21449. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21450. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21451. this.subCameras.push(this._leftCamera);
  21452. this.subCameras.push(this._rightCamera);
  21453. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21454. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21455. _this._onNewGameConnected(gamepad);
  21456. });
  21457. }
  21458. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21459. // Only the first gamepad can control the camera
  21460. if (gamepad.index === 0) {
  21461. this._gamepad = gamepad;
  21462. }
  21463. };
  21464. OculusGamepadCamera.prototype._update = function () {
  21465. this._leftCamera.position.copyFrom(this.position);
  21466. this._rightCamera.position.copyFrom(this.position);
  21467. this._updateCamera(this._leftCamera);
  21468. this._updateCamera(this._rightCamera);
  21469. _super.prototype._update.call(this);
  21470. };
  21471. OculusGamepadCamera.prototype._checkInputs = function () {
  21472. if (!this._gamepad) {
  21473. return;
  21474. }
  21475. var LSValues = this._gamepad.leftStick;
  21476. var normalizedLX = LSValues.x / this.moveSensibility;
  21477. var normalizedLY = LSValues.y / this.moveSensibility;
  21478. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21479. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21480. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21481. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21482. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21483. };
  21484. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21485. camera.minZ = this.minZ;
  21486. camera.maxZ = this.maxZ;
  21487. camera.rotation.x = this.rotation.x;
  21488. camera.rotation.y = this.rotation.y;
  21489. camera.rotation.z = this.rotation.z;
  21490. };
  21491. // Oculus events
  21492. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21493. var yaw = evt.alpha / 180 * Math.PI;
  21494. var pitch = evt.beta / 180 * Math.PI;
  21495. var roll = evt.gamma / 180 * Math.PI;
  21496. if (!this._offsetOrientation) {
  21497. this._offsetOrientation = {
  21498. yaw: yaw,
  21499. pitch: pitch,
  21500. roll: roll
  21501. };
  21502. return;
  21503. }
  21504. else {
  21505. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21506. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21507. this.rotation.z += this._offsetOrientation.roll - roll;
  21508. this._offsetOrientation.yaw = yaw;
  21509. this._offsetOrientation.pitch = pitch;
  21510. this._offsetOrientation.roll = roll;
  21511. }
  21512. };
  21513. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21514. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21515. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21516. };
  21517. OculusGamepadCamera.prototype.detachControl = function (element) {
  21518. _super.prototype.detachControl.call(this, element);
  21519. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21520. };
  21521. OculusGamepadCamera.prototype.dispose = function () {
  21522. this._gamepads.dispose();
  21523. _super.prototype.dispose.call(this);
  21524. };
  21525. return OculusGamepadCamera;
  21526. })(BABYLON.FreeCamera);
  21527. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21528. })(BABYLON || (BABYLON = {}));
  21529. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21530. var BABYLON;
  21531. (function (BABYLON) {
  21532. // We're mainly based on the logic defined into the FreeCamera code
  21533. var VirtualJoysticksCamera = (function (_super) {
  21534. __extends(VirtualJoysticksCamera, _super);
  21535. function VirtualJoysticksCamera(name, position, scene) {
  21536. _super.call(this, name, position, scene);
  21537. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21538. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21539. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21540. this._leftjoystick.setJoystickSensibility(0.15);
  21541. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21542. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21543. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21544. this._rightjoystick.reverseUpDown = true;
  21545. this._rightjoystick.setJoystickSensibility(0.05);
  21546. this._rightjoystick.setJoystickColor("yellow");
  21547. }
  21548. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21549. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21550. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21551. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21552. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21553. if (!this._leftjoystick.pressed) {
  21554. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21555. }
  21556. if (!this._rightjoystick.pressed) {
  21557. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21558. }
  21559. };
  21560. VirtualJoysticksCamera.prototype.dispose = function () {
  21561. this._leftjoystick.releaseCanvas();
  21562. _super.prototype.dispose.call(this);
  21563. };
  21564. return VirtualJoysticksCamera;
  21565. })(BABYLON.FreeCamera);
  21566. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21567. })(BABYLON || (BABYLON = {}));
  21568. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21569. var BABYLON;
  21570. (function (BABYLON) {
  21571. var ShaderMaterial = (function (_super) {
  21572. __extends(ShaderMaterial, _super);
  21573. function ShaderMaterial(name, scene, shaderPath, options) {
  21574. _super.call(this, name, scene);
  21575. this._textures = new Array();
  21576. this._floats = new Array();
  21577. this._floatsArrays = {};
  21578. this._colors3 = new Array();
  21579. this._colors4 = new Array();
  21580. this._vectors2 = new Array();
  21581. this._vectors3 = new Array();
  21582. this._matrices = new Array();
  21583. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21584. this._shaderPath = shaderPath;
  21585. options.needAlphaBlending = options.needAlphaBlending || false;
  21586. options.needAlphaTesting = options.needAlphaTesting || false;
  21587. options.attributes = options.attributes || ["position", "normal", "uv"];
  21588. options.uniforms = options.uniforms || ["worldViewProjection"];
  21589. options.samplers = options.samplers || [];
  21590. this._options = options;
  21591. }
  21592. ShaderMaterial.prototype.needAlphaBlending = function () {
  21593. return this._options.needAlphaBlending;
  21594. };
  21595. ShaderMaterial.prototype.needAlphaTesting = function () {
  21596. return this._options.needAlphaTesting;
  21597. };
  21598. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21599. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21600. this._options.uniforms.push(uniformName);
  21601. }
  21602. };
  21603. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21604. if (this._options.samplers.indexOf(name) === -1) {
  21605. this._options.samplers.push(name);
  21606. }
  21607. this._textures[name] = texture;
  21608. return this;
  21609. };
  21610. ShaderMaterial.prototype.setFloat = function (name, value) {
  21611. this._checkUniform(name);
  21612. this._floats[name] = value;
  21613. return this;
  21614. };
  21615. ShaderMaterial.prototype.setFloats = function (name, value) {
  21616. this._checkUniform(name);
  21617. this._floatsArrays[name] = value;
  21618. return this;
  21619. };
  21620. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21621. this._checkUniform(name);
  21622. this._colors3[name] = value;
  21623. return this;
  21624. };
  21625. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21626. this._checkUniform(name);
  21627. this._colors4[name] = value;
  21628. return this;
  21629. };
  21630. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21631. this._checkUniform(name);
  21632. this._vectors2[name] = value;
  21633. return this;
  21634. };
  21635. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21636. this._checkUniform(name);
  21637. this._vectors3[name] = value;
  21638. return this;
  21639. };
  21640. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21641. this._checkUniform(name);
  21642. this._matrices[name] = value;
  21643. return this;
  21644. };
  21645. ShaderMaterial.prototype.isReady = function () {
  21646. var scene = this.getScene();
  21647. var engine = scene.getEngine();
  21648. if (!this.checkReadyOnEveryCall) {
  21649. if (this._renderId === scene.getRenderId()) {
  21650. return true;
  21651. }
  21652. }
  21653. var previousEffect = this._effect;
  21654. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21655. if (!this._effect.isReady()) {
  21656. return false;
  21657. }
  21658. if (previousEffect !== this._effect) {
  21659. scene.resetCachedMaterial();
  21660. }
  21661. this._renderId = scene.getRenderId();
  21662. return true;
  21663. };
  21664. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21665. var scene = this.getScene();
  21666. if (this._options.uniforms.indexOf("world") !== -1) {
  21667. this._effect.setMatrix("world", world);
  21668. }
  21669. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21670. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21671. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21672. }
  21673. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21674. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21675. }
  21676. };
  21677. ShaderMaterial.prototype.bind = function (world) {
  21678. // Std values
  21679. this.bindOnlyWorldMatrix(world);
  21680. if (this.getScene().getCachedMaterial() !== this) {
  21681. if (this._options.uniforms.indexOf("view") !== -1) {
  21682. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21683. }
  21684. if (this._options.uniforms.indexOf("projection") !== -1) {
  21685. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21686. }
  21687. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21688. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21689. }
  21690. for (var name in this._textures) {
  21691. this._effect.setTexture(name, this._textures[name]);
  21692. }
  21693. for (name in this._floats) {
  21694. this._effect.setFloat(name, this._floats[name]);
  21695. }
  21696. for (name in this._floatsArrays) {
  21697. this._effect.setArray(name, this._floatsArrays[name]);
  21698. }
  21699. for (name in this._colors3) {
  21700. this._effect.setColor3(name, this._colors3[name]);
  21701. }
  21702. for (name in this._colors4) {
  21703. var color = this._colors4[name];
  21704. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21705. }
  21706. for (name in this._vectors2) {
  21707. this._effect.setVector2(name, this._vectors2[name]);
  21708. }
  21709. for (name in this._vectors3) {
  21710. this._effect.setVector3(name, this._vectors3[name]);
  21711. }
  21712. for (name in this._matrices) {
  21713. this._effect.setMatrix(name, this._matrices[name]);
  21714. }
  21715. }
  21716. _super.prototype.bind.call(this, world, null);
  21717. };
  21718. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21719. for (var name in this._textures) {
  21720. this._textures[name].dispose();
  21721. }
  21722. this._textures = [];
  21723. _super.prototype.dispose.call(this, forceDisposeEffect);
  21724. };
  21725. return ShaderMaterial;
  21726. })(BABYLON.Material);
  21727. BABYLON.ShaderMaterial = ShaderMaterial;
  21728. })(BABYLON || (BABYLON = {}));
  21729. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21730. (function (BABYLON) {
  21731. var VertexData = (function () {
  21732. function VertexData() {
  21733. }
  21734. VertexData.prototype.set = function (data, kind) {
  21735. switch (kind) {
  21736. case BABYLON.VertexBuffer.PositionKind:
  21737. this.positions = data;
  21738. break;
  21739. case BABYLON.VertexBuffer.NormalKind:
  21740. this.normals = data;
  21741. break;
  21742. case BABYLON.VertexBuffer.UVKind:
  21743. this.uvs = data;
  21744. break;
  21745. case BABYLON.VertexBuffer.UV2Kind:
  21746. this.uv2s = data;
  21747. break;
  21748. case BABYLON.VertexBuffer.ColorKind:
  21749. this.colors = data;
  21750. break;
  21751. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21752. this.matricesIndices = data;
  21753. break;
  21754. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21755. this.matricesWeights = data;
  21756. break;
  21757. }
  21758. };
  21759. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21760. this._applyTo(mesh, updatable);
  21761. };
  21762. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21763. this._applyTo(geometry, updatable);
  21764. };
  21765. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21766. this._update(mesh);
  21767. };
  21768. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21769. this._update(geometry);
  21770. };
  21771. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21772. if (this.positions) {
  21773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21774. }
  21775. if (this.normals) {
  21776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21777. }
  21778. if (this.uvs) {
  21779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21780. }
  21781. if (this.uv2s) {
  21782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21783. }
  21784. if (this.colors) {
  21785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21786. }
  21787. if (this.matricesIndices) {
  21788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21789. }
  21790. if (this.matricesWeights) {
  21791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21792. }
  21793. if (this.indices) {
  21794. meshOrGeometry.setIndices(this.indices);
  21795. }
  21796. };
  21797. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21798. if (this.positions) {
  21799. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21800. }
  21801. if (this.normals) {
  21802. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21803. }
  21804. if (this.uvs) {
  21805. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21806. }
  21807. if (this.uv2s) {
  21808. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21809. }
  21810. if (this.colors) {
  21811. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21812. }
  21813. if (this.matricesIndices) {
  21814. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21815. }
  21816. if (this.matricesWeights) {
  21817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21818. }
  21819. if (this.indices) {
  21820. meshOrGeometry.setIndices(this.indices);
  21821. }
  21822. };
  21823. VertexData.prototype.transform = function (matrix) {
  21824. var transformed = BABYLON.Vector3.Zero();
  21825. if (this.positions) {
  21826. var position = BABYLON.Vector3.Zero();
  21827. for (var index = 0; index < this.positions.length; index += 3) {
  21828. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21829. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21830. this.positions[index] = transformed.x;
  21831. this.positions[index + 1] = transformed.y;
  21832. this.positions[index + 2] = transformed.z;
  21833. }
  21834. }
  21835. if (this.normals) {
  21836. var normal = BABYLON.Vector3.Zero();
  21837. for (index = 0; index < this.normals.length; index += 3) {
  21838. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21839. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21840. this.normals[index] = transformed.x;
  21841. this.normals[index + 1] = transformed.y;
  21842. this.normals[index + 2] = transformed.z;
  21843. }
  21844. }
  21845. };
  21846. VertexData.prototype.merge = function (other) {
  21847. if (other.indices) {
  21848. if (!this.indices) {
  21849. this.indices = [];
  21850. }
  21851. var offset = this.positions ? this.positions.length / 3 : 0;
  21852. for (var index = 0; index < other.indices.length; index++) {
  21853. this.indices.push(other.indices[index] + offset);
  21854. }
  21855. }
  21856. if (other.positions) {
  21857. if (!this.positions) {
  21858. this.positions = [];
  21859. }
  21860. for (index = 0; index < other.positions.length; index++) {
  21861. this.positions.push(other.positions[index]);
  21862. }
  21863. }
  21864. if (other.normals) {
  21865. if (!this.normals) {
  21866. this.normals = [];
  21867. }
  21868. for (index = 0; index < other.normals.length; index++) {
  21869. this.normals.push(other.normals[index]);
  21870. }
  21871. }
  21872. if (other.uvs) {
  21873. if (!this.uvs) {
  21874. this.uvs = [];
  21875. }
  21876. for (index = 0; index < other.uvs.length; index++) {
  21877. this.uvs.push(other.uvs[index]);
  21878. }
  21879. }
  21880. if (other.uv2s) {
  21881. if (!this.uv2s) {
  21882. this.uv2s = [];
  21883. }
  21884. for (index = 0; index < other.uv2s.length; index++) {
  21885. this.uv2s.push(other.uv2s[index]);
  21886. }
  21887. }
  21888. if (other.matricesIndices) {
  21889. if (!this.matricesIndices) {
  21890. this.matricesIndices = [];
  21891. }
  21892. for (index = 0; index < other.matricesIndices.length; index++) {
  21893. this.matricesIndices.push(other.matricesIndices[index]);
  21894. }
  21895. }
  21896. if (other.matricesWeights) {
  21897. if (!this.matricesWeights) {
  21898. this.matricesWeights = [];
  21899. }
  21900. for (index = 0; index < other.matricesWeights.length; index++) {
  21901. this.matricesWeights.push(other.matricesWeights[index]);
  21902. }
  21903. }
  21904. if (other.colors) {
  21905. if (!this.colors) {
  21906. this.colors = [];
  21907. }
  21908. for (index = 0; index < other.colors.length; index++) {
  21909. this.colors.push(other.colors[index]);
  21910. }
  21911. }
  21912. };
  21913. // Statics
  21914. VertexData.ExtractFromMesh = function (mesh) {
  21915. return VertexData._ExtractFrom(mesh);
  21916. };
  21917. VertexData.ExtractFromGeometry = function (geometry) {
  21918. return VertexData._ExtractFrom(geometry);
  21919. };
  21920. VertexData._ExtractFrom = function (meshOrGeometry) {
  21921. var result = new VertexData();
  21922. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21923. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21924. }
  21925. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21926. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21927. }
  21928. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21929. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21930. }
  21931. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21932. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21933. }
  21934. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21935. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21936. }
  21937. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21938. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21939. }
  21940. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21941. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21942. }
  21943. result.indices = meshOrGeometry.getIndices();
  21944. return result;
  21945. };
  21946. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21947. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21948. closeArray = closeArray || false;
  21949. closePath = closePath || false;
  21950. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21951. offset = offset || defaultOffset;
  21952. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21953. var positions = [];
  21954. var indices = [];
  21955. var normals = [];
  21956. var uvs = [];
  21957. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21958. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21959. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21960. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21961. var minlg; // minimal length among all paths from pathArray
  21962. var lg = []; // array of path lengths : nb of vertex per path
  21963. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21964. var p; // path iterator
  21965. var i; // point iterator
  21966. var j; // point iterator
  21967. // if single path in pathArray
  21968. if (pathArray.length < 2) {
  21969. var ar1 = [];
  21970. var ar2 = [];
  21971. for (i = 0; i < pathArray[0].length - offset; i++) {
  21972. ar1.push(pathArray[0][i]);
  21973. ar2.push(pathArray[0][i + offset]);
  21974. }
  21975. pathArray = [ar1, ar2];
  21976. }
  21977. // positions and horizontal distances (u)
  21978. var idc = 0;
  21979. minlg = pathArray[0].length;
  21980. for (p = 0; p < pathArray.length; p++) {
  21981. uTotalDistance[p] = 0;
  21982. us[p] = [0];
  21983. var path = pathArray[p];
  21984. var l = path.length;
  21985. minlg = (minlg < l) ? minlg : l;
  21986. lg[p] = l;
  21987. idx[p] = idc;
  21988. j = 0;
  21989. while (j < l) {
  21990. positions.push(path[j].x, path[j].y, path[j].z);
  21991. if (j > 0) {
  21992. var vectlg = path[j].subtract(path[j - 1]).length();
  21993. var dist = vectlg + uTotalDistance[p];
  21994. us[p].push(dist);
  21995. uTotalDistance[p] = dist;
  21996. }
  21997. j++;
  21998. }
  21999. if (closePath) {
  22000. vectlg = path[0].subtract(path[j - 1]).length();
  22001. dist = vectlg + uTotalDistance[p];
  22002. uTotalDistance[p] = dist;
  22003. }
  22004. idc += l;
  22005. }
  22006. for (i = 0; i < minlg; i++) {
  22007. vTotalDistance[i] = 0;
  22008. vs[i] = [0];
  22009. var path1;
  22010. var path2;
  22011. for (p = 0; p < pathArray.length - 1; p++) {
  22012. path1 = pathArray[p];
  22013. path2 = pathArray[p + 1];
  22014. vectlg = path2[i].subtract(path1[i]).length();
  22015. dist = vectlg + vTotalDistance[i];
  22016. vs[i].push(dist);
  22017. vTotalDistance[i] = dist;
  22018. }
  22019. if (closeArray) {
  22020. path1 = pathArray[p];
  22021. path2 = pathArray[0];
  22022. vectlg = path2[i].subtract(path1[i]).length();
  22023. dist = vectlg + vTotalDistance[i];
  22024. vTotalDistance[i] = dist;
  22025. }
  22026. }
  22027. // uvs
  22028. var u;
  22029. var v;
  22030. for (p = 0; p < pathArray.length; p++) {
  22031. for (i = 0; i < minlg; i++) {
  22032. u = us[p][i] / uTotalDistance[p];
  22033. v = vs[i][p] / vTotalDistance[i];
  22034. uvs.push(u, v);
  22035. }
  22036. }
  22037. // indices
  22038. p = 0; // path index
  22039. var pi = 0; // positions array index
  22040. var l1 = lg[p] - 1; // path1 length
  22041. var l2 = lg[p + 1] - 1; // path2 length
  22042. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22043. var shft = idx[1] - idx[0]; // shift
  22044. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22045. var t1; // two consecutive triangles, so 4 points : point1
  22046. var t2; // point2
  22047. var t3; // point3
  22048. var t4; // point4
  22049. while (pi <= min && p < path1nb) {
  22050. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  22051. t1 = pi;
  22052. t2 = pi + shft;
  22053. t3 = pi + 1;
  22054. t4 = pi + shft + 1;
  22055. indices.push(pi, pi + shft, pi + 1);
  22056. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22057. pi += 1;
  22058. if (pi === min) {
  22059. if (closePath) {
  22060. indices.push(pi, pi + shft, idx[p]);
  22061. indices.push(idx[p] + shft, idx[p], pi + shft);
  22062. t3 = idx[p];
  22063. t4 = idx[p] + shft;
  22064. }
  22065. p++;
  22066. if (p === lg.length - 1) {
  22067. shft = idx[0] - idx[p];
  22068. l1 = lg[p] - 1;
  22069. l2 = lg[0] - 1;
  22070. }
  22071. else {
  22072. shft = idx[p + 1] - idx[p];
  22073. l1 = lg[p] - 1;
  22074. l2 = lg[p + 1] - 1;
  22075. }
  22076. pi = idx[p];
  22077. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22078. }
  22079. }
  22080. // normals
  22081. VertexData.ComputeNormals(positions, indices, normals);
  22082. // sides
  22083. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22084. // Result
  22085. var vertexData = new VertexData();
  22086. vertexData.indices = indices;
  22087. vertexData.positions = positions;
  22088. vertexData.normals = normals;
  22089. vertexData.uvs = uvs;
  22090. return vertexData;
  22091. };
  22092. VertexData.CreateBox = function (size, sideOrientation) {
  22093. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22094. var normalsSource = [
  22095. new BABYLON.Vector3(0, 0, 1),
  22096. new BABYLON.Vector3(0, 0, -1),
  22097. new BABYLON.Vector3(1, 0, 0),
  22098. new BABYLON.Vector3(-1, 0, 0),
  22099. new BABYLON.Vector3(0, 1, 0),
  22100. new BABYLON.Vector3(0, -1, 0)
  22101. ];
  22102. var indices = [];
  22103. var positions = [];
  22104. var normals = [];
  22105. var uvs = [];
  22106. size = size || 1;
  22107. for (var index = 0; index < normalsSource.length; index++) {
  22108. var normal = normalsSource[index];
  22109. // Get two vectors perpendicular to the face normal and to each other.
  22110. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22111. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22112. // Six indices (two triangles) per face.
  22113. var verticesLength = positions.length / 3;
  22114. indices.push(verticesLength);
  22115. indices.push(verticesLength + 1);
  22116. indices.push(verticesLength + 2);
  22117. indices.push(verticesLength);
  22118. indices.push(verticesLength + 2);
  22119. indices.push(verticesLength + 3);
  22120. // Four vertices per face.
  22121. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22122. positions.push(vertex.x, vertex.y, vertex.z);
  22123. normals.push(normal.x, normal.y, normal.z);
  22124. uvs.push(1.0, 1.0);
  22125. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22126. positions.push(vertex.x, vertex.y, vertex.z);
  22127. normals.push(normal.x, normal.y, normal.z);
  22128. uvs.push(0.0, 1.0);
  22129. vertex = normal.add(side1).add(side2).scale(size / 2);
  22130. positions.push(vertex.x, vertex.y, vertex.z);
  22131. normals.push(normal.x, normal.y, normal.z);
  22132. uvs.push(0.0, 0.0);
  22133. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22134. positions.push(vertex.x, vertex.y, vertex.z);
  22135. normals.push(normal.x, normal.y, normal.z);
  22136. uvs.push(1.0, 0.0);
  22137. }
  22138. // sides
  22139. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22140. // Result
  22141. var vertexData = new VertexData();
  22142. vertexData.indices = indices;
  22143. vertexData.positions = positions;
  22144. vertexData.normals = normals;
  22145. vertexData.uvs = uvs;
  22146. return vertexData;
  22147. };
  22148. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22149. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22150. segments = segments || 32;
  22151. diameter = diameter || 1;
  22152. var radius = diameter / 2;
  22153. var totalZRotationSteps = 2 + segments;
  22154. var totalYRotationSteps = 2 * totalZRotationSteps;
  22155. var indices = [];
  22156. var positions = [];
  22157. var normals = [];
  22158. var uvs = [];
  22159. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22160. var normalizedZ = zRotationStep / totalZRotationSteps;
  22161. var angleZ = (normalizedZ * Math.PI);
  22162. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22163. var normalizedY = yRotationStep / totalYRotationSteps;
  22164. var angleY = normalizedY * Math.PI * 2;
  22165. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22166. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22167. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22168. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22169. var vertex = complete.scale(radius);
  22170. var normal = BABYLON.Vector3.Normalize(vertex);
  22171. positions.push(vertex.x, vertex.y, vertex.z);
  22172. normals.push(normal.x, normal.y, normal.z);
  22173. uvs.push(normalizedZ, normalizedY);
  22174. }
  22175. if (zRotationStep > 0) {
  22176. var verticesCount = positions.length / 3;
  22177. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22178. indices.push((firstIndex));
  22179. indices.push((firstIndex + 1));
  22180. indices.push(firstIndex + totalYRotationSteps + 1);
  22181. indices.push((firstIndex + totalYRotationSteps + 1));
  22182. indices.push((firstIndex + 1));
  22183. indices.push((firstIndex + totalYRotationSteps + 2));
  22184. }
  22185. }
  22186. }
  22187. // Sides
  22188. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22189. // Result
  22190. var vertexData = new VertexData();
  22191. vertexData.indices = indices;
  22192. vertexData.positions = positions;
  22193. vertexData.normals = normals;
  22194. vertexData.uvs = uvs;
  22195. return vertexData;
  22196. };
  22197. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22198. if (subdivisions === void 0) { subdivisions = 1; }
  22199. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22200. var radiusTop = diameterTop / 2;
  22201. var radiusBottom = diameterBottom / 2;
  22202. var indices = [];
  22203. var positions = [];
  22204. var normals = [];
  22205. var uvs = [];
  22206. height = height || 1;
  22207. diameterTop = diameterTop || 0.5;
  22208. diameterBottom = diameterBottom || 1;
  22209. tessellation = tessellation || 16;
  22210. subdivisions = subdivisions || 1;
  22211. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22212. var getCircleVector = function (i) {
  22213. var angle = (i * 2.0 * Math.PI / tessellation);
  22214. var dx = Math.cos(angle);
  22215. var dz = Math.sin(angle);
  22216. return new BABYLON.Vector3(dx, 0, dz);
  22217. };
  22218. var createCylinderCap = function (isTop) {
  22219. var radius = isTop ? radiusTop : radiusBottom;
  22220. if (radius === 0) {
  22221. return;
  22222. }
  22223. var vbase = positions.length / 3;
  22224. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22225. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22226. if (!isTop) {
  22227. offset.scaleInPlace(-1);
  22228. textureScale.x = -textureScale.x;
  22229. }
  22230. for (var i = 0; i < tessellation; i++) {
  22231. var circleVector = getCircleVector(i);
  22232. var position = circleVector.scale(radius).add(offset);
  22233. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22234. positions.push(position.x, position.y, position.z);
  22235. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22236. }
  22237. for (i = 0; i < tessellation - 2; i++) {
  22238. if (!isTop) {
  22239. indices.push(vbase);
  22240. indices.push(vbase + (i + 2) % tessellation);
  22241. indices.push(vbase + (i + 1) % tessellation);
  22242. }
  22243. else {
  22244. indices.push(vbase);
  22245. indices.push(vbase + (i + 1) % tessellation);
  22246. indices.push(vbase + (i + 2) % tessellation);
  22247. }
  22248. }
  22249. };
  22250. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22251. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22252. var stride = tessellation + 1;
  22253. for (var i = 0; i <= tessellation; i++) {
  22254. var circleVector = getCircleVector(i);
  22255. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22256. var position, radius = radiusBottom;
  22257. for (var s = 0; s <= subdivisions; s++) {
  22258. // Update variables
  22259. position = circleVector.scale(radius);
  22260. position.addInPlace(base.add(offset.scale(s)));
  22261. textureCoordinate.y += 1 / subdivisions;
  22262. radius += (radiusTop - radiusBottom) / subdivisions;
  22263. // Push in arrays
  22264. positions.push(position.x, position.y, position.z);
  22265. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22266. }
  22267. }
  22268. subdivisions += 1;
  22269. for (s = 0; s < subdivisions - 1; s++) {
  22270. for (i = 0; i <= tessellation; i++) {
  22271. indices.push(i * subdivisions + s);
  22272. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22273. indices.push(i * subdivisions + (s + 1));
  22274. indices.push(i * subdivisions + (s + 1));
  22275. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22276. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22277. }
  22278. }
  22279. // Create flat triangle fan caps to seal the top and bottom.
  22280. createCylinderCap(true);
  22281. createCylinderCap(false);
  22282. // Normals
  22283. VertexData.ComputeNormals(positions, indices, normals);
  22284. // Sides
  22285. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22286. // Result
  22287. var vertexData = new VertexData();
  22288. vertexData.indices = indices;
  22289. vertexData.positions = positions;
  22290. vertexData.normals = normals;
  22291. vertexData.uvs = uvs;
  22292. return vertexData;
  22293. };
  22294. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22295. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22296. var indices = [];
  22297. var positions = [];
  22298. var normals = [];
  22299. var uvs = [];
  22300. diameter = diameter || 1;
  22301. thickness = thickness || 0.5;
  22302. tessellation = tessellation || 16;
  22303. var stride = tessellation + 1;
  22304. for (var i = 0; i <= tessellation; i++) {
  22305. var u = i / tessellation;
  22306. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22307. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22308. for (var j = 0; j <= tessellation; j++) {
  22309. var v = 1 - j / tessellation;
  22310. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22311. var dx = Math.cos(innerAngle);
  22312. var dy = Math.sin(innerAngle);
  22313. // Create a vertex.
  22314. var normal = new BABYLON.Vector3(dx, dy, 0);
  22315. var position = normal.scale(thickness / 2);
  22316. var textureCoordinate = new BABYLON.Vector2(u, v);
  22317. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22318. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22319. positions.push(position.x, position.y, position.z);
  22320. normals.push(normal.x, normal.y, normal.z);
  22321. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22322. // And create indices for two triangles.
  22323. var nextI = (i + 1) % stride;
  22324. var nextJ = (j + 1) % stride;
  22325. indices.push(i * stride + j);
  22326. indices.push(i * stride + nextJ);
  22327. indices.push(nextI * stride + j);
  22328. indices.push(i * stride + nextJ);
  22329. indices.push(nextI * stride + nextJ);
  22330. indices.push(nextI * stride + j);
  22331. }
  22332. }
  22333. // Sides
  22334. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22335. // Result
  22336. var vertexData = new VertexData();
  22337. vertexData.indices = indices;
  22338. vertexData.positions = positions;
  22339. vertexData.normals = normals;
  22340. vertexData.uvs = uvs;
  22341. return vertexData;
  22342. };
  22343. VertexData.CreateLines = function (points) {
  22344. var indices = [];
  22345. var positions = [];
  22346. for (var index = 0; index < points.length; index++) {
  22347. positions.push(points[index].x, points[index].y, points[index].z);
  22348. if (index > 0) {
  22349. indices.push(index - 1);
  22350. indices.push(index);
  22351. }
  22352. }
  22353. // Result
  22354. var vertexData = new VertexData();
  22355. vertexData.indices = indices;
  22356. vertexData.positions = positions;
  22357. return vertexData;
  22358. };
  22359. VertexData.CreateGround = function (width, height, subdivisions) {
  22360. var indices = [];
  22361. var positions = [];
  22362. var normals = [];
  22363. var uvs = [];
  22364. var row, col;
  22365. width = width || 1;
  22366. height = height || 1;
  22367. subdivisions = subdivisions || 1;
  22368. for (row = 0; row <= subdivisions; row++) {
  22369. for (col = 0; col <= subdivisions; col++) {
  22370. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22371. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22372. positions.push(position.x, position.y, position.z);
  22373. normals.push(normal.x, normal.y, normal.z);
  22374. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22375. }
  22376. }
  22377. for (row = 0; row < subdivisions; row++) {
  22378. for (col = 0; col < subdivisions; col++) {
  22379. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22380. indices.push(col + 1 + row * (subdivisions + 1));
  22381. indices.push(col + row * (subdivisions + 1));
  22382. indices.push(col + (row + 1) * (subdivisions + 1));
  22383. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22384. indices.push(col + row * (subdivisions + 1));
  22385. }
  22386. }
  22387. // Result
  22388. var vertexData = new VertexData();
  22389. vertexData.indices = indices;
  22390. vertexData.positions = positions;
  22391. vertexData.normals = normals;
  22392. vertexData.uvs = uvs;
  22393. return vertexData;
  22394. };
  22395. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22396. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22397. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22398. var indices = [];
  22399. var positions = [];
  22400. var normals = [];
  22401. var uvs = [];
  22402. var row, col, tileRow, tileCol;
  22403. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22404. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22405. precision.w = (precision.w < 1) ? 1 : precision.w;
  22406. precision.h = (precision.h < 1) ? 1 : precision.h;
  22407. var tileSize = {
  22408. 'w': (xmax - xmin) / subdivisions.w,
  22409. 'h': (zmax - zmin) / subdivisions.h
  22410. };
  22411. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22412. // Indices
  22413. var base = positions.length / 3;
  22414. var rowLength = precision.w + 1;
  22415. for (row = 0; row < precision.h; row++) {
  22416. for (col = 0; col < precision.w; col++) {
  22417. var square = [
  22418. base + col + row * rowLength,
  22419. base + (col + 1) + row * rowLength,
  22420. base + (col + 1) + (row + 1) * rowLength,
  22421. base + col + (row + 1) * rowLength
  22422. ];
  22423. indices.push(square[1]);
  22424. indices.push(square[2]);
  22425. indices.push(square[3]);
  22426. indices.push(square[0]);
  22427. indices.push(square[1]);
  22428. indices.push(square[3]);
  22429. }
  22430. }
  22431. // Position, normals and uvs
  22432. var position = BABYLON.Vector3.Zero();
  22433. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22434. for (row = 0; row <= precision.h; row++) {
  22435. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22436. for (col = 0; col <= precision.w; col++) {
  22437. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22438. position.y = 0;
  22439. positions.push(position.x, position.y, position.z);
  22440. normals.push(normal.x, normal.y, normal.z);
  22441. uvs.push(col / precision.w, row / precision.h);
  22442. }
  22443. }
  22444. }
  22445. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22446. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22447. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22448. }
  22449. }
  22450. // Result
  22451. var vertexData = new VertexData();
  22452. vertexData.indices = indices;
  22453. vertexData.positions = positions;
  22454. vertexData.normals = normals;
  22455. vertexData.uvs = uvs;
  22456. return vertexData;
  22457. };
  22458. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22459. var indices = [];
  22460. var positions = [];
  22461. var normals = [];
  22462. var uvs = [];
  22463. var row, col;
  22464. for (row = 0; row <= subdivisions; row++) {
  22465. for (col = 0; col <= subdivisions; col++) {
  22466. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22467. // Compute height
  22468. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22469. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22470. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22471. var r = buffer[pos] / 255.0;
  22472. var g = buffer[pos + 1] / 255.0;
  22473. var b = buffer[pos + 2] / 255.0;
  22474. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22475. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22476. // Add vertex
  22477. positions.push(position.x, position.y, position.z);
  22478. normals.push(0, 0, 0);
  22479. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22480. }
  22481. }
  22482. for (row = 0; row < subdivisions; row++) {
  22483. for (col = 0; col < subdivisions; col++) {
  22484. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22485. indices.push(col + 1 + row * (subdivisions + 1));
  22486. indices.push(col + row * (subdivisions + 1));
  22487. indices.push(col + (row + 1) * (subdivisions + 1));
  22488. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22489. indices.push(col + row * (subdivisions + 1));
  22490. }
  22491. }
  22492. // Normals
  22493. VertexData.ComputeNormals(positions, indices, normals);
  22494. // Result
  22495. var vertexData = new VertexData();
  22496. vertexData.indices = indices;
  22497. vertexData.positions = positions;
  22498. vertexData.normals = normals;
  22499. vertexData.uvs = uvs;
  22500. return vertexData;
  22501. };
  22502. VertexData.CreatePlane = function (size, sideOrientation) {
  22503. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22504. var indices = [];
  22505. var positions = [];
  22506. var normals = [];
  22507. var uvs = [];
  22508. size = size || 1;
  22509. // Vertices
  22510. var halfSize = size / 2.0;
  22511. positions.push(-halfSize, -halfSize, 0);
  22512. normals.push(0, 0, -1.0);
  22513. uvs.push(0.0, 0.0);
  22514. positions.push(halfSize, -halfSize, 0);
  22515. normals.push(0, 0, -1.0);
  22516. uvs.push(1.0, 0.0);
  22517. positions.push(halfSize, halfSize, 0);
  22518. normals.push(0, 0, -1.0);
  22519. uvs.push(1.0, 1.0);
  22520. positions.push(-halfSize, halfSize, 0);
  22521. normals.push(0, 0, -1.0);
  22522. uvs.push(0.0, 1.0);
  22523. // Indices
  22524. indices.push(0);
  22525. indices.push(1);
  22526. indices.push(2);
  22527. indices.push(0);
  22528. indices.push(2);
  22529. indices.push(3);
  22530. // Sides
  22531. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22532. // Result
  22533. var vertexData = new VertexData();
  22534. vertexData.indices = indices;
  22535. vertexData.positions = positions;
  22536. vertexData.normals = normals;
  22537. vertexData.uvs = uvs;
  22538. return vertexData;
  22539. };
  22540. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22541. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22542. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22543. var indices = [];
  22544. var positions = [];
  22545. var normals = [];
  22546. var uvs = [];
  22547. radius = radius || 2;
  22548. tube = tube || 0.5;
  22549. radialSegments = radialSegments || 32;
  22550. tubularSegments = tubularSegments || 32;
  22551. p = p || 2;
  22552. q = q || 3;
  22553. // Helper
  22554. var getPos = function (angle) {
  22555. var cu = Math.cos(angle);
  22556. var su = Math.sin(angle);
  22557. var quOverP = q / p * angle;
  22558. var cs = Math.cos(quOverP);
  22559. var tx = radius * (2 + cs) * 0.5 * cu;
  22560. var ty = radius * (2 + cs) * su * 0.5;
  22561. var tz = radius * Math.sin(quOverP) * 0.5;
  22562. return new BABYLON.Vector3(tx, ty, tz);
  22563. };
  22564. for (var i = 0; i <= radialSegments; i++) {
  22565. var modI = i % radialSegments;
  22566. var u = modI / radialSegments * 2 * p * Math.PI;
  22567. var p1 = getPos(u);
  22568. var p2 = getPos(u + 0.01);
  22569. var tang = p2.subtract(p1);
  22570. var n = p2.add(p1);
  22571. var bitan = BABYLON.Vector3.Cross(tang, n);
  22572. n = BABYLON.Vector3.Cross(bitan, tang);
  22573. bitan.normalize();
  22574. n.normalize();
  22575. for (var j = 0; j < tubularSegments; j++) {
  22576. var modJ = j % tubularSegments;
  22577. var v = modJ / tubularSegments * 2 * Math.PI;
  22578. var cx = -tube * Math.cos(v);
  22579. var cy = tube * Math.sin(v);
  22580. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22581. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22582. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22583. uvs.push(i / radialSegments);
  22584. uvs.push(j / tubularSegments);
  22585. }
  22586. }
  22587. for (i = 0; i < radialSegments; i++) {
  22588. for (j = 0; j < tubularSegments; j++) {
  22589. var jNext = (j + 1) % tubularSegments;
  22590. var a = i * tubularSegments + j;
  22591. var b = (i + 1) * tubularSegments + j;
  22592. var c = (i + 1) * tubularSegments + jNext;
  22593. var d = i * tubularSegments + jNext;
  22594. indices.push(d);
  22595. indices.push(b);
  22596. indices.push(a);
  22597. indices.push(d);
  22598. indices.push(c);
  22599. indices.push(b);
  22600. }
  22601. }
  22602. // Normals
  22603. VertexData.ComputeNormals(positions, indices, normals);
  22604. // Sides
  22605. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22606. // Result
  22607. var vertexData = new VertexData();
  22608. vertexData.indices = indices;
  22609. vertexData.positions = positions;
  22610. vertexData.normals = normals;
  22611. vertexData.uvs = uvs;
  22612. return vertexData;
  22613. };
  22614. // Tools
  22615. VertexData.ComputeNormals = function (positions, indices, normals) {
  22616. var positionVectors = [];
  22617. var facesOfVertices = [];
  22618. var index;
  22619. for (index = 0; index < positions.length; index += 3) {
  22620. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22621. positionVectors.push(vector3);
  22622. facesOfVertices.push([]);
  22623. }
  22624. // Compute normals
  22625. var facesNormals = [];
  22626. for (index = 0; index < indices.length / 3; index++) {
  22627. var i1 = indices[index * 3];
  22628. var i2 = indices[index * 3 + 1];
  22629. var i3 = indices[index * 3 + 2];
  22630. var p1 = positionVectors[i1];
  22631. var p2 = positionVectors[i2];
  22632. var p3 = positionVectors[i3];
  22633. var p1p2 = p1.subtract(p2);
  22634. var p3p2 = p3.subtract(p2);
  22635. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22636. facesOfVertices[i1].push(index);
  22637. facesOfVertices[i2].push(index);
  22638. facesOfVertices[i3].push(index);
  22639. }
  22640. for (index = 0; index < positionVectors.length; index++) {
  22641. var faces = facesOfVertices[index];
  22642. var normal = BABYLON.Vector3.Zero();
  22643. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22644. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22645. }
  22646. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22647. normals[index * 3] = normal.x;
  22648. normals[index * 3 + 1] = normal.y;
  22649. normals[index * 3 + 2] = normal.z;
  22650. }
  22651. };
  22652. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22653. var li = indices.length;
  22654. var ln = normals.length;
  22655. var i;
  22656. var n;
  22657. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22658. switch (sideOrientation) {
  22659. case BABYLON.Mesh.FRONTSIDE:
  22660. break;
  22661. case BABYLON.Mesh.BACKSIDE:
  22662. var tmp;
  22663. for (i = 0; i < li; i += 3) {
  22664. tmp = indices[i];
  22665. indices[i] = indices[i + 2];
  22666. indices[i + 2] = tmp;
  22667. }
  22668. for (n = 0; n < ln; n++) {
  22669. normals[n] = -normals[n];
  22670. }
  22671. break;
  22672. case BABYLON.Mesh.DOUBLESIDE:
  22673. // positions
  22674. var lp = positions.length;
  22675. var l = lp / 3;
  22676. for (var p = 0; p < lp; p++) {
  22677. positions[lp + p] = positions[p];
  22678. }
  22679. for (i = 0; i < li; i += 3) {
  22680. indices[i + li] = indices[i + 2] + l;
  22681. indices[i + 1 + li] = indices[i + 1] + l;
  22682. indices[i + 2 + li] = indices[i] + l;
  22683. }
  22684. for (n = 0; n < ln; n++) {
  22685. normals[ln + n] = -normals[n];
  22686. }
  22687. // uvs
  22688. var lu = uvs.length;
  22689. for (var u = 0; u < lu; u++) {
  22690. uvs[u + lu] = uvs[u];
  22691. }
  22692. break;
  22693. }
  22694. };
  22695. return VertexData;
  22696. })();
  22697. BABYLON.VertexData = VertexData;
  22698. })(BABYLON || (BABYLON = {}));
  22699. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22700. var BABYLON;
  22701. (function (BABYLON) {
  22702. var buildCamera = function (that, name) {
  22703. that._leftCamera.isIntermediate = true;
  22704. that.subCameras.push(that._leftCamera);
  22705. that.subCameras.push(that._rightCamera);
  22706. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22707. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22708. that._anaglyphPostProcess.onApply = function (effect) {
  22709. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22710. };
  22711. that._update();
  22712. };
  22713. var AnaglyphArcRotateCamera = (function (_super) {
  22714. __extends(AnaglyphArcRotateCamera, _super);
  22715. // ANY
  22716. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22717. _super.call(this, name, alpha, beta, radius, target, scene);
  22718. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22719. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22720. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22721. buildCamera(this, name);
  22722. }
  22723. AnaglyphArcRotateCamera.prototype._update = function () {
  22724. this._updateCamera(this._leftCamera);
  22725. this._updateCamera(this._rightCamera);
  22726. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22727. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22728. _super.prototype._update.call(this);
  22729. };
  22730. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22731. camera.beta = this.beta;
  22732. camera.radius = this.radius;
  22733. camera.minZ = this.minZ;
  22734. camera.maxZ = this.maxZ;
  22735. camera.fov = this.fov;
  22736. camera.target = this.target;
  22737. };
  22738. return AnaglyphArcRotateCamera;
  22739. })(BABYLON.ArcRotateCamera);
  22740. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22741. var AnaglyphFreeCamera = (function (_super) {
  22742. __extends(AnaglyphFreeCamera, _super);
  22743. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22744. _super.call(this, name, position, scene);
  22745. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22746. this._transformMatrix = new BABYLON.Matrix();
  22747. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22748. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22749. buildCamera(this, name);
  22750. }
  22751. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22752. var target = this.getTarget();
  22753. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22754. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22755. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22756. };
  22757. AnaglyphFreeCamera.prototype._update = function () {
  22758. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22759. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22760. this._updateCamera(this._leftCamera);
  22761. this._updateCamera(this._rightCamera);
  22762. _super.prototype._update.call(this);
  22763. };
  22764. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22765. camera.minZ = this.minZ;
  22766. camera.maxZ = this.maxZ;
  22767. camera.fov = this.fov;
  22768. camera.viewport = this.viewport;
  22769. camera.setTarget(this.getTarget());
  22770. };
  22771. return AnaglyphFreeCamera;
  22772. })(BABYLON.FreeCamera);
  22773. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22774. })(BABYLON || (BABYLON = {}));
  22775. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22776. var BABYLON;
  22777. (function (BABYLON) {
  22778. var AnaglyphPostProcess = (function (_super) {
  22779. __extends(AnaglyphPostProcess, _super);
  22780. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22781. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22782. }
  22783. return AnaglyphPostProcess;
  22784. })(BABYLON.PostProcess);
  22785. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22786. })(BABYLON || (BABYLON = {}));
  22787. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22788. (function (BABYLON) {
  22789. var Tags = (function () {
  22790. function Tags() {
  22791. }
  22792. Tags.EnableFor = function (obj) {
  22793. obj._tags = obj._tags || {};
  22794. obj.hasTags = function () {
  22795. return Tags.HasTags(obj);
  22796. };
  22797. obj.addTags = function (tagsString) {
  22798. return Tags.AddTagsTo(obj, tagsString);
  22799. };
  22800. obj.removeTags = function (tagsString) {
  22801. return Tags.RemoveTagsFrom(obj, tagsString);
  22802. };
  22803. obj.matchesTagsQuery = function (tagsQuery) {
  22804. return Tags.MatchesQuery(obj, tagsQuery);
  22805. };
  22806. };
  22807. Tags.DisableFor = function (obj) {
  22808. delete obj._tags;
  22809. delete obj.hasTags;
  22810. delete obj.addTags;
  22811. delete obj.removeTags;
  22812. delete obj.matchesTagsQuery;
  22813. };
  22814. Tags.HasTags = function (obj) {
  22815. if (!obj._tags) {
  22816. return false;
  22817. }
  22818. return !BABYLON.Tools.IsEmpty(obj._tags);
  22819. };
  22820. Tags.GetTags = function (obj) {
  22821. if (!obj._tags) {
  22822. return null;
  22823. }
  22824. return obj._tags;
  22825. };
  22826. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22827. // a tag cannot start with '||', '&&', and '!'
  22828. // it cannot contain whitespaces
  22829. Tags.AddTagsTo = function (obj, tagsString) {
  22830. if (!tagsString) {
  22831. return;
  22832. }
  22833. var tags = tagsString.split(" ");
  22834. for (var t in tags) {
  22835. Tags._AddTagTo(obj, tags[t]);
  22836. }
  22837. };
  22838. Tags._AddTagTo = function (obj, tag) {
  22839. tag = tag.trim();
  22840. if (tag === "" || tag === "true" || tag === "false") {
  22841. return;
  22842. }
  22843. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22844. return;
  22845. }
  22846. Tags.EnableFor(obj);
  22847. obj._tags[tag] = true;
  22848. };
  22849. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22850. if (!Tags.HasTags(obj)) {
  22851. return;
  22852. }
  22853. var tags = tagsString.split(" ");
  22854. for (var t in tags) {
  22855. Tags._RemoveTagFrom(obj, tags[t]);
  22856. }
  22857. };
  22858. Tags._RemoveTagFrom = function (obj, tag) {
  22859. delete obj._tags[tag];
  22860. };
  22861. Tags.MatchesQuery = function (obj, tagsQuery) {
  22862. if (tagsQuery === undefined) {
  22863. return true;
  22864. }
  22865. if (tagsQuery === "") {
  22866. return Tags.HasTags(obj);
  22867. }
  22868. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22869. };
  22870. return Tags;
  22871. })();
  22872. BABYLON.Tags = Tags;
  22873. })(BABYLON || (BABYLON = {}));
  22874. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22875. (function (BABYLON) {
  22876. var Internals;
  22877. (function (Internals) {
  22878. var AndOrNotEvaluator = (function () {
  22879. function AndOrNotEvaluator() {
  22880. }
  22881. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22882. if (!query.match(/\([^\(\)]*\)/g)) {
  22883. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22884. }
  22885. else {
  22886. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22887. // remove parenthesis
  22888. r = r.slice(1, r.length - 1);
  22889. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22890. });
  22891. }
  22892. if (query === "true") {
  22893. return true;
  22894. }
  22895. if (query === "false") {
  22896. return false;
  22897. }
  22898. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22899. };
  22900. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22901. evaluateCallback = evaluateCallback || (function (r) {
  22902. return r === "true" ? true : false;
  22903. });
  22904. var result;
  22905. var or = parenthesisContent.split("||");
  22906. for (var i in or) {
  22907. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22908. var and = ori.split("&&");
  22909. if (and.length > 1) {
  22910. for (var j = 0; j < and.length; ++j) {
  22911. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22912. if (andj !== "true" && andj !== "false") {
  22913. if (andj[0] === "!") {
  22914. result = !evaluateCallback(andj.substring(1));
  22915. }
  22916. else {
  22917. result = evaluateCallback(andj);
  22918. }
  22919. }
  22920. else {
  22921. result = andj === "true" ? true : false;
  22922. }
  22923. if (!result) {
  22924. ori = "false";
  22925. break;
  22926. }
  22927. }
  22928. }
  22929. if (result || ori === "true") {
  22930. result = true;
  22931. break;
  22932. }
  22933. // result equals false (or undefined)
  22934. if (ori !== "true" && ori !== "false") {
  22935. if (ori[0] === "!") {
  22936. result = !evaluateCallback(ori.substring(1));
  22937. }
  22938. else {
  22939. result = evaluateCallback(ori);
  22940. }
  22941. }
  22942. else {
  22943. result = ori === "true" ? true : false;
  22944. }
  22945. }
  22946. // the whole parenthesis scope is replaced by 'true' or 'false'
  22947. return result ? "true" : "false";
  22948. };
  22949. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22950. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22951. // remove whitespaces
  22952. r = r.replace(/[\s]/g, function () { return ""; });
  22953. return r.length % 2 ? "!" : "";
  22954. });
  22955. booleanString = booleanString.trim();
  22956. if (booleanString === "!true") {
  22957. booleanString = "false";
  22958. }
  22959. else if (booleanString === "!false") {
  22960. booleanString = "true";
  22961. }
  22962. return booleanString;
  22963. };
  22964. return AndOrNotEvaluator;
  22965. })();
  22966. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22967. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22968. })(BABYLON || (BABYLON = {}));
  22969. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22970. (function (BABYLON) {
  22971. var PostProcessRenderPass = (function () {
  22972. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22973. this._enabled = true;
  22974. this._refCount = 0;
  22975. this._name = name;
  22976. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22977. this.setRenderList(renderList);
  22978. this._renderTexture.onBeforeRender = beforeRender;
  22979. this._renderTexture.onAfterRender = afterRender;
  22980. this._scene = scene;
  22981. this._renderList = renderList;
  22982. }
  22983. // private
  22984. PostProcessRenderPass.prototype._incRefCount = function () {
  22985. if (this._refCount === 0) {
  22986. this._scene.customRenderTargets.push(this._renderTexture);
  22987. }
  22988. return ++this._refCount;
  22989. };
  22990. PostProcessRenderPass.prototype._decRefCount = function () {
  22991. this._refCount--;
  22992. if (this._refCount <= 0) {
  22993. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22994. }
  22995. return this._refCount;
  22996. };
  22997. PostProcessRenderPass.prototype._update = function () {
  22998. this.setRenderList(this._renderList);
  22999. };
  23000. // public
  23001. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23002. this._renderTexture.renderList = renderList;
  23003. };
  23004. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23005. return this._renderTexture;
  23006. };
  23007. return PostProcessRenderPass;
  23008. })();
  23009. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23010. })(BABYLON || (BABYLON = {}));
  23011. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23012. (function (BABYLON) {
  23013. var PostProcessRenderEffect = (function () {
  23014. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23015. this._engine = engine;
  23016. this._name = name;
  23017. this._singleInstance = singleInstance || true;
  23018. this._getPostProcess = getPostProcess;
  23019. this._cameras = [];
  23020. this._indicesForCamera = [];
  23021. this._postProcesses = {};
  23022. this._renderPasses = {};
  23023. this._renderEffectAsPasses = {};
  23024. }
  23025. PostProcessRenderEffect.prototype._update = function () {
  23026. for (var renderPassName in this._renderPasses) {
  23027. this._renderPasses[renderPassName]._update();
  23028. }
  23029. };
  23030. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23031. this._renderPasses[renderPass._name] = renderPass;
  23032. this._linkParameters();
  23033. };
  23034. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23035. delete this._renderPasses[renderPass._name];
  23036. this._linkParameters();
  23037. };
  23038. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23039. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23040. this._linkParameters();
  23041. };
  23042. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23043. for (var renderPassName in this._renderPasses) {
  23044. if (renderPassName === passName) {
  23045. return this._renderPasses[passName];
  23046. }
  23047. }
  23048. };
  23049. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23050. this._renderPasses = {};
  23051. this._linkParameters();
  23052. };
  23053. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23054. var cameraKey;
  23055. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23056. for (var i = 0; i < _cam.length; i++) {
  23057. var camera = _cam[i];
  23058. var cameraName = camera.name;
  23059. if (this._singleInstance) {
  23060. cameraKey = 0;
  23061. }
  23062. else {
  23063. cameraKey = cameraName;
  23064. }
  23065. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23066. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23067. if (!this._indicesForCamera[cameraName]) {
  23068. this._indicesForCamera[cameraName] = [];
  23069. }
  23070. this._indicesForCamera[cameraName].push(index);
  23071. if (this._cameras.indexOf(camera) === -1) {
  23072. this._cameras[cameraName] = camera;
  23073. }
  23074. for (var passName in this._renderPasses) {
  23075. this._renderPasses[passName]._incRefCount();
  23076. }
  23077. }
  23078. this._linkParameters();
  23079. };
  23080. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23081. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23082. for (var i = 0; i < _cam.length; i++) {
  23083. var camera = _cam[i];
  23084. var cameraName = camera.name;
  23085. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23086. var index = this._cameras.indexOf(cameraName);
  23087. this._indicesForCamera.splice(index, 1);
  23088. this._cameras.splice(index, 1);
  23089. for (var passName in this._renderPasses) {
  23090. this._renderPasses[passName]._decRefCount();
  23091. }
  23092. }
  23093. };
  23094. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23095. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23096. for (var i = 0; i < _cam.length; i++) {
  23097. var camera = _cam[i];
  23098. var cameraName = camera.name;
  23099. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23100. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23101. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23102. }
  23103. }
  23104. for (var passName in this._renderPasses) {
  23105. this._renderPasses[passName]._incRefCount();
  23106. }
  23107. }
  23108. };
  23109. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23110. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23111. for (var i = 0; i < _cam.length; i++) {
  23112. var camera = _cam[i];
  23113. var cameraName = camera.Name;
  23114. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23115. for (var passName in this._renderPasses) {
  23116. this._renderPasses[passName]._decRefCount();
  23117. }
  23118. }
  23119. };
  23120. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23121. if (this._singleInstance) {
  23122. return this._postProcesses[0];
  23123. }
  23124. else {
  23125. return this._postProcesses[camera.name];
  23126. }
  23127. };
  23128. PostProcessRenderEffect.prototype._linkParameters = function () {
  23129. var _this = this;
  23130. for (var index in this._postProcesses) {
  23131. if (this.applyParameters) {
  23132. this.applyParameters(this._postProcesses[index]);
  23133. }
  23134. this._postProcesses[index].onBeforeRender = function (effect) {
  23135. _this._linkTextures(effect);
  23136. };
  23137. }
  23138. };
  23139. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23140. for (var renderPassName in this._renderPasses) {
  23141. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23142. }
  23143. for (var renderEffectName in this._renderEffectAsPasses) {
  23144. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23145. }
  23146. };
  23147. return PostProcessRenderEffect;
  23148. })();
  23149. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23150. })(BABYLON || (BABYLON = {}));
  23151. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23152. (function (BABYLON) {
  23153. var PostProcessRenderPipeline = (function () {
  23154. function PostProcessRenderPipeline(engine, name) {
  23155. this._engine = engine;
  23156. this._name = name;
  23157. this._renderEffects = {};
  23158. this._renderEffectsForIsolatedPass = {};
  23159. this._cameras = [];
  23160. }
  23161. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23162. this._renderEffects[renderEffect._name] = renderEffect;
  23163. };
  23164. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23165. var renderEffects = this._renderEffects[renderEffectName];
  23166. if (!renderEffects) {
  23167. return;
  23168. }
  23169. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23170. };
  23171. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23172. var renderEffects = this._renderEffects[renderEffectName];
  23173. if (!renderEffects) {
  23174. return;
  23175. }
  23176. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23177. };
  23178. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23179. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23180. var indicesToDelete = [];
  23181. for (var i = 0; i < _cam.length; i++) {
  23182. var camera = _cam[i];
  23183. var cameraName = camera.name;
  23184. if (this._cameras.indexOf(camera) === -1) {
  23185. this._cameras[cameraName] = camera;
  23186. }
  23187. else if (unique) {
  23188. indicesToDelete.push(i);
  23189. }
  23190. }
  23191. for (var i = 0; i < indicesToDelete.length; i++) {
  23192. cameras.splice(indicesToDelete[i], 1);
  23193. }
  23194. for (var renderEffectName in this._renderEffects) {
  23195. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23196. }
  23197. };
  23198. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23199. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23200. for (var renderEffectName in this._renderEffects) {
  23201. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23202. }
  23203. for (var i = 0; i < _cam.length; i++) {
  23204. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23205. }
  23206. };
  23207. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23208. var _this = this;
  23209. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23210. var pass = null;
  23211. for (var renderEffectName in this._renderEffects) {
  23212. pass = this._renderEffects[renderEffectName].getPass(passName);
  23213. if (pass != null) {
  23214. break;
  23215. }
  23216. }
  23217. if (pass === null) {
  23218. return;
  23219. }
  23220. for (var renderEffectName in this._renderEffects) {
  23221. this._renderEffects[renderEffectName]._disable(_cam);
  23222. }
  23223. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23224. for (var i = 0; i < _cam.length; i++) {
  23225. var camera = _cam[i];
  23226. var cameraName = camera.name;
  23227. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23228. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23229. });
  23230. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23231. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23232. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23233. }
  23234. };
  23235. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23236. var _this = this;
  23237. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23238. for (var i = 0; i < _cam.length; i++) {
  23239. var camera = _cam[i];
  23240. var cameraName = camera.name;
  23241. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23242. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23243. });
  23244. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23245. }
  23246. for (var renderEffectName in this._renderEffects) {
  23247. this._renderEffects[renderEffectName]._enable(_cam);
  23248. }
  23249. };
  23250. PostProcessRenderPipeline.prototype._update = function () {
  23251. for (var renderEffectName in this._renderEffects) {
  23252. this._renderEffects[renderEffectName]._update();
  23253. }
  23254. for (var i = 0; i < this._cameras.length; i++) {
  23255. var cameraName = this._cameras[i].name;
  23256. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23257. this._renderEffectsForIsolatedPass[cameraName]._update();
  23258. }
  23259. }
  23260. };
  23261. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23262. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23263. return PostProcessRenderPipeline;
  23264. })();
  23265. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23266. })(BABYLON || (BABYLON = {}));
  23267. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23268. (function (BABYLON) {
  23269. var PostProcessRenderPipelineManager = (function () {
  23270. function PostProcessRenderPipelineManager() {
  23271. this._renderPipelines = {};
  23272. }
  23273. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23274. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23275. };
  23276. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23277. var renderPipeline = this._renderPipelines[renderPipelineName];
  23278. if (!renderPipeline) {
  23279. return;
  23280. }
  23281. renderPipeline._attachCameras(cameras, unique);
  23282. };
  23283. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23284. var renderPipeline = this._renderPipelines[renderPipelineName];
  23285. if (!renderPipeline) {
  23286. return;
  23287. }
  23288. renderPipeline._detachCameras(cameras);
  23289. };
  23290. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23291. var renderPipeline = this._renderPipelines[renderPipelineName];
  23292. if (!renderPipeline) {
  23293. return;
  23294. }
  23295. renderPipeline._enableEffect(renderEffectName, cameras);
  23296. };
  23297. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23298. var renderPipeline = this._renderPipelines[renderPipelineName];
  23299. if (!renderPipeline) {
  23300. return;
  23301. }
  23302. renderPipeline._disableEffect(renderEffectName, cameras);
  23303. };
  23304. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23305. var renderPipeline = this._renderPipelines[renderPipelineName];
  23306. if (!renderPipeline) {
  23307. return;
  23308. }
  23309. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23310. };
  23311. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23312. var renderPipeline = this._renderPipelines[renderPipelineName];
  23313. if (!renderPipeline) {
  23314. return;
  23315. }
  23316. renderPipeline._disableDisplayOnlyPass(cameras);
  23317. };
  23318. PostProcessRenderPipelineManager.prototype.update = function () {
  23319. for (var renderPipelineName in this._renderPipelines) {
  23320. this._renderPipelines[renderPipelineName]._update();
  23321. }
  23322. };
  23323. return PostProcessRenderPipelineManager;
  23324. })();
  23325. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23326. })(BABYLON || (BABYLON = {}));
  23327. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23328. var BABYLON;
  23329. (function (BABYLON) {
  23330. var DisplayPassPostProcess = (function (_super) {
  23331. __extends(DisplayPassPostProcess, _super);
  23332. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23333. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23334. }
  23335. return DisplayPassPostProcess;
  23336. })(BABYLON.PostProcess);
  23337. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23338. })(BABYLON || (BABYLON = {}));
  23339. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23340. (function (BABYLON) {
  23341. var BoundingBoxRenderer = (function () {
  23342. function BoundingBoxRenderer(scene) {
  23343. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23344. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23345. this.showBackLines = true;
  23346. this.renderList = new BABYLON.SmartArray(32);
  23347. this._scene = scene;
  23348. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23349. attributes: ["position"],
  23350. uniforms: ["worldViewProjection", "color"]
  23351. });
  23352. var engine = this._scene.getEngine();
  23353. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23354. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23355. 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]);
  23356. }
  23357. BoundingBoxRenderer.prototype.reset = function () {
  23358. this.renderList.reset();
  23359. };
  23360. BoundingBoxRenderer.prototype.render = function () {
  23361. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  23362. return;
  23363. }
  23364. var engine = this._scene.getEngine();
  23365. engine.setDepthWrite(false);
  23366. this._colorShader._preBind();
  23367. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23368. var boundingBox = this.renderList.data[boundingBoxIndex];
  23369. var min = boundingBox.minimum;
  23370. var max = boundingBox.maximum;
  23371. var diff = max.subtract(min);
  23372. var median = min.add(diff.scale(0.5));
  23373. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23374. // VBOs
  23375. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23376. if (this.showBackLines) {
  23377. // Back
  23378. engine.setDepthFunctionToGreaterOrEqual();
  23379. this._scene.resetCachedMaterial();
  23380. this._colorShader.setColor4("color", this.backColor.toColor4());
  23381. this._colorShader.bind(worldMatrix);
  23382. // Draw order
  23383. engine.draw(false, 0, 24);
  23384. }
  23385. // Front
  23386. engine.setDepthFunctionToLess();
  23387. this._scene.resetCachedMaterial();
  23388. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23389. this._colorShader.bind(worldMatrix);
  23390. // Draw order
  23391. engine.draw(false, 0, 24);
  23392. }
  23393. this._colorShader.unbind();
  23394. engine.setDepthFunctionToLessOrEqual();
  23395. engine.setDepthWrite(true);
  23396. };
  23397. BoundingBoxRenderer.prototype.dispose = function () {
  23398. this._colorShader.dispose();
  23399. this._vb.dispose();
  23400. this._scene.getEngine()._releaseBuffer(this._ib);
  23401. };
  23402. return BoundingBoxRenderer;
  23403. })();
  23404. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23405. })(BABYLON || (BABYLON = {}));
  23406. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23407. (function (BABYLON) {
  23408. var Internals;
  23409. (function (Internals) {
  23410. /*
  23411. * Based on jsTGALoader - Javascript loader for TGA file
  23412. * By Vincent Thibault
  23413. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23414. */
  23415. var TGATools = (function () {
  23416. function TGATools() {
  23417. }
  23418. TGATools.GetTGAHeader = function (data) {
  23419. var offset = 0;
  23420. var header = {
  23421. id_length: data[offset++],
  23422. colormap_type: data[offset++],
  23423. image_type: data[offset++],
  23424. colormap_index: data[offset++] | data[offset++] << 8,
  23425. colormap_length: data[offset++] | data[offset++] << 8,
  23426. colormap_size: data[offset++],
  23427. origin: [
  23428. data[offset++] | data[offset++] << 8,
  23429. data[offset++] | data[offset++] << 8
  23430. ],
  23431. width: data[offset++] | data[offset++] << 8,
  23432. height: data[offset++] | data[offset++] << 8,
  23433. pixel_size: data[offset++],
  23434. flags: data[offset++]
  23435. };
  23436. return header;
  23437. };
  23438. TGATools.UploadContent = function (gl, data) {
  23439. // Not enough data to contain header ?
  23440. if (data.length < 19) {
  23441. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23442. return;
  23443. }
  23444. // Read Header
  23445. var offset = 18;
  23446. var header = TGATools.GetTGAHeader(data);
  23447. // Assume it's a valid Targa file.
  23448. if (header.id_length + offset > data.length) {
  23449. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23450. return;
  23451. }
  23452. // Skip not needed data
  23453. offset += header.id_length;
  23454. var use_rle = false;
  23455. var use_pal = false;
  23456. var use_rgb = false;
  23457. var use_grey = false;
  23458. switch (header.image_type) {
  23459. case TGATools._TYPE_RLE_INDEXED:
  23460. use_rle = true;
  23461. case TGATools._TYPE_INDEXED:
  23462. use_pal = true;
  23463. break;
  23464. case TGATools._TYPE_RLE_RGB:
  23465. use_rle = true;
  23466. case TGATools._TYPE_RGB:
  23467. use_rgb = true;
  23468. break;
  23469. case TGATools._TYPE_RLE_GREY:
  23470. use_rle = true;
  23471. case TGATools._TYPE_GREY:
  23472. use_grey = true;
  23473. break;
  23474. }
  23475. var pixel_data;
  23476. var numAlphaBits = header.flags & 0xf;
  23477. var pixel_size = header.pixel_size >> 3;
  23478. var pixel_total = header.width * header.height * pixel_size;
  23479. // Read palettes
  23480. var palettes;
  23481. if (use_pal) {
  23482. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23483. }
  23484. // Read LRE
  23485. if (use_rle) {
  23486. pixel_data = new Uint8Array(pixel_total);
  23487. var c, count, i;
  23488. var localOffset = 0;
  23489. var pixels = new Uint8Array(pixel_size);
  23490. while (offset < pixel_total && localOffset < pixel_total) {
  23491. c = data[offset++];
  23492. count = (c & 0x7f) + 1;
  23493. // RLE pixels
  23494. if (c & 0x80) {
  23495. for (i = 0; i < pixel_size; ++i) {
  23496. pixels[i] = data[offset++];
  23497. }
  23498. for (i = 0; i < count; ++i) {
  23499. pixel_data.set(pixels, localOffset + i * pixel_size);
  23500. }
  23501. localOffset += pixel_size * count;
  23502. }
  23503. else {
  23504. count *= pixel_size;
  23505. for (i = 0; i < count; ++i) {
  23506. pixel_data[localOffset + i] = data[offset++];
  23507. }
  23508. localOffset += count;
  23509. }
  23510. }
  23511. }
  23512. else {
  23513. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23514. }
  23515. // Load to texture
  23516. var x_start, y_start, x_step, y_step, y_end, x_end;
  23517. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23518. default:
  23519. case TGATools._ORIGIN_UL:
  23520. x_start = 0;
  23521. x_step = 1;
  23522. x_end = header.width;
  23523. y_start = 0;
  23524. y_step = 1;
  23525. y_end = header.height;
  23526. break;
  23527. case TGATools._ORIGIN_BL:
  23528. x_start = 0;
  23529. x_step = 1;
  23530. x_end = header.width;
  23531. y_start = header.height - 1;
  23532. y_step = -1;
  23533. y_end = -1;
  23534. break;
  23535. case TGATools._ORIGIN_UR:
  23536. x_start = header.width - 1;
  23537. x_step = -1;
  23538. x_end = -1;
  23539. y_start = 0;
  23540. y_step = 1;
  23541. y_end = header.height;
  23542. break;
  23543. case TGATools._ORIGIN_BR:
  23544. x_start = header.width - 1;
  23545. x_step = -1;
  23546. x_end = -1;
  23547. y_start = header.height - 1;
  23548. y_step = -1;
  23549. y_end = -1;
  23550. break;
  23551. }
  23552. // Load the specify method
  23553. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23554. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23555. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23556. };
  23557. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23558. var image = pixel_data, colormap = palettes;
  23559. var width = header.width, height = header.height;
  23560. var color, i = 0, x, y;
  23561. var imageData = new Uint8Array(width * height * 4);
  23562. for (y = y_start; y !== y_end; y += y_step) {
  23563. for (x = x_start; x !== x_end; x += x_step, i++) {
  23564. color = image[i];
  23565. imageData[(x + width * y) * 4 + 3] = 255;
  23566. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23567. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23568. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23569. }
  23570. }
  23571. return imageData;
  23572. };
  23573. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23574. var image = pixel_data;
  23575. var width = header.width, height = header.height;
  23576. var color, i = 0, x, y;
  23577. var imageData = new Uint8Array(width * height * 4);
  23578. for (y = y_start; y !== y_end; y += y_step) {
  23579. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23580. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23581. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23582. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23583. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23584. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23585. }
  23586. }
  23587. return imageData;
  23588. };
  23589. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23590. var image = pixel_data;
  23591. var width = header.width, height = header.height;
  23592. var i = 0, x, y;
  23593. var imageData = new Uint8Array(width * height * 4);
  23594. for (y = y_start; y !== y_end; y += y_step) {
  23595. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23596. imageData[(x + width * y) * 4 + 3] = 255;
  23597. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23598. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23599. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23600. }
  23601. }
  23602. return imageData;
  23603. };
  23604. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23605. var image = pixel_data;
  23606. var width = header.width, height = header.height;
  23607. var i = 0, x, y;
  23608. var imageData = new Uint8Array(width * height * 4);
  23609. for (y = y_start; y !== y_end; y += y_step) {
  23610. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23611. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23612. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23613. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23614. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23615. }
  23616. }
  23617. return imageData;
  23618. };
  23619. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23620. var image = pixel_data;
  23621. var width = header.width, height = header.height;
  23622. var color, i = 0, x, y;
  23623. var imageData = new Uint8Array(width * height * 4);
  23624. for (y = y_start; y !== y_end; y += y_step) {
  23625. for (x = x_start; x !== x_end; x += x_step, i++) {
  23626. color = image[i];
  23627. imageData[(x + width * y) * 4 + 0] = color;
  23628. imageData[(x + width * y) * 4 + 1] = color;
  23629. imageData[(x + width * y) * 4 + 2] = color;
  23630. imageData[(x + width * y) * 4 + 3] = 255;
  23631. }
  23632. }
  23633. return imageData;
  23634. };
  23635. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23636. var image = pixel_data;
  23637. var width = header.width, height = header.height;
  23638. var i = 0, x, y;
  23639. var imageData = new Uint8Array(width * height * 4);
  23640. for (y = y_start; y !== y_end; y += y_step) {
  23641. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23642. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23643. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23644. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23645. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23646. }
  23647. }
  23648. return imageData;
  23649. };
  23650. TGATools._TYPE_NO_DATA = 0;
  23651. TGATools._TYPE_INDEXED = 1;
  23652. TGATools._TYPE_RGB = 2;
  23653. TGATools._TYPE_GREY = 3;
  23654. TGATools._TYPE_RLE_INDEXED = 9;
  23655. TGATools._TYPE_RLE_RGB = 10;
  23656. TGATools._TYPE_RLE_GREY = 11;
  23657. TGATools._ORIGIN_MASK = 0x30;
  23658. TGATools._ORIGIN_SHIFT = 0x04;
  23659. TGATools._ORIGIN_BL = 0x00;
  23660. TGATools._ORIGIN_BR = 0x01;
  23661. TGATools._ORIGIN_UL = 0x02;
  23662. TGATools._ORIGIN_UR = 0x03;
  23663. return TGATools;
  23664. })();
  23665. Internals.TGATools = TGATools;
  23666. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23667. })(BABYLON || (BABYLON = {}));
  23668. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23669. (function (BABYLON) {
  23670. var Internals;
  23671. (function (Internals) {
  23672. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23673. // All values and structures referenced from:
  23674. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23675. var DDS_MAGIC = 0x20534444;
  23676. 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;
  23677. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23678. 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;
  23679. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23680. function FourCCToInt32(value) {
  23681. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23682. }
  23683. function Int32ToFourCC(value) {
  23684. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23685. }
  23686. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23687. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23688. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23689. var headerLengthInt = 31; // The header length in 32 bit ints
  23690. // Offsets into the header array
  23691. var off_magic = 0;
  23692. var off_size = 1;
  23693. var off_flags = 2;
  23694. var off_height = 3;
  23695. var off_width = 4;
  23696. var off_mipmapCount = 7;
  23697. var off_pfFlags = 20;
  23698. var off_pfFourCC = 21;
  23699. var off_RGBbpp = 22;
  23700. var off_RMask = 23;
  23701. var off_GMask = 24;
  23702. var off_BMask = 25;
  23703. var off_AMask = 26;
  23704. var off_caps1 = 27;
  23705. var off_caps2 = 28;
  23706. ;
  23707. var DDSTools = (function () {
  23708. function DDSTools() {
  23709. }
  23710. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23711. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23712. var mipmapCount = 1;
  23713. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23714. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23715. }
  23716. return {
  23717. width: header[off_width],
  23718. height: header[off_height],
  23719. mipmapCount: mipmapCount,
  23720. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23721. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23722. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23723. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23724. };
  23725. };
  23726. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23727. var byteArray = new Uint8Array(dataLength);
  23728. var srcData = new Uint8Array(arrayBuffer);
  23729. var index = 0;
  23730. for (var y = height - 1; y >= 0; y--) {
  23731. for (var x = 0; x < width; x++) {
  23732. var srcPos = dataOffset + (x + y * width) * 4;
  23733. byteArray[index + 2] = srcData[srcPos];
  23734. byteArray[index + 1] = srcData[srcPos + 1];
  23735. byteArray[index] = srcData[srcPos + 2];
  23736. byteArray[index + 3] = srcData[srcPos + 3];
  23737. index += 4;
  23738. }
  23739. }
  23740. return byteArray;
  23741. };
  23742. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23743. var byteArray = new Uint8Array(dataLength);
  23744. var srcData = new Uint8Array(arrayBuffer);
  23745. var index = 0;
  23746. for (var y = height - 1; y >= 0; y--) {
  23747. for (var x = 0; x < width; x++) {
  23748. var srcPos = dataOffset + (x + y * width) * 3;
  23749. byteArray[index + 2] = srcData[srcPos];
  23750. byteArray[index + 1] = srcData[srcPos + 1];
  23751. byteArray[index] = srcData[srcPos + 2];
  23752. index += 3;
  23753. }
  23754. }
  23755. return byteArray;
  23756. };
  23757. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23758. var byteArray = new Uint8Array(dataLength);
  23759. var srcData = new Uint8Array(arrayBuffer);
  23760. var index = 0;
  23761. for (var y = height - 1; y >= 0; y--) {
  23762. for (var x = 0; x < width; x++) {
  23763. var srcPos = dataOffset + (x + y * width);
  23764. byteArray[index] = srcData[srcPos];
  23765. index++;
  23766. }
  23767. }
  23768. return byteArray;
  23769. };
  23770. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23771. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23772. if (header[off_magic] != DDS_MAGIC) {
  23773. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23774. return;
  23775. }
  23776. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23777. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23778. return;
  23779. }
  23780. if (info.isFourCC) {
  23781. fourCC = header[off_pfFourCC];
  23782. switch (fourCC) {
  23783. case FOURCC_DXT1:
  23784. blockBytes = 8;
  23785. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23786. break;
  23787. case FOURCC_DXT3:
  23788. blockBytes = 16;
  23789. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23790. break;
  23791. case FOURCC_DXT5:
  23792. blockBytes = 16;
  23793. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23794. break;
  23795. default:
  23796. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23797. return;
  23798. }
  23799. }
  23800. mipmapCount = 1;
  23801. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23802. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23803. }
  23804. var bpp = header[off_RGBbpp];
  23805. for (var face = 0; face < faces; face++) {
  23806. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23807. width = header[off_width];
  23808. height = header[off_height];
  23809. dataOffset = header[off_size] + 4;
  23810. for (i = 0; i < mipmapCount; ++i) {
  23811. if (info.isRGB) {
  23812. if (bpp == 24) {
  23813. dataLength = width * height * 3;
  23814. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23815. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23816. }
  23817. else {
  23818. dataLength = width * height * 4;
  23819. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23820. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23821. }
  23822. }
  23823. else if (info.isLuminance) {
  23824. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23825. var unpaddedRowSize = width;
  23826. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23827. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23828. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23829. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23830. }
  23831. else {
  23832. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23833. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23834. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23835. }
  23836. dataOffset += dataLength;
  23837. width *= 0.5;
  23838. height *= 0.5;
  23839. width = Math.max(1.0, width);
  23840. height = Math.max(1.0, height);
  23841. }
  23842. }
  23843. };
  23844. return DDSTools;
  23845. })();
  23846. Internals.DDSTools = DDSTools;
  23847. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23848. })(BABYLON || (BABYLON = {}));
  23849. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23850. (function (BABYLON) {
  23851. var SmartArray = (function () {
  23852. function SmartArray(capacity) {
  23853. this.length = 0;
  23854. this._duplicateId = 0;
  23855. this.data = new Array(capacity);
  23856. this._id = SmartArray._GlobalId++;
  23857. }
  23858. SmartArray.prototype.push = function (value) {
  23859. this.data[this.length++] = value;
  23860. if (this.length > this.data.length) {
  23861. this.data.length *= 2;
  23862. }
  23863. if (!value.__smartArrayFlags) {
  23864. value.__smartArrayFlags = {};
  23865. }
  23866. value.__smartArrayFlags[this._id] = this._duplicateId;
  23867. };
  23868. SmartArray.prototype.pushNoDuplicate = function (value) {
  23869. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23870. return;
  23871. }
  23872. this.push(value);
  23873. };
  23874. SmartArray.prototype.sort = function (compareFn) {
  23875. this.data.sort(compareFn);
  23876. };
  23877. SmartArray.prototype.reset = function () {
  23878. this.length = 0;
  23879. this._duplicateId++;
  23880. };
  23881. SmartArray.prototype.concat = function (array) {
  23882. if (array.length === 0) {
  23883. return;
  23884. }
  23885. if (this.length + array.length > this.data.length) {
  23886. this.data.length = (this.length + array.length) * 2;
  23887. }
  23888. for (var index = 0; index < array.length; index++) {
  23889. this.data[this.length++] = (array.data || array)[index];
  23890. }
  23891. };
  23892. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23893. if (array.length === 0) {
  23894. return;
  23895. }
  23896. if (this.length + array.length > this.data.length) {
  23897. this.data.length = (this.length + array.length) * 2;
  23898. }
  23899. for (var index = 0; index < array.length; index++) {
  23900. var item = (array.data || array)[index];
  23901. this.pushNoDuplicate(item);
  23902. }
  23903. };
  23904. SmartArray.prototype.indexOf = function (value) {
  23905. var position = this.data.indexOf(value);
  23906. if (position >= this.length) {
  23907. return -1;
  23908. }
  23909. return position;
  23910. };
  23911. // Statics
  23912. SmartArray._GlobalId = 0;
  23913. return SmartArray;
  23914. })();
  23915. BABYLON.SmartArray = SmartArray;
  23916. })(BABYLON || (BABYLON = {}));
  23917. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23918. (function (BABYLON) {
  23919. var CannonJSPlugin = (function () {
  23920. function CannonJSPlugin() {
  23921. this._registeredMeshes = [];
  23922. this._physicsMaterials = [];
  23923. this.updateBodyPosition = function (mesh) {
  23924. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23925. var registeredMesh = this._registeredMeshes[index];
  23926. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23927. var body = registeredMesh.body;
  23928. var center = mesh.getBoundingInfo().boundingBox.center;
  23929. body.position.set(center.x, center.z, center.y);
  23930. body.quaternion.x = mesh.rotationQuaternion.x;
  23931. body.quaternion.z = mesh.rotationQuaternion.y;
  23932. body.quaternion.y = mesh.rotationQuaternion.z;
  23933. body.quaternion.w = -mesh.rotationQuaternion.w;
  23934. return;
  23935. }
  23936. }
  23937. };
  23938. }
  23939. CannonJSPlugin.prototype.initialize = function (iterations) {
  23940. if (iterations === void 0) { iterations = 10; }
  23941. this._world = new CANNON.World();
  23942. this._world.broadphase = new CANNON.NaiveBroadphase();
  23943. this._world.solver.iterations = iterations;
  23944. };
  23945. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23946. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23947. };
  23948. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23949. this._world.step(delta);
  23950. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23951. var registeredMesh = this._registeredMeshes[index];
  23952. if (registeredMesh.isChild) {
  23953. continue;
  23954. }
  23955. // Body position
  23956. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23957. var deltaPos = registeredMesh.delta;
  23958. if (deltaPos) {
  23959. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23960. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23961. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23962. }
  23963. else {
  23964. registeredMesh.mesh.position.x = bodyX;
  23965. registeredMesh.mesh.position.y = bodyZ;
  23966. registeredMesh.mesh.position.z = bodyY;
  23967. }
  23968. if (!registeredMesh.mesh.rotationQuaternion) {
  23969. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23970. }
  23971. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23972. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23973. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23974. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23975. }
  23976. };
  23977. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23978. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23979. };
  23980. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23981. this.unregisterMesh(mesh);
  23982. mesh.computeWorldMatrix(true);
  23983. switch (impostor) {
  23984. case BABYLON.PhysicsEngine.SphereImpostor:
  23985. var bbox = mesh.getBoundingInfo().boundingBox;
  23986. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23987. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23988. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23989. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23990. case BABYLON.PhysicsEngine.BoxImpostor:
  23991. bbox = mesh.getBoundingInfo().boundingBox;
  23992. var min = bbox.minimumWorld;
  23993. var max = bbox.maximumWorld;
  23994. var box = max.subtract(min).scale(0.5);
  23995. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23996. case BABYLON.PhysicsEngine.PlaneImpostor:
  23997. return this._createPlane(mesh, options);
  23998. case BABYLON.PhysicsEngine.MeshImpostor:
  23999. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24000. var rawFaces = mesh.getIndices();
  24001. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24002. }
  24003. return null;
  24004. };
  24005. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24006. var shape = new CANNON.Sphere(radius);
  24007. if (!options) {
  24008. return shape;
  24009. }
  24010. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24011. };
  24012. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24013. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24014. if (!options) {
  24015. return shape;
  24016. }
  24017. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24018. };
  24019. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24020. var shape = new CANNON.Plane();
  24021. if (!options) {
  24022. return shape;
  24023. }
  24024. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24025. };
  24026. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24027. var verts = [], faces = [];
  24028. mesh.computeWorldMatrix(true);
  24029. for (var i = 0; i < rawVerts.length; i += 3) {
  24030. var transformed = BABYLON.Vector3.Zero();
  24031. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24032. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24033. }
  24034. for (var j = 0; j < rawFaces.length; j += 3) {
  24035. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24036. }
  24037. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24038. if (!options) {
  24039. return shape;
  24040. }
  24041. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24042. };
  24043. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24044. var index;
  24045. var mat;
  24046. for (index = 0; index < this._physicsMaterials.length; index++) {
  24047. mat = this._physicsMaterials[index];
  24048. if (mat.friction === friction && mat.restitution === restitution) {
  24049. return mat;
  24050. }
  24051. }
  24052. var currentMat = new CANNON.Material();
  24053. currentMat.friction = friction;
  24054. currentMat.restitution = restitution;
  24055. this._physicsMaterials.push(currentMat);
  24056. for (index = 0; index < this._physicsMaterials.length; index++) {
  24057. mat = this._physicsMaterials[index];
  24058. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24059. contactMaterial.contactEquationStiffness = 1e10;
  24060. contactMaterial.contactEquationRegularizationTime = 10;
  24061. this._world.addContactMaterial(contactMaterial);
  24062. }
  24063. return currentMat;
  24064. };
  24065. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24066. var initialRotation = null;
  24067. if (mesh.rotationQuaternion) {
  24068. initialRotation = mesh.rotationQuaternion.clone();
  24069. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24070. }
  24071. // The delta between the mesh position and the mesh bounding box center
  24072. var bbox = mesh.getBoundingInfo().boundingBox;
  24073. var deltaPosition = mesh.position.subtract(bbox.center);
  24074. var material = this._addMaterial(friction, restitution);
  24075. var body = new CANNON.RigidBody(mass, shape, material);
  24076. if (initialRotation) {
  24077. body.quaternion.x = initialRotation.x;
  24078. body.quaternion.z = initialRotation.y;
  24079. body.quaternion.y = initialRotation.z;
  24080. body.quaternion.w = -initialRotation.w;
  24081. }
  24082. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24083. this._world.add(body);
  24084. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24085. return body;
  24086. };
  24087. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24088. var compoundShape = new CANNON.Compound();
  24089. for (var index = 0; index < parts.length; index++) {
  24090. var mesh = parts[index].mesh;
  24091. var shape = this.registerMesh(mesh, parts[index].impostor);
  24092. if (index == 0) {
  24093. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24094. }
  24095. else {
  24096. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24097. }
  24098. }
  24099. var initialMesh = parts[0].mesh;
  24100. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24101. body.parts = parts;
  24102. return body;
  24103. };
  24104. CannonJSPlugin.prototype._unbindBody = function (body) {
  24105. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24106. var registeredMesh = this._registeredMeshes[index];
  24107. if (registeredMesh.body === body) {
  24108. registeredMesh.body = null;
  24109. registeredMesh.delta = 0;
  24110. }
  24111. }
  24112. };
  24113. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24114. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24115. var registeredMesh = this._registeredMeshes[index];
  24116. if (registeredMesh.mesh === mesh) {
  24117. // Remove body
  24118. if (registeredMesh.body) {
  24119. this._world.remove(registeredMesh.body);
  24120. this._unbindBody(registeredMesh.body);
  24121. }
  24122. this._registeredMeshes.splice(index, 1);
  24123. return;
  24124. }
  24125. }
  24126. };
  24127. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24128. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24129. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24130. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24131. var registeredMesh = this._registeredMeshes[index];
  24132. if (registeredMesh.mesh === mesh) {
  24133. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24134. return;
  24135. }
  24136. }
  24137. };
  24138. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24139. var body1 = null, body2 = null;
  24140. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24141. var registeredMesh = this._registeredMeshes[index];
  24142. if (registeredMesh.mesh === mesh1) {
  24143. body1 = registeredMesh.body;
  24144. }
  24145. else if (registeredMesh.mesh === mesh2) {
  24146. body2 = registeredMesh.body;
  24147. }
  24148. }
  24149. if (!body1 || !body2) {
  24150. return false;
  24151. }
  24152. 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));
  24153. this._world.addConstraint(constraint);
  24154. return true;
  24155. };
  24156. CannonJSPlugin.prototype.dispose = function () {
  24157. while (this._registeredMeshes.length) {
  24158. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24159. }
  24160. };
  24161. CannonJSPlugin.prototype.isSupported = function () {
  24162. return window.CANNON !== undefined;
  24163. };
  24164. return CannonJSPlugin;
  24165. })();
  24166. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24167. })(BABYLON || (BABYLON = {}));
  24168. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24169. var BABYLON;
  24170. (function (BABYLON) {
  24171. var Condition = (function () {
  24172. function Condition(actionManager) {
  24173. this._actionManager = actionManager;
  24174. }
  24175. Condition.prototype.isValid = function () {
  24176. return true;
  24177. };
  24178. Condition.prototype._getProperty = function (propertyPath) {
  24179. return this._actionManager._getProperty(propertyPath);
  24180. };
  24181. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24182. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24183. };
  24184. return Condition;
  24185. })();
  24186. BABYLON.Condition = Condition;
  24187. var ValueCondition = (function (_super) {
  24188. __extends(ValueCondition, _super);
  24189. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24190. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24191. _super.call(this, actionManager);
  24192. this.propertyPath = propertyPath;
  24193. this.value = value;
  24194. this.operator = operator;
  24195. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24196. this._property = this._getProperty(this.propertyPath);
  24197. }
  24198. Object.defineProperty(ValueCondition, "IsEqual", {
  24199. get: function () {
  24200. return ValueCondition._IsEqual;
  24201. },
  24202. enumerable: true,
  24203. configurable: true
  24204. });
  24205. Object.defineProperty(ValueCondition, "IsDifferent", {
  24206. get: function () {
  24207. return ValueCondition._IsDifferent;
  24208. },
  24209. enumerable: true,
  24210. configurable: true
  24211. });
  24212. Object.defineProperty(ValueCondition, "IsGreater", {
  24213. get: function () {
  24214. return ValueCondition._IsGreater;
  24215. },
  24216. enumerable: true,
  24217. configurable: true
  24218. });
  24219. Object.defineProperty(ValueCondition, "IsLesser", {
  24220. get: function () {
  24221. return ValueCondition._IsLesser;
  24222. },
  24223. enumerable: true,
  24224. configurable: true
  24225. });
  24226. // Methods
  24227. ValueCondition.prototype.isValid = function () {
  24228. switch (this.operator) {
  24229. case ValueCondition.IsGreater:
  24230. return this._target[this._property] > this.value;
  24231. case ValueCondition.IsLesser:
  24232. return this._target[this._property] < this.value;
  24233. case ValueCondition.IsEqual:
  24234. case ValueCondition.IsDifferent:
  24235. var check;
  24236. if (this.value.equals) {
  24237. check = this.value.equals(this._target[this._property]);
  24238. }
  24239. else {
  24240. check = this.value === this._target[this._property];
  24241. }
  24242. return this.operator === ValueCondition.IsEqual ? check : !check;
  24243. }
  24244. return false;
  24245. };
  24246. // Statics
  24247. ValueCondition._IsEqual = 0;
  24248. ValueCondition._IsDifferent = 1;
  24249. ValueCondition._IsGreater = 2;
  24250. ValueCondition._IsLesser = 3;
  24251. return ValueCondition;
  24252. })(Condition);
  24253. BABYLON.ValueCondition = ValueCondition;
  24254. var PredicateCondition = (function (_super) {
  24255. __extends(PredicateCondition, _super);
  24256. function PredicateCondition(actionManager, predicate) {
  24257. _super.call(this, actionManager);
  24258. this.predicate = predicate;
  24259. }
  24260. PredicateCondition.prototype.isValid = function () {
  24261. return this.predicate();
  24262. };
  24263. return PredicateCondition;
  24264. })(Condition);
  24265. BABYLON.PredicateCondition = PredicateCondition;
  24266. var StateCondition = (function (_super) {
  24267. __extends(StateCondition, _super);
  24268. function StateCondition(actionManager, target, value) {
  24269. _super.call(this, actionManager);
  24270. this.value = value;
  24271. this._target = target;
  24272. }
  24273. // Methods
  24274. StateCondition.prototype.isValid = function () {
  24275. return this._target.state === this.value;
  24276. };
  24277. return StateCondition;
  24278. })(Condition);
  24279. BABYLON.StateCondition = StateCondition;
  24280. })(BABYLON || (BABYLON = {}));
  24281. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24282. (function (BABYLON) {
  24283. var Action = (function () {
  24284. function Action(triggerOptions, condition) {
  24285. this.triggerOptions = triggerOptions;
  24286. if (triggerOptions.parameter) {
  24287. this.trigger = triggerOptions.trigger;
  24288. this._triggerParameter = triggerOptions.parameter;
  24289. }
  24290. else {
  24291. this.trigger = triggerOptions;
  24292. }
  24293. this._nextActiveAction = this;
  24294. this._condition = condition;
  24295. }
  24296. // Methods
  24297. Action.prototype._prepare = function () {
  24298. };
  24299. Action.prototype.getTriggerParameter = function () {
  24300. return this._triggerParameter;
  24301. };
  24302. Action.prototype._executeCurrent = function (evt) {
  24303. if (this._nextActiveAction._condition) {
  24304. var condition = this._nextActiveAction._condition;
  24305. var currentRenderId = this._actionManager.getScene().getRenderId();
  24306. // We cache the current evaluation for the current frame
  24307. if (condition._evaluationId === currentRenderId) {
  24308. if (!condition._currentResult) {
  24309. return;
  24310. }
  24311. }
  24312. else {
  24313. condition._evaluationId = currentRenderId;
  24314. if (!condition.isValid()) {
  24315. condition._currentResult = false;
  24316. return;
  24317. }
  24318. condition._currentResult = true;
  24319. }
  24320. }
  24321. this._nextActiveAction.execute(evt);
  24322. if (this._nextActiveAction._child) {
  24323. if (!this._nextActiveAction._child._actionManager) {
  24324. this._nextActiveAction._child._actionManager = this._actionManager;
  24325. }
  24326. this._nextActiveAction = this._nextActiveAction._child;
  24327. }
  24328. else {
  24329. this._nextActiveAction = this;
  24330. }
  24331. };
  24332. Action.prototype.execute = function (evt) {
  24333. };
  24334. Action.prototype.then = function (action) {
  24335. this._child = action;
  24336. action._actionManager = this._actionManager;
  24337. action._prepare();
  24338. return action;
  24339. };
  24340. Action.prototype._getProperty = function (propertyPath) {
  24341. return this._actionManager._getProperty(propertyPath);
  24342. };
  24343. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24344. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24345. };
  24346. return Action;
  24347. })();
  24348. BABYLON.Action = Action;
  24349. })(BABYLON || (BABYLON = {}));
  24350. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24351. (function (BABYLON) {
  24352. /**
  24353. * ActionEvent is the event beint sent when an action is triggered.
  24354. */
  24355. var ActionEvent = (function () {
  24356. /**
  24357. * @constructor
  24358. * @param source The mesh that triggered the action.
  24359. * @param pointerX the X mouse cursor position at the time of the event
  24360. * @param pointerY the Y mouse cursor position at the time of the event
  24361. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24362. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24363. */
  24364. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24365. this.source = source;
  24366. this.pointerX = pointerX;
  24367. this.pointerY = pointerY;
  24368. this.meshUnderPointer = meshUnderPointer;
  24369. this.sourceEvent = sourceEvent;
  24370. }
  24371. /**
  24372. * Helper function to auto-create an ActionEvent from a source mesh.
  24373. * @param source the source mesh that triggered the event
  24374. * @param evt {Event} The original (browser) event
  24375. */
  24376. ActionEvent.CreateNew = function (source, evt) {
  24377. var scene = source.getScene();
  24378. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24379. };
  24380. /**
  24381. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24382. * @param scene the scene where the event occurred
  24383. * @param evt {Event} The original (browser) event
  24384. */
  24385. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24386. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24387. };
  24388. return ActionEvent;
  24389. })();
  24390. BABYLON.ActionEvent = ActionEvent;
  24391. /**
  24392. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24393. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24394. */
  24395. var ActionManager = (function () {
  24396. function ActionManager(scene) {
  24397. // Members
  24398. this.actions = new Array();
  24399. this._scene = scene;
  24400. scene._actionManagers.push(this);
  24401. }
  24402. Object.defineProperty(ActionManager, "NothingTrigger", {
  24403. get: function () {
  24404. return ActionManager._NothingTrigger;
  24405. },
  24406. enumerable: true,
  24407. configurable: true
  24408. });
  24409. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24410. get: function () {
  24411. return ActionManager._OnPickTrigger;
  24412. },
  24413. enumerable: true,
  24414. configurable: true
  24415. });
  24416. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24417. get: function () {
  24418. return ActionManager._OnLeftPickTrigger;
  24419. },
  24420. enumerable: true,
  24421. configurable: true
  24422. });
  24423. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24424. get: function () {
  24425. return ActionManager._OnRightPickTrigger;
  24426. },
  24427. enumerable: true,
  24428. configurable: true
  24429. });
  24430. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24431. get: function () {
  24432. return ActionManager._OnCenterPickTrigger;
  24433. },
  24434. enumerable: true,
  24435. configurable: true
  24436. });
  24437. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24438. get: function () {
  24439. return ActionManager._OnPointerOverTrigger;
  24440. },
  24441. enumerable: true,
  24442. configurable: true
  24443. });
  24444. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24445. get: function () {
  24446. return ActionManager._OnPointerOutTrigger;
  24447. },
  24448. enumerable: true,
  24449. configurable: true
  24450. });
  24451. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24452. get: function () {
  24453. return ActionManager._OnEveryFrameTrigger;
  24454. },
  24455. enumerable: true,
  24456. configurable: true
  24457. });
  24458. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24459. get: function () {
  24460. return ActionManager._OnIntersectionEnterTrigger;
  24461. },
  24462. enumerable: true,
  24463. configurable: true
  24464. });
  24465. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24466. get: function () {
  24467. return ActionManager._OnIntersectionExitTrigger;
  24468. },
  24469. enumerable: true,
  24470. configurable: true
  24471. });
  24472. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24473. get: function () {
  24474. return ActionManager._OnKeyDownTrigger;
  24475. },
  24476. enumerable: true,
  24477. configurable: true
  24478. });
  24479. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24480. get: function () {
  24481. return ActionManager._OnKeyUpTrigger;
  24482. },
  24483. enumerable: true,
  24484. configurable: true
  24485. });
  24486. // Methods
  24487. ActionManager.prototype.dispose = function () {
  24488. var index = this._scene._actionManagers.indexOf(this);
  24489. if (index > -1) {
  24490. this._scene._actionManagers.splice(index, 1);
  24491. }
  24492. };
  24493. ActionManager.prototype.getScene = function () {
  24494. return this._scene;
  24495. };
  24496. /**
  24497. * Does this action manager handles actions of any of the given triggers
  24498. * @param {number[]} triggers - the triggers to be tested
  24499. * @return {boolean} whether one (or more) of the triggers is handeled
  24500. */
  24501. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24502. for (var index = 0; index < this.actions.length; index++) {
  24503. var action = this.actions[index];
  24504. if (triggers.indexOf(action.trigger) > -1) {
  24505. return true;
  24506. }
  24507. }
  24508. return false;
  24509. };
  24510. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24511. /**
  24512. * Does this action manager has pointer triggers
  24513. * @return {boolean} whether or not it has pointer triggers
  24514. */
  24515. get: function () {
  24516. for (var index = 0; index < this.actions.length; index++) {
  24517. var action = this.actions[index];
  24518. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24519. return true;
  24520. }
  24521. }
  24522. return false;
  24523. },
  24524. enumerable: true,
  24525. configurable: true
  24526. });
  24527. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24528. /**
  24529. * Does this action manager has pick triggers
  24530. * @return {boolean} whether or not it has pick triggers
  24531. */
  24532. get: function () {
  24533. for (var index = 0; index < this.actions.length; index++) {
  24534. var action = this.actions[index];
  24535. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24536. return true;
  24537. }
  24538. }
  24539. return false;
  24540. },
  24541. enumerable: true,
  24542. configurable: true
  24543. });
  24544. /**
  24545. * Registers an action to this action manager
  24546. * @param {BABYLON.Action} action - the action to be registered
  24547. * @return {BABYLON.Action} the action amended (prepared) after registration
  24548. */
  24549. ActionManager.prototype.registerAction = function (action) {
  24550. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24551. if (this.getScene().actionManager !== this) {
  24552. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24553. return null;
  24554. }
  24555. }
  24556. this.actions.push(action);
  24557. action._actionManager = this;
  24558. action._prepare();
  24559. return action;
  24560. };
  24561. /**
  24562. * Process a specific trigger
  24563. * @param {number} trigger - the trigger to process
  24564. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24565. */
  24566. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24567. for (var index = 0; index < this.actions.length; index++) {
  24568. var action = this.actions[index];
  24569. if (action.trigger === trigger) {
  24570. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24571. var parameter = action.getTriggerParameter();
  24572. if (parameter) {
  24573. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24574. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24575. if (actualkey !== parameter.toLowerCase()) {
  24576. continue;
  24577. }
  24578. }
  24579. }
  24580. action._executeCurrent(evt);
  24581. }
  24582. }
  24583. };
  24584. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24585. var properties = propertyPath.split(".");
  24586. for (var index = 0; index < properties.length - 1; index++) {
  24587. target = target[properties[index]];
  24588. }
  24589. return target;
  24590. };
  24591. ActionManager.prototype._getProperty = function (propertyPath) {
  24592. var properties = propertyPath.split(".");
  24593. return properties[properties.length - 1];
  24594. };
  24595. // Statics
  24596. ActionManager._NothingTrigger = 0;
  24597. ActionManager._OnPickTrigger = 1;
  24598. ActionManager._OnLeftPickTrigger = 2;
  24599. ActionManager._OnRightPickTrigger = 3;
  24600. ActionManager._OnCenterPickTrigger = 4;
  24601. ActionManager._OnPointerOverTrigger = 5;
  24602. ActionManager._OnPointerOutTrigger = 6;
  24603. ActionManager._OnEveryFrameTrigger = 7;
  24604. ActionManager._OnIntersectionEnterTrigger = 8;
  24605. ActionManager._OnIntersectionExitTrigger = 9;
  24606. ActionManager._OnKeyDownTrigger = 10;
  24607. ActionManager._OnKeyUpTrigger = 11;
  24608. return ActionManager;
  24609. })();
  24610. BABYLON.ActionManager = ActionManager;
  24611. })(BABYLON || (BABYLON = {}));
  24612. //# sourceMappingURL=babylon.actionManager.js.map
  24613. var BABYLON;
  24614. (function (BABYLON) {
  24615. var InterpolateValueAction = (function (_super) {
  24616. __extends(InterpolateValueAction, _super);
  24617. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24618. if (duration === void 0) { duration = 1000; }
  24619. _super.call(this, triggerOptions, condition);
  24620. this.propertyPath = propertyPath;
  24621. this.value = value;
  24622. this.duration = duration;
  24623. this.stopOtherAnimations = stopOtherAnimations;
  24624. this._target = target;
  24625. }
  24626. InterpolateValueAction.prototype._prepare = function () {
  24627. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24628. this._property = this._getProperty(this.propertyPath);
  24629. };
  24630. InterpolateValueAction.prototype.execute = function () {
  24631. var scene = this._actionManager.getScene();
  24632. var keys = [
  24633. {
  24634. frame: 0,
  24635. value: this._target[this._property]
  24636. },
  24637. {
  24638. frame: 100,
  24639. value: this.value
  24640. }
  24641. ];
  24642. var dataType;
  24643. if (typeof this.value === "number") {
  24644. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24645. }
  24646. else if (this.value instanceof BABYLON.Color3) {
  24647. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24648. }
  24649. else if (this.value instanceof BABYLON.Vector3) {
  24650. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24651. }
  24652. else if (this.value instanceof BABYLON.Matrix) {
  24653. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24654. }
  24655. else if (this.value instanceof BABYLON.Quaternion) {
  24656. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24657. }
  24658. else {
  24659. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24660. return;
  24661. }
  24662. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24663. animation.setKeys(keys);
  24664. if (this.stopOtherAnimations) {
  24665. scene.stopAnimation(this._target);
  24666. }
  24667. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24668. };
  24669. return InterpolateValueAction;
  24670. })(BABYLON.Action);
  24671. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24672. })(BABYLON || (BABYLON = {}));
  24673. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24674. var BABYLON;
  24675. (function (BABYLON) {
  24676. var SwitchBooleanAction = (function (_super) {
  24677. __extends(SwitchBooleanAction, _super);
  24678. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24679. _super.call(this, triggerOptions, condition);
  24680. this.propertyPath = propertyPath;
  24681. this._target = target;
  24682. }
  24683. SwitchBooleanAction.prototype._prepare = function () {
  24684. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24685. this._property = this._getProperty(this.propertyPath);
  24686. };
  24687. SwitchBooleanAction.prototype.execute = function () {
  24688. this._target[this._property] = !this._target[this._property];
  24689. };
  24690. return SwitchBooleanAction;
  24691. })(BABYLON.Action);
  24692. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24693. var SetStateAction = (function (_super) {
  24694. __extends(SetStateAction, _super);
  24695. function SetStateAction(triggerOptions, target, value, condition) {
  24696. _super.call(this, triggerOptions, condition);
  24697. this.value = value;
  24698. this._target = target;
  24699. }
  24700. SetStateAction.prototype.execute = function () {
  24701. this._target.state = this.value;
  24702. };
  24703. return SetStateAction;
  24704. })(BABYLON.Action);
  24705. BABYLON.SetStateAction = SetStateAction;
  24706. var SetValueAction = (function (_super) {
  24707. __extends(SetValueAction, _super);
  24708. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24709. _super.call(this, triggerOptions, condition);
  24710. this.propertyPath = propertyPath;
  24711. this.value = value;
  24712. this._target = target;
  24713. }
  24714. SetValueAction.prototype._prepare = function () {
  24715. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24716. this._property = this._getProperty(this.propertyPath);
  24717. };
  24718. SetValueAction.prototype.execute = function () {
  24719. this._target[this._property] = this.value;
  24720. };
  24721. return SetValueAction;
  24722. })(BABYLON.Action);
  24723. BABYLON.SetValueAction = SetValueAction;
  24724. var IncrementValueAction = (function (_super) {
  24725. __extends(IncrementValueAction, _super);
  24726. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24727. _super.call(this, triggerOptions, condition);
  24728. this.propertyPath = propertyPath;
  24729. this.value = value;
  24730. this._target = target;
  24731. }
  24732. IncrementValueAction.prototype._prepare = function () {
  24733. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24734. this._property = this._getProperty(this.propertyPath);
  24735. if (typeof this._target[this._property] !== "number") {
  24736. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24737. }
  24738. };
  24739. IncrementValueAction.prototype.execute = function () {
  24740. this._target[this._property] += this.value;
  24741. };
  24742. return IncrementValueAction;
  24743. })(BABYLON.Action);
  24744. BABYLON.IncrementValueAction = IncrementValueAction;
  24745. var PlayAnimationAction = (function (_super) {
  24746. __extends(PlayAnimationAction, _super);
  24747. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24748. _super.call(this, triggerOptions, condition);
  24749. this.from = from;
  24750. this.to = to;
  24751. this.loop = loop;
  24752. this._target = target;
  24753. }
  24754. PlayAnimationAction.prototype._prepare = function () {
  24755. };
  24756. PlayAnimationAction.prototype.execute = function () {
  24757. var scene = this._actionManager.getScene();
  24758. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24759. };
  24760. return PlayAnimationAction;
  24761. })(BABYLON.Action);
  24762. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24763. var StopAnimationAction = (function (_super) {
  24764. __extends(StopAnimationAction, _super);
  24765. function StopAnimationAction(triggerOptions, target, condition) {
  24766. _super.call(this, triggerOptions, condition);
  24767. this._target = target;
  24768. }
  24769. StopAnimationAction.prototype._prepare = function () {
  24770. };
  24771. StopAnimationAction.prototype.execute = function () {
  24772. var scene = this._actionManager.getScene();
  24773. scene.stopAnimation(this._target);
  24774. };
  24775. return StopAnimationAction;
  24776. })(BABYLON.Action);
  24777. BABYLON.StopAnimationAction = StopAnimationAction;
  24778. var DoNothingAction = (function (_super) {
  24779. __extends(DoNothingAction, _super);
  24780. function DoNothingAction(triggerOptions, condition) {
  24781. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24782. _super.call(this, triggerOptions, condition);
  24783. }
  24784. DoNothingAction.prototype.execute = function () {
  24785. };
  24786. return DoNothingAction;
  24787. })(BABYLON.Action);
  24788. BABYLON.DoNothingAction = DoNothingAction;
  24789. var CombineAction = (function (_super) {
  24790. __extends(CombineAction, _super);
  24791. function CombineAction(triggerOptions, children, condition) {
  24792. _super.call(this, triggerOptions, condition);
  24793. this.children = children;
  24794. }
  24795. CombineAction.prototype._prepare = function () {
  24796. for (var index = 0; index < this.children.length; index++) {
  24797. this.children[index]._actionManager = this._actionManager;
  24798. this.children[index]._prepare();
  24799. }
  24800. };
  24801. CombineAction.prototype.execute = function (evt) {
  24802. for (var index = 0; index < this.children.length; index++) {
  24803. this.children[index].execute(evt);
  24804. }
  24805. };
  24806. return CombineAction;
  24807. })(BABYLON.Action);
  24808. BABYLON.CombineAction = CombineAction;
  24809. var ExecuteCodeAction = (function (_super) {
  24810. __extends(ExecuteCodeAction, _super);
  24811. function ExecuteCodeAction(triggerOptions, func, condition) {
  24812. _super.call(this, triggerOptions, condition);
  24813. this.func = func;
  24814. }
  24815. ExecuteCodeAction.prototype.execute = function (evt) {
  24816. this.func(evt);
  24817. };
  24818. return ExecuteCodeAction;
  24819. })(BABYLON.Action);
  24820. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24821. var SetParentAction = (function (_super) {
  24822. __extends(SetParentAction, _super);
  24823. function SetParentAction(triggerOptions, target, parent, condition) {
  24824. _super.call(this, triggerOptions, condition);
  24825. this._target = target;
  24826. this._parent = parent;
  24827. }
  24828. SetParentAction.prototype._prepare = function () {
  24829. };
  24830. SetParentAction.prototype.execute = function () {
  24831. if (this._target.parent === this._parent) {
  24832. return;
  24833. }
  24834. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24835. invertParentWorldMatrix.invert();
  24836. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24837. this._target.parent = this._parent;
  24838. };
  24839. return SetParentAction;
  24840. })(BABYLON.Action);
  24841. BABYLON.SetParentAction = SetParentAction;
  24842. var PlaySoundAction = (function (_super) {
  24843. __extends(PlaySoundAction, _super);
  24844. function PlaySoundAction(triggerOptions, sound, condition) {
  24845. _super.call(this, triggerOptions, condition);
  24846. this._sound = sound;
  24847. }
  24848. PlaySoundAction.prototype._prepare = function () {
  24849. };
  24850. PlaySoundAction.prototype.execute = function () {
  24851. if (this._sound !== undefined)
  24852. this._sound.play();
  24853. };
  24854. return PlaySoundAction;
  24855. })(BABYLON.Action);
  24856. BABYLON.PlaySoundAction = PlaySoundAction;
  24857. var StopSoundAction = (function (_super) {
  24858. __extends(StopSoundAction, _super);
  24859. function StopSoundAction(triggerOptions, sound, condition) {
  24860. _super.call(this, triggerOptions, condition);
  24861. this._sound = sound;
  24862. }
  24863. StopSoundAction.prototype._prepare = function () {
  24864. };
  24865. StopSoundAction.prototype.execute = function () {
  24866. if (this._sound !== undefined)
  24867. this._sound.stop();
  24868. };
  24869. return StopSoundAction;
  24870. })(BABYLON.Action);
  24871. BABYLON.StopSoundAction = StopSoundAction;
  24872. })(BABYLON || (BABYLON = {}));
  24873. //# sourceMappingURL=babylon.directActions.js.map
  24874. var BABYLON;
  24875. (function (BABYLON) {
  24876. var Geometry = (function () {
  24877. function Geometry(id, scene, vertexData, updatable, mesh) {
  24878. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24879. this._totalVertices = 0;
  24880. this._indices = [];
  24881. this._isDisposed = false;
  24882. this.id = id;
  24883. this._engine = scene.getEngine();
  24884. this._meshes = [];
  24885. this._scene = scene;
  24886. // vertexData
  24887. if (vertexData) {
  24888. this.setAllVerticesData(vertexData, updatable);
  24889. }
  24890. else {
  24891. this._totalVertices = 0;
  24892. this._indices = [];
  24893. }
  24894. // applyToMesh
  24895. if (mesh) {
  24896. this.applyToMesh(mesh);
  24897. mesh.computeWorldMatrix(true);
  24898. }
  24899. }
  24900. Geometry.prototype.getScene = function () {
  24901. return this._scene;
  24902. };
  24903. Geometry.prototype.getEngine = function () {
  24904. return this._engine;
  24905. };
  24906. Geometry.prototype.isReady = function () {
  24907. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24908. };
  24909. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24910. vertexData.applyToGeometry(this, updatable);
  24911. };
  24912. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24913. this._vertexBuffers = this._vertexBuffers || {};
  24914. if (this._vertexBuffers[kind]) {
  24915. this._vertexBuffers[kind].dispose();
  24916. }
  24917. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24918. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24919. stride = this._vertexBuffers[kind].getStrideSize();
  24920. this._totalVertices = data.length / stride;
  24921. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24922. var meshes = this._meshes;
  24923. var numOfMeshes = meshes.length;
  24924. for (var index = 0; index < numOfMeshes; index++) {
  24925. var mesh = meshes[index];
  24926. mesh._resetPointsArrayCache();
  24927. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24928. mesh._createGlobalSubMesh();
  24929. mesh.computeWorldMatrix(true);
  24930. }
  24931. }
  24932. };
  24933. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24934. var vertexBuffer = this.getVertexBuffer(kind);
  24935. if (!vertexBuffer) {
  24936. return;
  24937. }
  24938. vertexBuffer.updateDirectly(data, offset);
  24939. };
  24940. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24941. var vertexBuffer = this.getVertexBuffer(kind);
  24942. if (!vertexBuffer) {
  24943. return;
  24944. }
  24945. vertexBuffer.update(data);
  24946. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24947. var extend;
  24948. var stride = vertexBuffer.getStrideSize();
  24949. this._totalVertices = data.length / stride;
  24950. if (updateExtends) {
  24951. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24952. }
  24953. var meshes = this._meshes;
  24954. var numOfMeshes = meshes.length;
  24955. for (var index = 0; index < numOfMeshes; index++) {
  24956. var mesh = meshes[index];
  24957. mesh._resetPointsArrayCache();
  24958. if (updateExtends) {
  24959. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24960. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24961. var subMesh = mesh.subMeshes[subIndex];
  24962. subMesh.refreshBoundingInfo();
  24963. }
  24964. }
  24965. }
  24966. }
  24967. };
  24968. Geometry.prototype.getTotalVertices = function () {
  24969. if (!this.isReady()) {
  24970. return 0;
  24971. }
  24972. return this._totalVertices;
  24973. };
  24974. Geometry.prototype.getVerticesData = function (kind) {
  24975. var vertexBuffer = this.getVertexBuffer(kind);
  24976. if (!vertexBuffer) {
  24977. return null;
  24978. }
  24979. return vertexBuffer.getData();
  24980. };
  24981. Geometry.prototype.getVertexBuffer = function (kind) {
  24982. if (!this.isReady()) {
  24983. return null;
  24984. }
  24985. return this._vertexBuffers[kind];
  24986. };
  24987. Geometry.prototype.getVertexBuffers = function () {
  24988. if (!this.isReady()) {
  24989. return null;
  24990. }
  24991. return this._vertexBuffers;
  24992. };
  24993. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24994. if (!this._vertexBuffers) {
  24995. if (this._delayInfo) {
  24996. return this._delayInfo.indexOf(kind) !== -1;
  24997. }
  24998. return false;
  24999. }
  25000. return this._vertexBuffers[kind] !== undefined;
  25001. };
  25002. Geometry.prototype.getVerticesDataKinds = function () {
  25003. var result = [];
  25004. if (!this._vertexBuffers && this._delayInfo) {
  25005. for (var kind in this._delayInfo) {
  25006. result.push(kind);
  25007. }
  25008. }
  25009. else {
  25010. for (kind in this._vertexBuffers) {
  25011. result.push(kind);
  25012. }
  25013. }
  25014. return result;
  25015. };
  25016. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25017. if (this._indexBuffer) {
  25018. this._engine._releaseBuffer(this._indexBuffer);
  25019. }
  25020. this._indices = indices;
  25021. if (this._meshes.length !== 0 && this._indices) {
  25022. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25023. }
  25024. if (totalVertices !== undefined) {
  25025. this._totalVertices = totalVertices;
  25026. }
  25027. var meshes = this._meshes;
  25028. var numOfMeshes = meshes.length;
  25029. for (var index = 0; index < numOfMeshes; index++) {
  25030. meshes[index]._createGlobalSubMesh();
  25031. }
  25032. };
  25033. Geometry.prototype.getTotalIndices = function () {
  25034. if (!this.isReady()) {
  25035. return 0;
  25036. }
  25037. return this._indices.length;
  25038. };
  25039. Geometry.prototype.getIndices = function () {
  25040. if (!this.isReady()) {
  25041. return null;
  25042. }
  25043. return this._indices;
  25044. };
  25045. Geometry.prototype.getIndexBuffer = function () {
  25046. if (!this.isReady()) {
  25047. return null;
  25048. }
  25049. return this._indexBuffer;
  25050. };
  25051. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25052. var meshes = this._meshes;
  25053. var index = meshes.indexOf(mesh);
  25054. if (index === -1) {
  25055. return;
  25056. }
  25057. for (var kind in this._vertexBuffers) {
  25058. this._vertexBuffers[kind].dispose();
  25059. }
  25060. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25061. this._indexBuffer = null;
  25062. }
  25063. meshes.splice(index, 1);
  25064. mesh._geometry = null;
  25065. if (meshes.length === 0 && shouldDispose) {
  25066. this.dispose();
  25067. }
  25068. };
  25069. Geometry.prototype.applyToMesh = function (mesh) {
  25070. if (mesh._geometry === this) {
  25071. return;
  25072. }
  25073. var previousGeometry = mesh._geometry;
  25074. if (previousGeometry) {
  25075. previousGeometry.releaseForMesh(mesh);
  25076. }
  25077. var meshes = this._meshes;
  25078. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25079. mesh._geometry = this;
  25080. this._scene.pushGeometry(this);
  25081. meshes.push(mesh);
  25082. if (this.isReady()) {
  25083. this._applyToMesh(mesh);
  25084. }
  25085. else {
  25086. mesh._boundingInfo = this._boundingInfo;
  25087. }
  25088. };
  25089. Geometry.prototype._applyToMesh = function (mesh) {
  25090. var numOfMeshes = this._meshes.length;
  25091. for (var kind in this._vertexBuffers) {
  25092. if (numOfMeshes === 1) {
  25093. this._vertexBuffers[kind].create();
  25094. }
  25095. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25096. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25097. mesh._resetPointsArrayCache();
  25098. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25099. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25100. mesh._createGlobalSubMesh();
  25101. //bounding info was just created again, world matrix should be applied again.
  25102. mesh._updateBoundingInfo();
  25103. }
  25104. }
  25105. // indexBuffer
  25106. if (numOfMeshes === 1 && this._indices) {
  25107. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25108. }
  25109. if (this._indexBuffer) {
  25110. this._indexBuffer.references = numOfMeshes;
  25111. }
  25112. };
  25113. Geometry.prototype.load = function (scene, onLoaded) {
  25114. var _this = this;
  25115. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25116. return;
  25117. }
  25118. if (this.isReady()) {
  25119. if (onLoaded) {
  25120. onLoaded();
  25121. }
  25122. return;
  25123. }
  25124. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25125. scene._addPendingData(this);
  25126. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25127. _this._delayLoadingFunction(JSON.parse(data), _this);
  25128. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25129. _this._delayInfo = [];
  25130. scene._removePendingData(_this);
  25131. var meshes = _this._meshes;
  25132. var numOfMeshes = meshes.length;
  25133. for (var index = 0; index < numOfMeshes; index++) {
  25134. _this._applyToMesh(meshes[index]);
  25135. }
  25136. if (onLoaded) {
  25137. onLoaded();
  25138. }
  25139. }, function () {
  25140. }, scene.database);
  25141. };
  25142. Geometry.prototype.isDisposed = function () {
  25143. return this._isDisposed;
  25144. };
  25145. Geometry.prototype.dispose = function () {
  25146. var meshes = this._meshes;
  25147. var numOfMeshes = meshes.length;
  25148. var index;
  25149. for (index = 0; index < numOfMeshes; index++) {
  25150. this.releaseForMesh(meshes[index]);
  25151. }
  25152. this._meshes = [];
  25153. for (var kind in this._vertexBuffers) {
  25154. this._vertexBuffers[kind].dispose();
  25155. }
  25156. this._vertexBuffers = [];
  25157. this._totalVertices = 0;
  25158. if (this._indexBuffer) {
  25159. this._engine._releaseBuffer(this._indexBuffer);
  25160. }
  25161. this._indexBuffer = null;
  25162. this._indices = [];
  25163. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25164. this.delayLoadingFile = null;
  25165. this._delayLoadingFunction = null;
  25166. this._delayInfo = [];
  25167. this._boundingInfo = null; // todo: .dispose()
  25168. var geometries = this._scene.getGeometries();
  25169. index = geometries.indexOf(this);
  25170. if (index > -1) {
  25171. geometries.splice(index, 1);
  25172. }
  25173. this._isDisposed = true;
  25174. };
  25175. Geometry.prototype.copy = function (id) {
  25176. var vertexData = new BABYLON.VertexData();
  25177. vertexData.indices = [];
  25178. var indices = this.getIndices();
  25179. for (var index = 0; index < indices.length; index++) {
  25180. vertexData.indices.push(indices[index]);
  25181. }
  25182. var updatable = false;
  25183. var stopChecking = false;
  25184. for (var kind in this._vertexBuffers) {
  25185. // using slice() to make a copy of the array and not just reference it
  25186. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25187. if (!stopChecking) {
  25188. updatable = this.getVertexBuffer(kind).isUpdatable();
  25189. stopChecking = !updatable;
  25190. }
  25191. }
  25192. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25193. geometry.delayLoadState = this.delayLoadState;
  25194. geometry.delayLoadingFile = this.delayLoadingFile;
  25195. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25196. for (kind in this._delayInfo) {
  25197. geometry._delayInfo = geometry._delayInfo || [];
  25198. geometry._delayInfo.push(kind);
  25199. }
  25200. // Bounding info
  25201. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25202. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25203. return geometry;
  25204. };
  25205. // Statics
  25206. Geometry.ExtractFromMesh = function (mesh, id) {
  25207. var geometry = mesh._geometry;
  25208. if (!geometry) {
  25209. return null;
  25210. }
  25211. return geometry.copy(id);
  25212. };
  25213. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25214. // be aware Math.random() could cause collisions
  25215. Geometry.RandomId = function () {
  25216. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25217. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25218. return v.toString(16);
  25219. });
  25220. };
  25221. return Geometry;
  25222. })();
  25223. BABYLON.Geometry = Geometry;
  25224. /////// Primitives //////////////////////////////////////////////
  25225. var Geometry;
  25226. (function (Geometry) {
  25227. var Primitives;
  25228. (function (Primitives) {
  25229. /// Abstract class
  25230. var _Primitive = (function (_super) {
  25231. __extends(_Primitive, _super);
  25232. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25233. this._beingRegenerated = true;
  25234. this._canBeRegenerated = canBeRegenerated;
  25235. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25236. this._beingRegenerated = false;
  25237. }
  25238. _Primitive.prototype.canBeRegenerated = function () {
  25239. return this._canBeRegenerated;
  25240. };
  25241. _Primitive.prototype.regenerate = function () {
  25242. if (!this._canBeRegenerated) {
  25243. return;
  25244. }
  25245. this._beingRegenerated = true;
  25246. this.setAllVerticesData(this._regenerateVertexData(), false);
  25247. this._beingRegenerated = false;
  25248. };
  25249. _Primitive.prototype.asNewGeometry = function (id) {
  25250. return _super.prototype.copy.call(this, id);
  25251. };
  25252. // overrides
  25253. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25254. if (!this._beingRegenerated) {
  25255. return;
  25256. }
  25257. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25258. };
  25259. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25260. if (!this._beingRegenerated) {
  25261. return;
  25262. }
  25263. _super.prototype.setVerticesData.call(this, kind, data, false);
  25264. };
  25265. // to override
  25266. // protected
  25267. _Primitive.prototype._regenerateVertexData = function () {
  25268. throw new Error("Abstract method");
  25269. };
  25270. _Primitive.prototype.copy = function (id) {
  25271. throw new Error("Must be overriden in sub-classes.");
  25272. };
  25273. return _Primitive;
  25274. })(Geometry);
  25275. Primitives._Primitive = _Primitive;
  25276. var Ribbon = (function (_super) {
  25277. __extends(Ribbon, _super);
  25278. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25279. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25280. this.pathArray = pathArray;
  25281. this.closeArray = closeArray;
  25282. this.closePath = closePath;
  25283. this.offset = offset;
  25284. this.side = side;
  25285. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25286. }
  25287. Ribbon.prototype._regenerateVertexData = function () {
  25288. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25289. };
  25290. Ribbon.prototype.copy = function (id) {
  25291. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25292. };
  25293. return Ribbon;
  25294. })(_Primitive);
  25295. Primitives.Ribbon = Ribbon;
  25296. var Box = (function (_super) {
  25297. __extends(Box, _super);
  25298. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25299. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25300. this.size = size;
  25301. this.side = side;
  25302. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25303. }
  25304. Box.prototype._regenerateVertexData = function () {
  25305. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25306. };
  25307. Box.prototype.copy = function (id) {
  25308. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25309. };
  25310. return Box;
  25311. })(_Primitive);
  25312. Primitives.Box = Box;
  25313. var Sphere = (function (_super) {
  25314. __extends(Sphere, _super);
  25315. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25316. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25317. this.segments = segments;
  25318. this.diameter = diameter;
  25319. this.side = side;
  25320. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25321. }
  25322. Sphere.prototype._regenerateVertexData = function () {
  25323. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25324. };
  25325. Sphere.prototype.copy = function (id) {
  25326. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25327. };
  25328. return Sphere;
  25329. })(_Primitive);
  25330. Primitives.Sphere = Sphere;
  25331. var Cylinder = (function (_super) {
  25332. __extends(Cylinder, _super);
  25333. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25334. if (subdivisions === void 0) { subdivisions = 1; }
  25335. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25336. this.height = height;
  25337. this.diameterTop = diameterTop;
  25338. this.diameterBottom = diameterBottom;
  25339. this.tessellation = tessellation;
  25340. this.subdivisions = subdivisions;
  25341. this.side = side;
  25342. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25343. }
  25344. Cylinder.prototype._regenerateVertexData = function () {
  25345. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25346. };
  25347. Cylinder.prototype.copy = function (id) {
  25348. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25349. };
  25350. return Cylinder;
  25351. })(_Primitive);
  25352. Primitives.Cylinder = Cylinder;
  25353. var Torus = (function (_super) {
  25354. __extends(Torus, _super);
  25355. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25356. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25357. this.diameter = diameter;
  25358. this.thickness = thickness;
  25359. this.tessellation = tessellation;
  25360. this.side = side;
  25361. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25362. }
  25363. Torus.prototype._regenerateVertexData = function () {
  25364. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25365. };
  25366. Torus.prototype.copy = function (id) {
  25367. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25368. };
  25369. return Torus;
  25370. })(_Primitive);
  25371. Primitives.Torus = Torus;
  25372. var Ground = (function (_super) {
  25373. __extends(Ground, _super);
  25374. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25375. this.width = width;
  25376. this.height = height;
  25377. this.subdivisions = subdivisions;
  25378. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25379. }
  25380. Ground.prototype._regenerateVertexData = function () {
  25381. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25382. };
  25383. Ground.prototype.copy = function (id) {
  25384. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25385. };
  25386. return Ground;
  25387. })(_Primitive);
  25388. Primitives.Ground = Ground;
  25389. var TiledGround = (function (_super) {
  25390. __extends(TiledGround, _super);
  25391. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25392. this.xmin = xmin;
  25393. this.zmin = zmin;
  25394. this.xmax = xmax;
  25395. this.zmax = zmax;
  25396. this.subdivisions = subdivisions;
  25397. this.precision = precision;
  25398. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25399. }
  25400. TiledGround.prototype._regenerateVertexData = function () {
  25401. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25402. };
  25403. TiledGround.prototype.copy = function (id) {
  25404. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25405. };
  25406. return TiledGround;
  25407. })(_Primitive);
  25408. Primitives.TiledGround = TiledGround;
  25409. var Plane = (function (_super) {
  25410. __extends(Plane, _super);
  25411. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25412. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25413. this.size = size;
  25414. this.side = side;
  25415. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25416. }
  25417. Plane.prototype._regenerateVertexData = function () {
  25418. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25419. };
  25420. Plane.prototype.copy = function (id) {
  25421. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25422. };
  25423. return Plane;
  25424. })(_Primitive);
  25425. Primitives.Plane = Plane;
  25426. var TorusKnot = (function (_super) {
  25427. __extends(TorusKnot, _super);
  25428. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25429. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25430. this.radius = radius;
  25431. this.tube = tube;
  25432. this.radialSegments = radialSegments;
  25433. this.tubularSegments = tubularSegments;
  25434. this.p = p;
  25435. this.q = q;
  25436. this.side = side;
  25437. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25438. }
  25439. TorusKnot.prototype._regenerateVertexData = function () {
  25440. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25441. };
  25442. TorusKnot.prototype.copy = function (id) {
  25443. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25444. };
  25445. return TorusKnot;
  25446. })(_Primitive);
  25447. Primitives.TorusKnot = TorusKnot;
  25448. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25449. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25450. })(BABYLON || (BABYLON = {}));
  25451. //# sourceMappingURL=babylon.geometry.js.map
  25452. var BABYLON;
  25453. (function (BABYLON) {
  25454. var Gamepads = (function () {
  25455. function Gamepads(ongamedpadconnected) {
  25456. var _this = this;
  25457. this.babylonGamepads = [];
  25458. this.oneGamepadConnected = false;
  25459. this.isMonitoring = false;
  25460. this.gamepadEventSupported = 'GamepadEvent' in window;
  25461. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25462. 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=";
  25463. this._callbackGamepadConnected = ongamedpadconnected;
  25464. if (this.gamepadSupportAvailable) {
  25465. // Checking if the gamepad connected event is supported (like in Firefox)
  25466. if (this.gamepadEventSupported) {
  25467. window.addEventListener('gamepadconnected', function (evt) {
  25468. _this._onGamepadConnected(evt);
  25469. }, false);
  25470. window.addEventListener('gamepaddisconnected', function (evt) {
  25471. _this._onGamepadDisconnected(evt);
  25472. }, false);
  25473. }
  25474. else {
  25475. this._startMonitoringGamepads();
  25476. }
  25477. if (!this.oneGamepadConnected) {
  25478. this._insertGamepadDOMInstructions();
  25479. }
  25480. }
  25481. else {
  25482. this._insertGamepadDOMNotSupported();
  25483. }
  25484. }
  25485. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25486. Gamepads.gamepadDOMInfo = document.createElement("div");
  25487. var buttonAImage = document.createElement("img");
  25488. buttonAImage.src = this.buttonADataURL;
  25489. var spanMessage = document.createElement("span");
  25490. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25491. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25492. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25493. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25494. Gamepads.gamepadDOMInfo.style.width = "100%";
  25495. Gamepads.gamepadDOMInfo.style.height = "48px";
  25496. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25497. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25498. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25499. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25500. buttonAImage.style.position = "relative";
  25501. buttonAImage.style.bottom = "8px";
  25502. spanMessage.style.position = "relative";
  25503. spanMessage.style.fontSize = "32px";
  25504. spanMessage.style.bottom = "32px";
  25505. spanMessage.style.color = "green";
  25506. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25507. };
  25508. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25509. Gamepads.gamepadDOMInfo = document.createElement("div");
  25510. var spanMessage = document.createElement("span");
  25511. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25512. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25513. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25514. Gamepads.gamepadDOMInfo.style.width = "100%";
  25515. Gamepads.gamepadDOMInfo.style.height = "40px";
  25516. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25517. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25518. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25519. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25520. spanMessage.style.position = "relative";
  25521. spanMessage.style.fontSize = "32px";
  25522. spanMessage.style.color = "red";
  25523. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25524. };
  25525. Gamepads.prototype.dispose = function () {
  25526. if (Gamepads.gamepadDOMInfo) {
  25527. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25528. }
  25529. };
  25530. Gamepads.prototype._onGamepadConnected = function (evt) {
  25531. var newGamepad = this._addNewGamepad(evt.gamepad);
  25532. if (this._callbackGamepadConnected)
  25533. this._callbackGamepadConnected(newGamepad);
  25534. this._startMonitoringGamepads();
  25535. };
  25536. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25537. if (!this.oneGamepadConnected) {
  25538. this.oneGamepadConnected = true;
  25539. if (Gamepads.gamepadDOMInfo) {
  25540. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25541. Gamepads.gamepadDOMInfo = null;
  25542. }
  25543. }
  25544. var newGamepad;
  25545. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25546. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25547. }
  25548. else {
  25549. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25550. }
  25551. this.babylonGamepads.push(newGamepad);
  25552. return newGamepad;
  25553. };
  25554. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25555. for (var i in this.babylonGamepads) {
  25556. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25557. this.babylonGamepads.splice(i, 1);
  25558. break;
  25559. }
  25560. }
  25561. // If no gamepads are left, stop the polling loop.
  25562. if (this.babylonGamepads.length == 0) {
  25563. this._stopMonitoringGamepads();
  25564. }
  25565. };
  25566. Gamepads.prototype._startMonitoringGamepads = function () {
  25567. if (!this.isMonitoring) {
  25568. this.isMonitoring = true;
  25569. this._checkGamepadsStatus();
  25570. }
  25571. };
  25572. Gamepads.prototype._stopMonitoringGamepads = function () {
  25573. this.isMonitoring = false;
  25574. };
  25575. Gamepads.prototype._checkGamepadsStatus = function () {
  25576. var _this = this;
  25577. // updating gamepad objects
  25578. this._updateGamepadObjects();
  25579. for (var i in this.babylonGamepads) {
  25580. this.babylonGamepads[i].update();
  25581. }
  25582. if (this.isMonitoring) {
  25583. if (window.requestAnimationFrame) {
  25584. window.requestAnimationFrame(function () {
  25585. _this._checkGamepadsStatus();
  25586. });
  25587. }
  25588. else if (window.mozRequestAnimationFrame) {
  25589. window.mozRequestAnimationFrame(function () {
  25590. _this._checkGamepadsStatus();
  25591. });
  25592. }
  25593. else if (window.webkitRequestAnimationFrame) {
  25594. window.webkitRequestAnimationFrame(function () {
  25595. _this._checkGamepadsStatus();
  25596. });
  25597. }
  25598. }
  25599. };
  25600. // This function is called only on Chrome, which does not yet support
  25601. // connection/disconnection events, but requires you to monitor
  25602. // an array for changes.
  25603. Gamepads.prototype._updateGamepadObjects = function () {
  25604. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25605. for (var i = 0; i < gamepads.length; i++) {
  25606. if (gamepads[i]) {
  25607. if (!(gamepads[i].index in this.babylonGamepads)) {
  25608. var newGamepad = this._addNewGamepad(gamepads[i]);
  25609. if (this._callbackGamepadConnected) {
  25610. this._callbackGamepadConnected(newGamepad);
  25611. }
  25612. }
  25613. else {
  25614. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25615. }
  25616. }
  25617. }
  25618. };
  25619. return Gamepads;
  25620. })();
  25621. BABYLON.Gamepads = Gamepads;
  25622. var StickValues = (function () {
  25623. function StickValues(x, y) {
  25624. this.x = x;
  25625. this.y = y;
  25626. }
  25627. return StickValues;
  25628. })();
  25629. BABYLON.StickValues = StickValues;
  25630. var Gamepad = (function () {
  25631. function Gamepad(id, index, browserGamepad) {
  25632. this.id = id;
  25633. this.index = index;
  25634. this.browserGamepad = browserGamepad;
  25635. if (this.browserGamepad.axes.length >= 2) {
  25636. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25637. }
  25638. if (this.browserGamepad.axes.length >= 4) {
  25639. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25640. }
  25641. }
  25642. Gamepad.prototype.onleftstickchanged = function (callback) {
  25643. this._onleftstickchanged = callback;
  25644. };
  25645. Gamepad.prototype.onrightstickchanged = function (callback) {
  25646. this._onrightstickchanged = callback;
  25647. };
  25648. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25649. get: function () {
  25650. return this._leftStick;
  25651. },
  25652. set: function (newValues) {
  25653. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25654. this._onleftstickchanged(newValues);
  25655. }
  25656. this._leftStick = newValues;
  25657. },
  25658. enumerable: true,
  25659. configurable: true
  25660. });
  25661. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25662. get: function () {
  25663. return this._rightStick;
  25664. },
  25665. set: function (newValues) {
  25666. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25667. this._onrightstickchanged(newValues);
  25668. }
  25669. this._rightStick = newValues;
  25670. },
  25671. enumerable: true,
  25672. configurable: true
  25673. });
  25674. Gamepad.prototype.update = function () {
  25675. if (this._leftStick) {
  25676. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25677. }
  25678. if (this._rightStick) {
  25679. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25680. }
  25681. };
  25682. return Gamepad;
  25683. })();
  25684. BABYLON.Gamepad = Gamepad;
  25685. var GenericPad = (function (_super) {
  25686. __extends(GenericPad, _super);
  25687. function GenericPad(id, index, gamepad) {
  25688. _super.call(this, id, index, gamepad);
  25689. this.id = id;
  25690. this.index = index;
  25691. this.gamepad = gamepad;
  25692. this._buttons = new Array(gamepad.buttons.length);
  25693. }
  25694. GenericPad.prototype.onbuttondown = function (callback) {
  25695. this._onbuttondown = callback;
  25696. };
  25697. GenericPad.prototype.onbuttonup = function (callback) {
  25698. this._onbuttonup = callback;
  25699. };
  25700. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25701. if (newValue !== currentValue) {
  25702. if (this._onbuttondown && newValue === 1) {
  25703. this._onbuttondown(buttonIndex);
  25704. }
  25705. if (this._onbuttonup && newValue === 0) {
  25706. this._onbuttonup(buttonIndex);
  25707. }
  25708. }
  25709. return newValue;
  25710. };
  25711. GenericPad.prototype.update = function () {
  25712. _super.prototype.update.call(this);
  25713. for (var index = 0; index < this._buttons.length; index++) {
  25714. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25715. }
  25716. };
  25717. return GenericPad;
  25718. })(Gamepad);
  25719. BABYLON.GenericPad = GenericPad;
  25720. (function (Xbox360Button) {
  25721. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25722. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25723. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25724. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25725. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25726. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25727. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25728. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25729. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25730. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25731. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25732. var Xbox360Button = BABYLON.Xbox360Button;
  25733. (function (Xbox360Dpad) {
  25734. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25735. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25736. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25737. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25738. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25739. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25740. var Xbox360Pad = (function (_super) {
  25741. __extends(Xbox360Pad, _super);
  25742. function Xbox360Pad() {
  25743. _super.apply(this, arguments);
  25744. this._leftTrigger = 0;
  25745. this._rightTrigger = 0;
  25746. this._buttonA = 0;
  25747. this._buttonB = 0;
  25748. this._buttonX = 0;
  25749. this._buttonY = 0;
  25750. this._buttonBack = 0;
  25751. this._buttonStart = 0;
  25752. this._buttonLB = 0;
  25753. this._buttonRB = 0;
  25754. this._buttonLeftStick = 0;
  25755. this._buttonRightStick = 0;
  25756. this._dPadUp = 0;
  25757. this._dPadDown = 0;
  25758. this._dPadLeft = 0;
  25759. this._dPadRight = 0;
  25760. }
  25761. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25762. this._onlefttriggerchanged = callback;
  25763. };
  25764. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25765. this._onrighttriggerchanged = callback;
  25766. };
  25767. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25768. get: function () {
  25769. return this._leftTrigger;
  25770. },
  25771. set: function (newValue) {
  25772. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25773. this._onlefttriggerchanged(newValue);
  25774. }
  25775. this._leftTrigger = newValue;
  25776. },
  25777. enumerable: true,
  25778. configurable: true
  25779. });
  25780. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25781. get: function () {
  25782. return this._rightTrigger;
  25783. },
  25784. set: function (newValue) {
  25785. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25786. this._onrighttriggerchanged(newValue);
  25787. }
  25788. this._rightTrigger = newValue;
  25789. },
  25790. enumerable: true,
  25791. configurable: true
  25792. });
  25793. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25794. this._onbuttondown = callback;
  25795. };
  25796. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25797. this._onbuttonup = callback;
  25798. };
  25799. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25800. this._ondpaddown = callback;
  25801. };
  25802. Xbox360Pad.prototype.ondpadup = function (callback) {
  25803. this._ondpadup = callback;
  25804. };
  25805. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25806. if (newValue !== currentValue) {
  25807. if (this._onbuttondown && newValue === 1) {
  25808. this._onbuttondown(buttonType);
  25809. }
  25810. if (this._onbuttonup && newValue === 0) {
  25811. this._onbuttonup(buttonType);
  25812. }
  25813. }
  25814. return newValue;
  25815. };
  25816. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25817. if (newValue !== currentValue) {
  25818. if (this._ondpaddown && newValue === 1) {
  25819. this._ondpaddown(buttonType);
  25820. }
  25821. if (this._ondpadup && newValue === 0) {
  25822. this._ondpadup(buttonType);
  25823. }
  25824. }
  25825. return newValue;
  25826. };
  25827. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25828. get: function () {
  25829. return this._buttonA;
  25830. },
  25831. set: function (value) {
  25832. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25833. },
  25834. enumerable: true,
  25835. configurable: true
  25836. });
  25837. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25838. get: function () {
  25839. return this._buttonB;
  25840. },
  25841. set: function (value) {
  25842. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25843. },
  25844. enumerable: true,
  25845. configurable: true
  25846. });
  25847. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25848. get: function () {
  25849. return this._buttonX;
  25850. },
  25851. set: function (value) {
  25852. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25853. },
  25854. enumerable: true,
  25855. configurable: true
  25856. });
  25857. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25858. get: function () {
  25859. return this._buttonY;
  25860. },
  25861. set: function (value) {
  25862. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25863. },
  25864. enumerable: true,
  25865. configurable: true
  25866. });
  25867. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25868. get: function () {
  25869. return this._buttonStart;
  25870. },
  25871. set: function (value) {
  25872. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25873. },
  25874. enumerable: true,
  25875. configurable: true
  25876. });
  25877. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25878. get: function () {
  25879. return this._buttonBack;
  25880. },
  25881. set: function (value) {
  25882. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25883. },
  25884. enumerable: true,
  25885. configurable: true
  25886. });
  25887. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25888. get: function () {
  25889. return this._buttonLB;
  25890. },
  25891. set: function (value) {
  25892. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25893. },
  25894. enumerable: true,
  25895. configurable: true
  25896. });
  25897. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25898. get: function () {
  25899. return this._buttonRB;
  25900. },
  25901. set: function (value) {
  25902. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25903. },
  25904. enumerable: true,
  25905. configurable: true
  25906. });
  25907. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25908. get: function () {
  25909. return this._buttonLeftStick;
  25910. },
  25911. set: function (value) {
  25912. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25913. },
  25914. enumerable: true,
  25915. configurable: true
  25916. });
  25917. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25918. get: function () {
  25919. return this._buttonRightStick;
  25920. },
  25921. set: function (value) {
  25922. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25923. },
  25924. enumerable: true,
  25925. configurable: true
  25926. });
  25927. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25928. get: function () {
  25929. return this._dPadUp;
  25930. },
  25931. set: function (value) {
  25932. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25933. },
  25934. enumerable: true,
  25935. configurable: true
  25936. });
  25937. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25938. get: function () {
  25939. return this._dPadDown;
  25940. },
  25941. set: function (value) {
  25942. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25943. },
  25944. enumerable: true,
  25945. configurable: true
  25946. });
  25947. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25948. get: function () {
  25949. return this._dPadLeft;
  25950. },
  25951. set: function (value) {
  25952. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25953. },
  25954. enumerable: true,
  25955. configurable: true
  25956. });
  25957. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25958. get: function () {
  25959. return this._dPadRight;
  25960. },
  25961. set: function (value) {
  25962. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25963. },
  25964. enumerable: true,
  25965. configurable: true
  25966. });
  25967. Xbox360Pad.prototype.update = function () {
  25968. _super.prototype.update.call(this);
  25969. this.buttonA = this.browserGamepad.buttons[0].value;
  25970. this.buttonB = this.browserGamepad.buttons[1].value;
  25971. this.buttonX = this.browserGamepad.buttons[2].value;
  25972. this.buttonY = this.browserGamepad.buttons[3].value;
  25973. this.buttonLB = this.browserGamepad.buttons[4].value;
  25974. this.buttonRB = this.browserGamepad.buttons[5].value;
  25975. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25976. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25977. this.buttonBack = this.browserGamepad.buttons[8].value;
  25978. this.buttonStart = this.browserGamepad.buttons[9].value;
  25979. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25980. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25981. this.dPadUp = this.browserGamepad.buttons[12].value;
  25982. this.dPadDown = this.browserGamepad.buttons[13].value;
  25983. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25984. this.dPadRight = this.browserGamepad.buttons[15].value;
  25985. };
  25986. return Xbox360Pad;
  25987. })(Gamepad);
  25988. BABYLON.Xbox360Pad = Xbox360Pad;
  25989. })(BABYLON || (BABYLON = {}));
  25990. //# sourceMappingURL=babylon.gamepads.js.map
  25991. var BABYLON;
  25992. (function (BABYLON) {
  25993. // We're mainly based on the logic defined into the FreeCamera code
  25994. var GamepadCamera = (function (_super) {
  25995. __extends(GamepadCamera, _super);
  25996. function GamepadCamera(name, position, scene) {
  25997. var _this = this;
  25998. _super.call(this, name, position, scene);
  25999. this.angularSensibility = 200;
  26000. this.moveSensibility = 75;
  26001. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26002. _this._onNewGameConnected(gamepad);
  26003. });
  26004. }
  26005. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26006. // Only the first gamepad can control the camera
  26007. if (gamepad.index === 0) {
  26008. this._gamepad = gamepad;
  26009. }
  26010. };
  26011. GamepadCamera.prototype._checkInputs = function () {
  26012. if (!this._gamepad) {
  26013. return;
  26014. }
  26015. var LSValues = this._gamepad.leftStick;
  26016. var normalizedLX = LSValues.x / this.moveSensibility;
  26017. var normalizedLY = LSValues.y / this.moveSensibility;
  26018. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26019. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26020. var RSValues = this._gamepad.rightStick;
  26021. var normalizedRX = RSValues.x / this.angularSensibility;
  26022. var normalizedRY = RSValues.y / this.angularSensibility;
  26023. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26024. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26025. ;
  26026. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26027. var speed = this._computeLocalCameraSpeed() * 50.0;
  26028. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26029. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26030. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26031. };
  26032. GamepadCamera.prototype.dispose = function () {
  26033. this._gamepads.dispose();
  26034. _super.prototype.dispose.call(this);
  26035. };
  26036. return GamepadCamera;
  26037. })(BABYLON.FreeCamera);
  26038. BABYLON.GamepadCamera = GamepadCamera;
  26039. })(BABYLON || (BABYLON = {}));
  26040. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26041. var BABYLON;
  26042. (function (BABYLON) {
  26043. var LinesMesh = (function (_super) {
  26044. __extends(LinesMesh, _super);
  26045. function LinesMesh(name, scene, updatable) {
  26046. if (updatable === void 0) { updatable = false; }
  26047. _super.call(this, name, scene);
  26048. this.color = new BABYLON.Color3(1, 1, 1);
  26049. this.alpha = 1;
  26050. this._indices = new Array();
  26051. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26052. attributes: ["position"],
  26053. uniforms: ["worldViewProjection", "color"],
  26054. needAlphaBlending: true
  26055. });
  26056. }
  26057. Object.defineProperty(LinesMesh.prototype, "material", {
  26058. get: function () {
  26059. return this._colorShader;
  26060. },
  26061. enumerable: true,
  26062. configurable: true
  26063. });
  26064. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26065. get: function () {
  26066. return false;
  26067. },
  26068. enumerable: true,
  26069. configurable: true
  26070. });
  26071. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26072. get: function () {
  26073. return false;
  26074. },
  26075. enumerable: true,
  26076. configurable: true
  26077. });
  26078. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26079. var engine = this.getScene().getEngine();
  26080. var indexToBind = this._geometry.getIndexBuffer();
  26081. // VBOs
  26082. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26083. // Color
  26084. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26085. };
  26086. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26087. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26088. return;
  26089. }
  26090. var engine = this.getScene().getEngine();
  26091. // Draw order
  26092. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26093. };
  26094. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26095. return null;
  26096. };
  26097. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26098. this._colorShader.dispose();
  26099. _super.prototype.dispose.call(this, doNotRecurse);
  26100. };
  26101. return LinesMesh;
  26102. })(BABYLON.Mesh);
  26103. BABYLON.LinesMesh = LinesMesh;
  26104. })(BABYLON || (BABYLON = {}));
  26105. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26106. (function (BABYLON) {
  26107. var OutlineRenderer = (function () {
  26108. function OutlineRenderer(scene) {
  26109. this._scene = scene;
  26110. }
  26111. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26112. var _this = this;
  26113. if (useOverlay === void 0) { useOverlay = false; }
  26114. var scene = this._scene;
  26115. var engine = this._scene.getEngine();
  26116. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26117. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26118. return;
  26119. }
  26120. var mesh = subMesh.getRenderingMesh();
  26121. var material = subMesh.getMaterial();
  26122. engine.enableEffect(this._effect);
  26123. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26124. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26125. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26126. // Bones
  26127. if (mesh.useBones) {
  26128. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26129. }
  26130. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26131. // Alpha test
  26132. if (material && material.needAlphaTesting()) {
  26133. var alphaTexture = material.getAlphaTestTexture();
  26134. this._effect.setTexture("diffuseSampler", alphaTexture);
  26135. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26136. }
  26137. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26138. _this._effect.setMatrix("world", world);
  26139. });
  26140. };
  26141. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26142. var defines = [];
  26143. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26144. var mesh = subMesh.getMesh();
  26145. var material = subMesh.getMaterial();
  26146. // Alpha test
  26147. if (material && material.needAlphaTesting()) {
  26148. defines.push("#define ALPHATEST");
  26149. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26150. attribs.push(BABYLON.VertexBuffer.UVKind);
  26151. defines.push("#define UV1");
  26152. }
  26153. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26154. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26155. defines.push("#define UV2");
  26156. }
  26157. }
  26158. // Bones
  26159. if (mesh.useBones) {
  26160. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26161. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26162. defines.push("#define BONES");
  26163. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26164. }
  26165. // Instances
  26166. if (useInstances) {
  26167. defines.push("#define INSTANCES");
  26168. attribs.push("world0");
  26169. attribs.push("world1");
  26170. attribs.push("world2");
  26171. attribs.push("world3");
  26172. }
  26173. // Get correct effect
  26174. var join = defines.join("\n");
  26175. if (this._cachedDefines !== join) {
  26176. this._cachedDefines = join;
  26177. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26178. }
  26179. return this._effect.isReady();
  26180. };
  26181. return OutlineRenderer;
  26182. })();
  26183. BABYLON.OutlineRenderer = OutlineRenderer;
  26184. })(BABYLON || (BABYLON = {}));
  26185. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26186. (function (BABYLON) {
  26187. var MeshAssetTask = (function () {
  26188. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26189. this.name = name;
  26190. this.meshesNames = meshesNames;
  26191. this.rootUrl = rootUrl;
  26192. this.sceneFilename = sceneFilename;
  26193. this.isCompleted = false;
  26194. }
  26195. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26196. var _this = this;
  26197. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26198. _this.loadedMeshes = meshes;
  26199. _this.loadedParticleSystems = particleSystems;
  26200. _this.loadedSkeletons = skeletons;
  26201. _this.isCompleted = true;
  26202. if (_this.onSuccess) {
  26203. _this.onSuccess(_this);
  26204. }
  26205. onSuccess();
  26206. }, null, function () {
  26207. if (_this.onError) {
  26208. _this.onError(_this);
  26209. }
  26210. onError();
  26211. });
  26212. };
  26213. return MeshAssetTask;
  26214. })();
  26215. BABYLON.MeshAssetTask = MeshAssetTask;
  26216. var TextFileAssetTask = (function () {
  26217. function TextFileAssetTask(name, url) {
  26218. this.name = name;
  26219. this.url = url;
  26220. this.isCompleted = false;
  26221. }
  26222. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26223. var _this = this;
  26224. BABYLON.Tools.LoadFile(this.url, function (data) {
  26225. _this.text = data;
  26226. _this.isCompleted = true;
  26227. if (_this.onSuccess) {
  26228. _this.onSuccess(_this);
  26229. }
  26230. onSuccess();
  26231. }, null, scene.database, false, function () {
  26232. if (_this.onError) {
  26233. _this.onError(_this);
  26234. }
  26235. onError();
  26236. });
  26237. };
  26238. return TextFileAssetTask;
  26239. })();
  26240. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26241. var BinaryFileAssetTask = (function () {
  26242. function BinaryFileAssetTask(name, url) {
  26243. this.name = name;
  26244. this.url = url;
  26245. this.isCompleted = false;
  26246. }
  26247. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26248. var _this = this;
  26249. BABYLON.Tools.LoadFile(this.url, function (data) {
  26250. _this.data = data;
  26251. _this.isCompleted = true;
  26252. if (_this.onSuccess) {
  26253. _this.onSuccess(_this);
  26254. }
  26255. onSuccess();
  26256. }, null, scene.database, true, function () {
  26257. if (_this.onError) {
  26258. _this.onError(_this);
  26259. }
  26260. onError();
  26261. });
  26262. };
  26263. return BinaryFileAssetTask;
  26264. })();
  26265. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26266. var ImageAssetTask = (function () {
  26267. function ImageAssetTask(name, url) {
  26268. this.name = name;
  26269. this.url = url;
  26270. this.isCompleted = false;
  26271. }
  26272. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26273. var _this = this;
  26274. var img = new Image();
  26275. img.onload = function () {
  26276. _this.image = img;
  26277. _this.isCompleted = true;
  26278. if (_this.onSuccess) {
  26279. _this.onSuccess(_this);
  26280. }
  26281. onSuccess();
  26282. };
  26283. img.onerror = function () {
  26284. if (_this.onError) {
  26285. _this.onError(_this);
  26286. }
  26287. onError();
  26288. };
  26289. img.src = this.url;
  26290. };
  26291. return ImageAssetTask;
  26292. })();
  26293. BABYLON.ImageAssetTask = ImageAssetTask;
  26294. var TextureAssetTask = (function () {
  26295. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26297. this.name = name;
  26298. this.url = url;
  26299. this.noMipmap = noMipmap;
  26300. this.invertY = invertY;
  26301. this.samplingMode = samplingMode;
  26302. this.isCompleted = false;
  26303. }
  26304. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26305. var _this = this;
  26306. var onload = function () {
  26307. _this.isCompleted = true;
  26308. if (_this.onSuccess) {
  26309. _this.onSuccess(_this);
  26310. }
  26311. onSuccess();
  26312. };
  26313. var onerror = function () {
  26314. if (_this.onError) {
  26315. _this.onError(_this);
  26316. }
  26317. onError();
  26318. };
  26319. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26320. };
  26321. return TextureAssetTask;
  26322. })();
  26323. BABYLON.TextureAssetTask = TextureAssetTask;
  26324. var AssetsManager = (function () {
  26325. function AssetsManager(scene) {
  26326. this._tasks = new Array();
  26327. this._waitingTasksCount = 0;
  26328. this.useDefaultLoadingScreen = true;
  26329. this._scene = scene;
  26330. }
  26331. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26332. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26333. this._tasks.push(task);
  26334. return task;
  26335. };
  26336. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26337. var task = new TextFileAssetTask(taskName, url);
  26338. this._tasks.push(task);
  26339. return task;
  26340. };
  26341. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26342. var task = new BinaryFileAssetTask(taskName, url);
  26343. this._tasks.push(task);
  26344. return task;
  26345. };
  26346. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26347. var task = new ImageAssetTask(taskName, url);
  26348. this._tasks.push(task);
  26349. return task;
  26350. };
  26351. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26353. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26354. this._tasks.push(task);
  26355. return task;
  26356. };
  26357. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26358. this._waitingTasksCount--;
  26359. if (this._waitingTasksCount === 0) {
  26360. if (this.onFinish) {
  26361. this.onFinish(this._tasks);
  26362. }
  26363. this._scene.getEngine().hideLoadingUI();
  26364. }
  26365. };
  26366. AssetsManager.prototype._runTask = function (task) {
  26367. var _this = this;
  26368. task.run(this._scene, function () {
  26369. if (_this.onTaskSuccess) {
  26370. _this.onTaskSuccess(task);
  26371. }
  26372. _this._decreaseWaitingTasksCount();
  26373. }, function () {
  26374. if (_this.onTaskError) {
  26375. _this.onTaskError(task);
  26376. }
  26377. _this._decreaseWaitingTasksCount();
  26378. });
  26379. };
  26380. AssetsManager.prototype.reset = function () {
  26381. this._tasks = new Array();
  26382. return this;
  26383. };
  26384. AssetsManager.prototype.load = function () {
  26385. this._waitingTasksCount = this._tasks.length;
  26386. if (this._waitingTasksCount === 0) {
  26387. if (this.onFinish) {
  26388. this.onFinish(this._tasks);
  26389. }
  26390. return this;
  26391. }
  26392. if (this.useDefaultLoadingScreen) {
  26393. this._scene.getEngine().displayLoadingUI();
  26394. }
  26395. for (var index = 0; index < this._tasks.length; index++) {
  26396. var task = this._tasks[index];
  26397. this._runTask(task);
  26398. }
  26399. return this;
  26400. };
  26401. return AssetsManager;
  26402. })();
  26403. BABYLON.AssetsManager = AssetsManager;
  26404. })(BABYLON || (BABYLON = {}));
  26405. //# sourceMappingURL=babylon.assetsManager.js.map
  26406. var BABYLON;
  26407. (function (BABYLON) {
  26408. var VRDeviceOrientationCamera = (function (_super) {
  26409. __extends(VRDeviceOrientationCamera, _super);
  26410. function VRDeviceOrientationCamera(name, position, scene) {
  26411. _super.call(this, name, position, scene);
  26412. this._alpha = 0;
  26413. this._beta = 0;
  26414. this._gamma = 0;
  26415. }
  26416. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26417. this._alpha = +evt.alpha | 0;
  26418. this._beta = +evt.beta | 0;
  26419. this._gamma = +evt.gamma | 0;
  26420. if (this._gamma < 0) {
  26421. this._gamma = 90 + this._gamma;
  26422. }
  26423. else {
  26424. // Incline it in the correct angle.
  26425. this._gamma = 270 - this._gamma;
  26426. }
  26427. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26428. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26429. this.rotation.z = this._beta / 180.0 * Math.PI;
  26430. };
  26431. return VRDeviceOrientationCamera;
  26432. })(BABYLON.OculusCamera);
  26433. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26434. })(BABYLON || (BABYLON = {}));
  26435. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26436. var BABYLON;
  26437. (function (BABYLON) {
  26438. var WebVRCamera = (function (_super) {
  26439. __extends(WebVRCamera, _super);
  26440. function WebVRCamera(name, position, scene) {
  26441. _super.call(this, name, position, scene);
  26442. this._hmdDevice = null;
  26443. this._sensorDevice = null;
  26444. this._cacheState = null;
  26445. this._cacheQuaternion = new BABYLON.Quaternion();
  26446. this._cacheRotation = BABYLON.Vector3.Zero();
  26447. this._vrEnabled = false;
  26448. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26449. }
  26450. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26451. var size = devices.length;
  26452. var i = 0;
  26453. // Reset devices.
  26454. this._sensorDevice = null;
  26455. this._hmdDevice = null;
  26456. while (i < size && this._hmdDevice === null) {
  26457. if (devices[i] instanceof HMDVRDevice) {
  26458. this._hmdDevice = devices[i];
  26459. }
  26460. i++;
  26461. }
  26462. i = 0;
  26463. while (i < size && this._sensorDevice === null) {
  26464. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26465. this._sensorDevice = devices[i];
  26466. }
  26467. i++;
  26468. }
  26469. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26470. };
  26471. WebVRCamera.prototype._update = function () {
  26472. if (this._vrEnabled) {
  26473. this._cacheState = this._sensorDevice.getState();
  26474. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26475. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26476. this.rotation.x = -this._cacheRotation.z;
  26477. this.rotation.y = -this._cacheRotation.y;
  26478. this.rotation.z = this._cacheRotation.x;
  26479. }
  26480. _super.prototype._update.call(this);
  26481. };
  26482. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26483. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26484. if (navigator.getVRDevices) {
  26485. navigator.getVRDevices().then(this._getWebVRDevices);
  26486. }
  26487. else if (navigator.mozGetVRDevices) {
  26488. navigator.mozGetVRDevices(this._getWebVRDevices);
  26489. }
  26490. };
  26491. WebVRCamera.prototype.detachControl = function (element) {
  26492. _super.prototype.detachControl.call(this, element);
  26493. this._vrEnabled = false;
  26494. };
  26495. return WebVRCamera;
  26496. })(BABYLON.OculusCamera);
  26497. BABYLON.WebVRCamera = WebVRCamera;
  26498. })(BABYLON || (BABYLON = {}));
  26499. //# sourceMappingURL=babylon.webVRCamera.js.map
  26500. var BABYLON;
  26501. (function (BABYLON) {
  26502. // Standard optimizations
  26503. var SceneOptimization = (function () {
  26504. function SceneOptimization(priority) {
  26505. if (priority === void 0) { priority = 0; }
  26506. this.priority = priority;
  26507. this.apply = function (scene) {
  26508. return true; // Return true if everything that can be done was applied
  26509. };
  26510. }
  26511. return SceneOptimization;
  26512. })();
  26513. BABYLON.SceneOptimization = SceneOptimization;
  26514. var TextureOptimization = (function (_super) {
  26515. __extends(TextureOptimization, _super);
  26516. function TextureOptimization(priority, maximumSize) {
  26517. var _this = this;
  26518. if (priority === void 0) { priority = 0; }
  26519. if (maximumSize === void 0) { maximumSize = 1024; }
  26520. _super.call(this, priority);
  26521. this.priority = priority;
  26522. this.maximumSize = maximumSize;
  26523. this.apply = function (scene) {
  26524. var allDone = true;
  26525. for (var index = 0; index < scene.textures.length; index++) {
  26526. var texture = scene.textures[index];
  26527. if (!texture.canRescale) {
  26528. continue;
  26529. }
  26530. var currentSize = texture.getSize();
  26531. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26532. if (maxDimension > _this.maximumSize) {
  26533. texture.scale(0.5);
  26534. allDone = false;
  26535. }
  26536. }
  26537. return allDone;
  26538. };
  26539. }
  26540. return TextureOptimization;
  26541. })(SceneOptimization);
  26542. BABYLON.TextureOptimization = TextureOptimization;
  26543. var HardwareScalingOptimization = (function (_super) {
  26544. __extends(HardwareScalingOptimization, _super);
  26545. function HardwareScalingOptimization(priority, maximumScale) {
  26546. var _this = this;
  26547. if (priority === void 0) { priority = 0; }
  26548. if (maximumScale === void 0) { maximumScale = 2; }
  26549. _super.call(this, priority);
  26550. this.priority = priority;
  26551. this.maximumScale = maximumScale;
  26552. this._currentScale = 1;
  26553. this.apply = function (scene) {
  26554. _this._currentScale++;
  26555. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26556. return _this._currentScale >= _this.maximumScale;
  26557. };
  26558. }
  26559. return HardwareScalingOptimization;
  26560. })(SceneOptimization);
  26561. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26562. var ShadowsOptimization = (function (_super) {
  26563. __extends(ShadowsOptimization, _super);
  26564. function ShadowsOptimization() {
  26565. _super.apply(this, arguments);
  26566. this.apply = function (scene) {
  26567. scene.shadowsEnabled = false;
  26568. return true;
  26569. };
  26570. }
  26571. return ShadowsOptimization;
  26572. })(SceneOptimization);
  26573. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26574. var PostProcessesOptimization = (function (_super) {
  26575. __extends(PostProcessesOptimization, _super);
  26576. function PostProcessesOptimization() {
  26577. _super.apply(this, arguments);
  26578. this.apply = function (scene) {
  26579. scene.postProcessesEnabled = false;
  26580. return true;
  26581. };
  26582. }
  26583. return PostProcessesOptimization;
  26584. })(SceneOptimization);
  26585. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26586. var LensFlaresOptimization = (function (_super) {
  26587. __extends(LensFlaresOptimization, _super);
  26588. function LensFlaresOptimization() {
  26589. _super.apply(this, arguments);
  26590. this.apply = function (scene) {
  26591. scene.lensFlaresEnabled = false;
  26592. return true;
  26593. };
  26594. }
  26595. return LensFlaresOptimization;
  26596. })(SceneOptimization);
  26597. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26598. var ParticlesOptimization = (function (_super) {
  26599. __extends(ParticlesOptimization, _super);
  26600. function ParticlesOptimization() {
  26601. _super.apply(this, arguments);
  26602. this.apply = function (scene) {
  26603. scene.particlesEnabled = false;
  26604. return true;
  26605. };
  26606. }
  26607. return ParticlesOptimization;
  26608. })(SceneOptimization);
  26609. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26610. var RenderTargetsOptimization = (function (_super) {
  26611. __extends(RenderTargetsOptimization, _super);
  26612. function RenderTargetsOptimization() {
  26613. _super.apply(this, arguments);
  26614. this.apply = function (scene) {
  26615. scene.renderTargetsEnabled = false;
  26616. return true;
  26617. };
  26618. }
  26619. return RenderTargetsOptimization;
  26620. })(SceneOptimization);
  26621. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26622. var MergeMeshesOptimization = (function (_super) {
  26623. __extends(MergeMeshesOptimization, _super);
  26624. function MergeMeshesOptimization() {
  26625. var _this = this;
  26626. _super.apply(this, arguments);
  26627. this._canBeMerged = function (abstractMesh) {
  26628. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26629. return false;
  26630. }
  26631. var mesh = abstractMesh;
  26632. if (!mesh.isVisible || !mesh.isEnabled()) {
  26633. return false;
  26634. }
  26635. if (mesh.instances.length > 0) {
  26636. return false;
  26637. }
  26638. if (mesh.skeleton || mesh.hasLODLevels) {
  26639. return false;
  26640. }
  26641. return true;
  26642. };
  26643. this.apply = function (scene) {
  26644. var globalPool = scene.meshes.slice(0);
  26645. var globalLength = globalPool.length;
  26646. for (var index = 0; index < globalLength; index++) {
  26647. var currentPool = new Array();
  26648. var current = globalPool[index];
  26649. // Checks
  26650. if (!_this._canBeMerged(current)) {
  26651. continue;
  26652. }
  26653. currentPool.push(current);
  26654. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26655. var otherMesh = globalPool[subIndex];
  26656. if (!_this._canBeMerged(otherMesh)) {
  26657. continue;
  26658. }
  26659. if (otherMesh.material !== current.material) {
  26660. continue;
  26661. }
  26662. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26663. continue;
  26664. }
  26665. currentPool.push(otherMesh);
  26666. globalLength--;
  26667. globalPool.splice(subIndex, 1);
  26668. subIndex--;
  26669. }
  26670. if (currentPool.length < 2) {
  26671. continue;
  26672. }
  26673. // Merge meshes
  26674. BABYLON.Mesh.MergeMeshes(currentPool);
  26675. }
  26676. return true;
  26677. };
  26678. }
  26679. return MergeMeshesOptimization;
  26680. })(SceneOptimization);
  26681. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26682. // Options
  26683. var SceneOptimizerOptions = (function () {
  26684. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26685. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26686. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26687. this.targetFrameRate = targetFrameRate;
  26688. this.trackerDuration = trackerDuration;
  26689. this.optimizations = new Array();
  26690. }
  26691. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26692. var result = new SceneOptimizerOptions(targetFrameRate);
  26693. var priority = 0;
  26694. result.optimizations.push(new MergeMeshesOptimization(priority));
  26695. result.optimizations.push(new ShadowsOptimization(priority));
  26696. result.optimizations.push(new LensFlaresOptimization(priority));
  26697. // Next priority
  26698. priority++;
  26699. result.optimizations.push(new PostProcessesOptimization(priority));
  26700. result.optimizations.push(new ParticlesOptimization(priority));
  26701. // Next priority
  26702. priority++;
  26703. result.optimizations.push(new TextureOptimization(priority, 1024));
  26704. return result;
  26705. };
  26706. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26707. var result = new SceneOptimizerOptions(targetFrameRate);
  26708. var priority = 0;
  26709. result.optimizations.push(new MergeMeshesOptimization(priority));
  26710. result.optimizations.push(new ShadowsOptimization(priority));
  26711. result.optimizations.push(new LensFlaresOptimization(priority));
  26712. // Next priority
  26713. priority++;
  26714. result.optimizations.push(new PostProcessesOptimization(priority));
  26715. result.optimizations.push(new ParticlesOptimization(priority));
  26716. // Next priority
  26717. priority++;
  26718. result.optimizations.push(new TextureOptimization(priority, 512));
  26719. // Next priority
  26720. priority++;
  26721. result.optimizations.push(new RenderTargetsOptimization(priority));
  26722. // Next priority
  26723. priority++;
  26724. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26725. return result;
  26726. };
  26727. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26728. var result = new SceneOptimizerOptions(targetFrameRate);
  26729. var priority = 0;
  26730. result.optimizations.push(new MergeMeshesOptimization(priority));
  26731. result.optimizations.push(new ShadowsOptimization(priority));
  26732. result.optimizations.push(new LensFlaresOptimization(priority));
  26733. // Next priority
  26734. priority++;
  26735. result.optimizations.push(new PostProcessesOptimization(priority));
  26736. result.optimizations.push(new ParticlesOptimization(priority));
  26737. // Next priority
  26738. priority++;
  26739. result.optimizations.push(new TextureOptimization(priority, 256));
  26740. // Next priority
  26741. priority++;
  26742. result.optimizations.push(new RenderTargetsOptimization(priority));
  26743. // Next priority
  26744. priority++;
  26745. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26746. return result;
  26747. };
  26748. return SceneOptimizerOptions;
  26749. })();
  26750. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26751. // Scene optimizer tool
  26752. var SceneOptimizer = (function () {
  26753. function SceneOptimizer() {
  26754. }
  26755. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26756. // TODO: add an epsilon
  26757. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26758. if (onSuccess) {
  26759. onSuccess();
  26760. }
  26761. return;
  26762. }
  26763. // Apply current level of optimizations
  26764. var allDone = true;
  26765. var noOptimizationApplied = true;
  26766. for (var index = 0; index < options.optimizations.length; index++) {
  26767. var optimization = options.optimizations[index];
  26768. if (optimization.priority === currentPriorityLevel) {
  26769. noOptimizationApplied = false;
  26770. allDone = allDone && optimization.apply(scene);
  26771. }
  26772. }
  26773. // If no optimization was applied, this is a failure :(
  26774. if (noOptimizationApplied) {
  26775. if (onFailure) {
  26776. onFailure();
  26777. }
  26778. return;
  26779. }
  26780. // If all optimizations were done, move to next level
  26781. if (allDone) {
  26782. currentPriorityLevel++;
  26783. }
  26784. // Let's the system running for a specific amount of time before checking FPS
  26785. scene.executeWhenReady(function () {
  26786. setTimeout(function () {
  26787. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26788. }, options.trackerDuration);
  26789. });
  26790. };
  26791. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26792. if (!options) {
  26793. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26794. }
  26795. // Let's the system running for a specific amount of time before checking FPS
  26796. scene.executeWhenReady(function () {
  26797. setTimeout(function () {
  26798. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26799. }, options.trackerDuration);
  26800. });
  26801. };
  26802. return SceneOptimizer;
  26803. })();
  26804. BABYLON.SceneOptimizer = SceneOptimizer;
  26805. })(BABYLON || (BABYLON = {}));
  26806. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26807. (function (BABYLON) {
  26808. var Internals;
  26809. (function (Internals) {
  26810. var MeshLODLevel = (function () {
  26811. function MeshLODLevel(distance, mesh) {
  26812. this.distance = distance;
  26813. this.mesh = mesh;
  26814. }
  26815. return MeshLODLevel;
  26816. })();
  26817. Internals.MeshLODLevel = MeshLODLevel;
  26818. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26819. })(BABYLON || (BABYLON = {}));
  26820. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26821. (function (BABYLON) {
  26822. var AudioEngine = (function () {
  26823. function AudioEngine() {
  26824. this.audioContext = null;
  26825. this.canUseWebAudio = false;
  26826. this.WarnedWebAudioUnsupported = false;
  26827. try {
  26828. if (typeof AudioContext !== 'undefined') {
  26829. this.audioContext = new AudioContext();
  26830. this.canUseWebAudio = true;
  26831. }
  26832. else if (typeof webkitAudioContext !== 'undefined') {
  26833. this.audioContext = new webkitAudioContext();
  26834. this.canUseWebAudio = true;
  26835. }
  26836. }
  26837. catch (e) {
  26838. this.canUseWebAudio = false;
  26839. BABYLON.Tools.Error("Web Audio: " + e.message);
  26840. }
  26841. // create a global volume gain node
  26842. if (this.canUseWebAudio) {
  26843. this.masterGain = this.audioContext.createGain();
  26844. this.masterGain.gain.value = 1;
  26845. this.masterGain.connect(this.audioContext.destination);
  26846. }
  26847. }
  26848. AudioEngine.prototype.dispose = function () {
  26849. if (this.canUseWebAudio) {
  26850. if (this._connectedAnalyser) {
  26851. this._connectedAnalyser.stopDebugCanvas();
  26852. this._connectedAnalyser.dispose();
  26853. this.masterGain.disconnect();
  26854. this.masterGain.connect(this.audioContext.destination);
  26855. this._connectedAnalyser = null;
  26856. }
  26857. this.masterGain.gain.value = 1;
  26858. }
  26859. this.WarnedWebAudioUnsupported = false;
  26860. };
  26861. AudioEngine.prototype.getGlobalVolume = function () {
  26862. if (this.canUseWebAudio) {
  26863. return this.masterGain.gain.value;
  26864. }
  26865. else {
  26866. return -1;
  26867. }
  26868. };
  26869. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26870. if (this.canUseWebAudio) {
  26871. this.masterGain.gain.value = newVolume;
  26872. }
  26873. };
  26874. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26875. if (this._connectedAnalyser) {
  26876. this._connectedAnalyser.stopDebugCanvas();
  26877. }
  26878. this._connectedAnalyser = analyser;
  26879. if (this.canUseWebAudio) {
  26880. this.masterGain.disconnect();
  26881. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26882. }
  26883. };
  26884. return AudioEngine;
  26885. })();
  26886. BABYLON.AudioEngine = AudioEngine;
  26887. })(BABYLON || (BABYLON = {}));
  26888. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  26889. (function (BABYLON) {
  26890. var Sound = (function () {
  26891. /**
  26892. * Create a sound and attach it to a scene
  26893. * @param name Name of your sound
  26894. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26895. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26896. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26897. */
  26898. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26899. var _this = this;
  26900. this.autoplay = false;
  26901. this.loop = false;
  26902. this.useCustomAttenuation = false;
  26903. this.spatialSound = false;
  26904. this.refDistance = 1;
  26905. this.rolloffFactor = 1;
  26906. this.maxDistance = 100;
  26907. this.distanceModel = "linear";
  26908. this._panningModel = "equalpower";
  26909. this._playbackRate = 1;
  26910. this._startTime = 0;
  26911. this._startOffset = 0;
  26912. this._position = BABYLON.Vector3.Zero();
  26913. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26914. this._volume = 1;
  26915. this._isLoaded = false;
  26916. this._isReadyToPlay = false;
  26917. this.isPlaying = false;
  26918. this.isPaused = false;
  26919. this._isDirectional = false;
  26920. // Used if you'd like to create a directional sound.
  26921. // If not set, the sound will be omnidirectional
  26922. this._coneInnerAngle = 360;
  26923. this._coneOuterAngle = 360;
  26924. this._coneOuterGain = 0;
  26925. this.name = name;
  26926. this._scene = scene;
  26927. this._readyToPlayCallback = readyToPlayCallback;
  26928. // Default custom attenuation function is a linear attenuation
  26929. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26930. if (currentDistance < maxDistance) {
  26931. return currentVolume * (1 - currentDistance / maxDistance);
  26932. }
  26933. else {
  26934. return 0;
  26935. }
  26936. };
  26937. if (options) {
  26938. this.autoplay = options.autoplay || false;
  26939. this.loop = options.loop || false;
  26940. // if volume === 0, we need another way to check this option
  26941. if (options.volume !== undefined) {
  26942. this._volume = options.volume;
  26943. }
  26944. this.spatialSound = options.spatialSound || false;
  26945. this.maxDistance = options.maxDistance || 100;
  26946. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26947. this.rolloffFactor = options.rolloffFactor || 1;
  26948. this.refDistance = options.refDistance || 1;
  26949. this.distanceModel = options.distanceModel || "linear";
  26950. this._playbackRate = options.playbackRate || 1;
  26951. }
  26952. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26953. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26954. this._soundGain.gain.value = this._volume;
  26955. this._inputAudioNode = this._soundGain;
  26956. this._ouputAudioNode = this._soundGain;
  26957. if (this.spatialSound) {
  26958. this._createSpatialParameters();
  26959. }
  26960. this._scene.mainSoundTrack.AddSound(this);
  26961. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26962. if (urlOrArrayBuffer) {
  26963. // If it's an URL
  26964. if (typeof (urlOrArrayBuffer) === "string") {
  26965. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26966. _this._soundLoaded(data);
  26967. }, null, null, true);
  26968. }
  26969. else {
  26970. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26971. this._soundLoaded(urlOrArrayBuffer);
  26972. }
  26973. else {
  26974. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26975. }
  26976. }
  26977. }
  26978. }
  26979. else {
  26980. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26981. this._scene.mainSoundTrack.AddSound(this);
  26982. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26983. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26984. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26985. }
  26986. if (this._readyToPlayCallback) {
  26987. this._readyToPlayCallback();
  26988. }
  26989. }
  26990. }
  26991. Sound.prototype.dispose = function () {
  26992. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26993. if (this.isPlaying) {
  26994. this.stop();
  26995. }
  26996. this._isReadyToPlay = false;
  26997. if (this.soundTrackId === -1) {
  26998. this._scene.mainSoundTrack.RemoveSound(this);
  26999. }
  27000. else {
  27001. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27002. }
  27003. if (this._soundGain) {
  27004. this._soundGain.disconnect();
  27005. this._soundGain = null;
  27006. }
  27007. if (this._soundPanner) {
  27008. this._soundPanner.disconnect();
  27009. this._soundPanner = null;
  27010. }
  27011. if (this._soundSource) {
  27012. this._soundSource.disconnect();
  27013. this._soundSource = null;
  27014. }
  27015. this._audioBuffer = null;
  27016. if (this._connectedMesh) {
  27017. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27018. this._connectedMesh = null;
  27019. }
  27020. }
  27021. };
  27022. Sound.prototype._soundLoaded = function (audioData) {
  27023. var _this = this;
  27024. this._isLoaded = true;
  27025. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27026. _this._audioBuffer = buffer;
  27027. _this._isReadyToPlay = true;
  27028. if (_this.autoplay) {
  27029. _this.play();
  27030. }
  27031. if (_this._readyToPlayCallback) {
  27032. _this._readyToPlayCallback();
  27033. }
  27034. }, function (error) {
  27035. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27036. });
  27037. };
  27038. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27039. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27040. this._audioBuffer = audioBuffer;
  27041. this._isReadyToPlay = true;
  27042. }
  27043. };
  27044. Sound.prototype.updateOptions = function (options) {
  27045. if (options) {
  27046. this.loop = options.loop || this.loop;
  27047. this.maxDistance = options.maxDistance || this.maxDistance;
  27048. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27049. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27050. this.refDistance = options.refDistance || this.refDistance;
  27051. this.distanceModel = options.distanceModel || this.distanceModel;
  27052. this._playbackRate = options.playbackRate || this._playbackRate;
  27053. }
  27054. };
  27055. Sound.prototype._createSpatialParameters = function () {
  27056. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27057. if (this._scene.headphone) {
  27058. this._panningModel = "HRTF";
  27059. }
  27060. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27061. if (this.useCustomAttenuation) {
  27062. // Tricks to disable in a way embedded Web Audio attenuation
  27063. this._soundPanner.distanceModel = "linear";
  27064. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27065. this._soundPanner.refDistance = 1;
  27066. this._soundPanner.rolloffFactor = 1;
  27067. this._soundPanner.panningModel = this._panningModel;
  27068. }
  27069. else {
  27070. this._soundPanner.distanceModel = this.distanceModel;
  27071. this._soundPanner.maxDistance = this.maxDistance;
  27072. this._soundPanner.refDistance = this.refDistance;
  27073. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27074. this._soundPanner.panningModel = this._panningModel;
  27075. }
  27076. this._soundPanner.connect(this._ouputAudioNode);
  27077. this._inputAudioNode = this._soundPanner;
  27078. }
  27079. };
  27080. Sound.prototype.switchPanningModelToHRTF = function () {
  27081. this._panningModel = "HRTF";
  27082. this._switchPanningModel();
  27083. };
  27084. Sound.prototype.switchPanningModelToEqualPower = function () {
  27085. this._panningModel = "equalpower";
  27086. this._switchPanningModel();
  27087. };
  27088. Sound.prototype._switchPanningModel = function () {
  27089. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27090. this._soundPanner.panningModel = this._panningModel;
  27091. }
  27092. };
  27093. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27094. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27095. this._ouputAudioNode.disconnect();
  27096. this._ouputAudioNode.connect(soundTrackAudioNode);
  27097. }
  27098. };
  27099. /**
  27100. * Transform this sound into a directional source
  27101. * @param coneInnerAngle Size of the inner cone in degree
  27102. * @param coneOuterAngle Size of the outer cone in degree
  27103. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27104. */
  27105. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27106. if (coneOuterAngle < coneInnerAngle) {
  27107. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27108. return;
  27109. }
  27110. this._coneInnerAngle = coneInnerAngle;
  27111. this._coneOuterAngle = coneOuterAngle;
  27112. this._coneOuterGain = coneOuterGain;
  27113. this._isDirectional = true;
  27114. if (this.isPlaying && this.loop) {
  27115. this.stop();
  27116. this.play();
  27117. }
  27118. };
  27119. Sound.prototype.setPosition = function (newPosition) {
  27120. this._position = newPosition;
  27121. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27122. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27123. }
  27124. };
  27125. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27126. this._localDirection = newLocalDirection;
  27127. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27128. this._updateDirection();
  27129. }
  27130. };
  27131. Sound.prototype._updateDirection = function () {
  27132. var mat = this._connectedMesh.getWorldMatrix();
  27133. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27134. direction.normalize();
  27135. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27136. };
  27137. Sound.prototype.updateDistanceFromListener = function () {
  27138. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27139. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27140. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27141. }
  27142. };
  27143. Sound.prototype.setAttenuationFunction = function (callback) {
  27144. this._customAttenuationFunction = callback;
  27145. };
  27146. /**
  27147. * Play the sound
  27148. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27149. */
  27150. Sound.prototype.play = function (time) {
  27151. var _this = this;
  27152. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27153. try {
  27154. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27155. if (!this._soundSource) {
  27156. if (this.spatialSound) {
  27157. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27158. if (this._isDirectional) {
  27159. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27160. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27161. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27162. if (this._connectedMesh) {
  27163. this._updateDirection();
  27164. }
  27165. else {
  27166. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27167. }
  27168. }
  27169. }
  27170. }
  27171. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27172. this._soundSource.buffer = this._audioBuffer;
  27173. this._soundSource.connect(this._inputAudioNode);
  27174. this._soundSource.loop = this.loop;
  27175. this._soundSource.playbackRate.value = this._playbackRate;
  27176. this._startTime = startTime;
  27177. this._soundSource.onended = function () {
  27178. _this._onended();
  27179. };
  27180. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27181. this.isPlaying = true;
  27182. this.isPaused = false;
  27183. }
  27184. catch (ex) {
  27185. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27186. }
  27187. }
  27188. };
  27189. Sound.prototype._onended = function () {
  27190. this.isPlaying = false;
  27191. if (this.onended) {
  27192. this.onended();
  27193. }
  27194. };
  27195. /**
  27196. * Stop the sound
  27197. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27198. */
  27199. Sound.prototype.stop = function (time) {
  27200. if (this.isPlaying) {
  27201. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27202. this._soundSource.stop(stopTime);
  27203. this.isPlaying = false;
  27204. }
  27205. };
  27206. Sound.prototype.pause = function () {
  27207. if (this.isPlaying) {
  27208. this.stop(0);
  27209. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27210. this.isPaused = true;
  27211. }
  27212. };
  27213. Sound.prototype.setVolume = function (newVolume, time) {
  27214. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27215. if (time) {
  27216. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27217. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27218. }
  27219. else {
  27220. this._soundGain.gain.value = newVolume;
  27221. }
  27222. }
  27223. this._volume = newVolume;
  27224. };
  27225. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27226. this._playbackRate = newPlaybackRate;
  27227. if (this.isPlaying) {
  27228. this._soundSource.playbackRate.value = this._playbackRate;
  27229. }
  27230. };
  27231. Sound.prototype.getVolume = function () {
  27232. return this._volume;
  27233. };
  27234. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27235. var _this = this;
  27236. this._connectedMesh = meshToConnectTo;
  27237. if (!this.spatialSound) {
  27238. this._createSpatialParameters();
  27239. this.spatialSound = true;
  27240. if (this.isPlaying && this.loop) {
  27241. this.stop();
  27242. this.play();
  27243. }
  27244. }
  27245. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27246. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27247. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27248. };
  27249. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27250. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27251. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27252. this._updateDirection();
  27253. }
  27254. };
  27255. return Sound;
  27256. })();
  27257. BABYLON.Sound = Sound;
  27258. })(BABYLON || (BABYLON = {}));
  27259. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27260. (function (BABYLON) {
  27261. var SoundTrack = (function () {
  27262. function SoundTrack(scene, options) {
  27263. this.id = -1;
  27264. this._isMainTrack = false;
  27265. this._scene = scene;
  27266. this._audioEngine = BABYLON.Engine.audioEngine;
  27267. this.soundCollection = new Array();
  27268. if (this._audioEngine.canUseWebAudio) {
  27269. this._trackGain = this._audioEngine.audioContext.createGain();
  27270. this._trackGain.connect(this._audioEngine.masterGain);
  27271. if (options) {
  27272. if (options.volume) {
  27273. this._trackGain.gain.value = options.volume;
  27274. }
  27275. if (options.mainTrack) {
  27276. this._isMainTrack = options.mainTrack;
  27277. }
  27278. }
  27279. }
  27280. if (!this._isMainTrack) {
  27281. this._scene.soundTracks.push(this);
  27282. this.id = this._scene.soundTracks.length - 1;
  27283. }
  27284. }
  27285. SoundTrack.prototype.dispose = function () {
  27286. if (this._audioEngine.canUseWebAudio) {
  27287. if (this._connectedAnalyser) {
  27288. this._connectedAnalyser.stopDebugCanvas();
  27289. }
  27290. while (this.soundCollection.length) {
  27291. this.soundCollection[0].dispose();
  27292. }
  27293. this._trackGain.disconnect();
  27294. this._trackGain = null;
  27295. }
  27296. };
  27297. SoundTrack.prototype.AddSound = function (sound) {
  27298. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27299. sound.connectToSoundTrackAudioNode(this._trackGain);
  27300. }
  27301. if (sound.soundTrackId) {
  27302. if (sound.soundTrackId === -1) {
  27303. this._scene.mainSoundTrack.RemoveSound(sound);
  27304. }
  27305. else {
  27306. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27307. }
  27308. }
  27309. this.soundCollection.push(sound);
  27310. sound.soundTrackId = this.id;
  27311. };
  27312. SoundTrack.prototype.RemoveSound = function (sound) {
  27313. var index = this.soundCollection.indexOf(sound);
  27314. if (index !== -1) {
  27315. this.soundCollection.splice(index, 1);
  27316. }
  27317. };
  27318. SoundTrack.prototype.setVolume = function (newVolume) {
  27319. if (this._audioEngine.canUseWebAudio) {
  27320. this._trackGain.gain.value = newVolume;
  27321. }
  27322. };
  27323. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27324. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27325. for (var i = 0; i < this.soundCollection.length; i++) {
  27326. this.soundCollection[i].switchPanningModelToHRTF();
  27327. }
  27328. }
  27329. };
  27330. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27331. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27332. for (var i = 0; i < this.soundCollection.length; i++) {
  27333. this.soundCollection[i].switchPanningModelToEqualPower();
  27334. }
  27335. }
  27336. };
  27337. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27338. if (this._connectedAnalyser) {
  27339. this._connectedAnalyser.stopDebugCanvas();
  27340. }
  27341. this._connectedAnalyser = analyser;
  27342. if (this._audioEngine.canUseWebAudio) {
  27343. this._trackGain.disconnect();
  27344. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27345. }
  27346. };
  27347. return SoundTrack;
  27348. })();
  27349. BABYLON.SoundTrack = SoundTrack;
  27350. })(BABYLON || (BABYLON = {}));
  27351. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27352. (function (BABYLON) {
  27353. var DebugLayer = (function () {
  27354. function DebugLayer(scene) {
  27355. var _this = this;
  27356. this._transformationMatrix = BABYLON.Matrix.Identity();
  27357. this._enabled = false;
  27358. this._labelsEnabled = false;
  27359. this._displayStatistics = true;
  27360. this._displayTree = false;
  27361. this._displayLogs = false;
  27362. this._identityMatrix = BABYLON.Matrix.Identity();
  27363. this.axisRatio = 0.02;
  27364. this.accentColor = "orange";
  27365. this._scene = scene;
  27366. this._syncPositions = function () {
  27367. var engine = _this._scene.getEngine();
  27368. var canvasRect = engine.getRenderingCanvasClientRect();
  27369. if (_this._showUI) {
  27370. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27371. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27372. _this._statsDiv.style.width = "400px";
  27373. _this._statsDiv.style.height = "auto";
  27374. _this._statsSubsetDiv.style.maxHeight = "240px";
  27375. _this._optionsDiv.style.left = "0px";
  27376. _this._optionsDiv.style.top = "10px";
  27377. _this._optionsDiv.style.width = "200px";
  27378. _this._optionsDiv.style.height = "auto";
  27379. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27380. _this._logDiv.style.left = "0px";
  27381. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27382. _this._logDiv.style.width = "600px";
  27383. _this._logDiv.style.height = "160px";
  27384. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27385. _this._treeDiv.style.top = "10px";
  27386. _this._treeDiv.style.width = "300px";
  27387. _this._treeDiv.style.height = "auto";
  27388. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27389. }
  27390. _this._globalDiv.style.left = canvasRect.left + "px";
  27391. _this._globalDiv.style.top = canvasRect.top + "px";
  27392. _this._drawingCanvas.style.left = "0px";
  27393. _this._drawingCanvas.style.top = "0px";
  27394. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27395. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27396. var devicePixelRatio = window.devicePixelRatio || 1;
  27397. var context = _this._drawingContext;
  27398. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27399. _this._ratio = devicePixelRatio / backingStoreRatio;
  27400. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27401. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27402. };
  27403. this._onCanvasClick = function (evt) {
  27404. _this._clickPosition = {
  27405. x: evt.clientX * _this._ratio,
  27406. y: evt.clientY * _this._ratio
  27407. };
  27408. };
  27409. this._syncUI = function () {
  27410. if (_this._showUI) {
  27411. if (_this._displayStatistics) {
  27412. _this._displayStats();
  27413. _this._statsDiv.style.display = "";
  27414. }
  27415. else {
  27416. _this._statsDiv.style.display = "none";
  27417. }
  27418. if (_this._displayLogs) {
  27419. _this._logDiv.style.display = "";
  27420. }
  27421. else {
  27422. _this._logDiv.style.display = "none";
  27423. }
  27424. if (_this._displayTree) {
  27425. _this._treeDiv.style.display = "";
  27426. if (_this._needToRefreshMeshesTree) {
  27427. _this._needToRefreshMeshesTree = false;
  27428. _this._refreshMeshesTreeContent();
  27429. }
  27430. }
  27431. else {
  27432. _this._treeDiv.style.display = "none";
  27433. }
  27434. }
  27435. };
  27436. this._syncData = function () {
  27437. if (_this._labelsEnabled || !_this._showUI) {
  27438. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27439. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27440. var engine = _this._scene.getEngine();
  27441. var viewport = _this._camera.viewport;
  27442. var globalViewport = viewport.toGlobal(engine);
  27443. // Meshes
  27444. var meshes = _this._camera.getActiveMeshes();
  27445. for (var index = 0; index < meshes.length; index++) {
  27446. var mesh = meshes.data[index];
  27447. var position = mesh.getBoundingInfo().boundingSphere.center;
  27448. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27449. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27450. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27451. }
  27452. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27453. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27454. mesh.renderOverlay = !mesh.renderOverlay;
  27455. }, function () {
  27456. return mesh.renderOverlay ? 'red' : 'black';
  27457. });
  27458. }
  27459. }
  27460. // Cameras
  27461. var cameras = _this._scene.cameras;
  27462. for (index = 0; index < cameras.length; index++) {
  27463. var camera = cameras[index];
  27464. if (camera === _this._camera) {
  27465. continue;
  27466. }
  27467. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27468. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27469. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27470. _this._camera.detachControl(engine.getRenderingCanvas());
  27471. _this._camera = camera;
  27472. _this._camera.attachControl(engine.getRenderingCanvas());
  27473. }, function () {
  27474. return "purple";
  27475. });
  27476. }
  27477. }
  27478. // Lights
  27479. var lights = _this._scene.lights;
  27480. for (index = 0; index < lights.length; index++) {
  27481. var light = lights[index];
  27482. if (light.position) {
  27483. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27484. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27485. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27486. light.setEnabled(!light.isEnabled());
  27487. }, function () {
  27488. return light.isEnabled() ? "orange" : "gray";
  27489. });
  27490. }
  27491. }
  27492. }
  27493. }
  27494. _this._clickPosition = undefined;
  27495. };
  27496. }
  27497. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27498. while (this._treeSubsetDiv.hasChildNodes()) {
  27499. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27500. }
  27501. // Add meshes
  27502. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27503. sortedArray.sort(function (a, b) {
  27504. if (a.name === b.name) {
  27505. return 0;
  27506. }
  27507. return (a.name > b.name) ? 1 : -1;
  27508. });
  27509. for (var index = 0; index < sortedArray.length; index++) {
  27510. var mesh = sortedArray[index];
  27511. if (!mesh.isEnabled()) {
  27512. continue;
  27513. }
  27514. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27515. m.isVisible = element.checked;
  27516. }, mesh);
  27517. }
  27518. };
  27519. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27520. this._drawingContext.beginPath();
  27521. this._drawingContext.moveTo(zero.x, zero.y);
  27522. this._drawingContext.lineTo(unit.x, unit.y);
  27523. this._drawingContext.strokeStyle = color;
  27524. this._drawingContext.lineWidth = 4;
  27525. this._drawingContext.stroke();
  27526. this._drawingContext.font = "normal 14px Segoe UI";
  27527. this._drawingContext.fillStyle = color;
  27528. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27529. };
  27530. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27531. var position = mesh.getBoundingInfo().boundingSphere.center;
  27532. var worldMatrix = mesh.getWorldMatrix();
  27533. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27534. var unit = (unprojectedVector.subtract(position)).length();
  27535. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27536. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27537. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27538. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27539. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27540. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27541. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27542. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27543. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27544. };
  27545. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27546. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27547. this._drawingContext.font = "normal 12px Segoe UI";
  27548. var textMetrics = this._drawingContext.measureText(text);
  27549. var centerX = projectedPosition.x - textMetrics.width / 2;
  27550. var centerY = projectedPosition.y;
  27551. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27552. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27553. onClick();
  27554. }
  27555. this._drawingContext.beginPath();
  27556. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27557. this._drawingContext.fillStyle = getFillStyle();
  27558. this._drawingContext.globalAlpha = 0.5;
  27559. this._drawingContext.fill();
  27560. this._drawingContext.globalAlpha = 1.0;
  27561. this._drawingContext.strokeStyle = '#FFFFFF';
  27562. this._drawingContext.lineWidth = 1;
  27563. this._drawingContext.stroke();
  27564. this._drawingContext.fillStyle = "#FFFFFF";
  27565. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27566. this._drawingContext.beginPath();
  27567. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27568. this._drawingContext.fill();
  27569. }
  27570. };
  27571. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27572. if (!this._clickPosition) {
  27573. return false;
  27574. }
  27575. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27576. return false;
  27577. }
  27578. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27579. return false;
  27580. }
  27581. return true;
  27582. };
  27583. DebugLayer.prototype.isVisible = function () {
  27584. return this._enabled;
  27585. };
  27586. DebugLayer.prototype.hide = function () {
  27587. if (!this._enabled) {
  27588. return;
  27589. }
  27590. this._enabled = false;
  27591. var engine = this._scene.getEngine();
  27592. this._scene.unregisterBeforeRender(this._syncData);
  27593. this._scene.unregisterAfterRender(this._syncUI);
  27594. document.body.removeChild(this._globalDiv);
  27595. window.removeEventListener("resize", this._syncPositions);
  27596. this._scene.forceShowBoundingBoxes = false;
  27597. this._scene.forceWireframe = false;
  27598. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27599. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27600. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27601. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27602. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27603. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27604. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27605. this._scene.shadowsEnabled = true;
  27606. this._scene.particlesEnabled = true;
  27607. this._scene.postProcessesEnabled = true;
  27608. this._scene.collisionsEnabled = true;
  27609. this._scene.lightsEnabled = true;
  27610. this._scene.texturesEnabled = true;
  27611. this._scene.lensFlaresEnabled = true;
  27612. this._scene.proceduralTexturesEnabled = true;
  27613. this._scene.renderTargetsEnabled = true;
  27614. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27615. };
  27616. DebugLayer.prototype.show = function (showUI, camera) {
  27617. if (showUI === void 0) { showUI = true; }
  27618. if (camera === void 0) { camera = null; }
  27619. if (this._enabled) {
  27620. return;
  27621. }
  27622. if (camera) {
  27623. this._camera = camera;
  27624. }
  27625. else {
  27626. this._camera = this._scene.activeCamera;
  27627. }
  27628. this._enabled = true;
  27629. this._showUI = showUI;
  27630. var engine = this._scene.getEngine();
  27631. this._globalDiv = document.createElement("div");
  27632. document.body.appendChild(this._globalDiv);
  27633. this._generateDOMelements();
  27634. window.addEventListener("resize", this._syncPositions);
  27635. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27636. this._syncPositions();
  27637. this._scene.registerBeforeRender(this._syncData);
  27638. this._scene.registerAfterRender(this._syncUI);
  27639. };
  27640. DebugLayer.prototype._clearLabels = function () {
  27641. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27642. for (var index = 0; index < this._scene.meshes.length; index++) {
  27643. var mesh = this._scene.meshes[index];
  27644. mesh.renderOverlay = false;
  27645. }
  27646. };
  27647. DebugLayer.prototype._generateheader = function (root, text) {
  27648. var header = document.createElement("div");
  27649. header.innerHTML = text + "&nbsp;";
  27650. header.style.textAlign = "right";
  27651. header.style.width = "100%";
  27652. header.style.color = "white";
  27653. header.style.backgroundColor = "Black";
  27654. header.style.padding = "5px 5px 4px 0px";
  27655. header.style.marginLeft = "-5px";
  27656. header.style.fontWeight = "bold";
  27657. root.appendChild(header);
  27658. };
  27659. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27660. var label = document.createElement("label");
  27661. label.innerHTML = title;
  27662. label.style.color = color;
  27663. root.appendChild(label);
  27664. root.appendChild(document.createElement("br"));
  27665. };
  27666. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27667. if (tag === void 0) { tag = null; }
  27668. var label = document.createElement("label");
  27669. var boundingBoxesCheckbox = document.createElement("input");
  27670. boundingBoxesCheckbox.type = "checkbox";
  27671. boundingBoxesCheckbox.checked = initialState;
  27672. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27673. task(evt.target, tag);
  27674. });
  27675. label.appendChild(boundingBoxesCheckbox);
  27676. var container = document.createElement("span");
  27677. var leftPart = document.createElement("span");
  27678. var rightPart = document.createElement("span");
  27679. rightPart.style.cssFloat = "right";
  27680. leftPart.innerHTML = leftTitle;
  27681. rightPart.innerHTML = rightTitle;
  27682. rightPart.style.fontSize = "12px";
  27683. rightPart.style.maxWidth = "200px";
  27684. container.appendChild(leftPart);
  27685. container.appendChild(rightPart);
  27686. label.appendChild(container);
  27687. root.appendChild(label);
  27688. root.appendChild(document.createElement("br"));
  27689. };
  27690. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27691. if (tag === void 0) { tag = null; }
  27692. var label = document.createElement("label");
  27693. var checkBox = document.createElement("input");
  27694. checkBox.type = "checkbox";
  27695. checkBox.checked = initialState;
  27696. checkBox.addEventListener("change", function (evt) {
  27697. task(evt.target, tag);
  27698. });
  27699. label.appendChild(checkBox);
  27700. label.appendChild(document.createTextNode(title));
  27701. root.appendChild(label);
  27702. root.appendChild(document.createElement("br"));
  27703. };
  27704. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27705. if (tag === void 0) { tag = null; }
  27706. var button = document.createElement("button");
  27707. button.innerHTML = title;
  27708. button.style.height = "24px";
  27709. button.style.color = "#444444";
  27710. button.style.border = "1px solid white";
  27711. button.className = "debugLayerButton";
  27712. button.addEventListener("click", function (evt) {
  27713. task(evt.target, tag);
  27714. });
  27715. root.appendChild(button);
  27716. root.appendChild(document.createElement("br"));
  27717. };
  27718. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27719. if (tag === void 0) { tag = null; }
  27720. var label = document.createElement("label");
  27721. var boundingBoxesRadio = document.createElement("input");
  27722. boundingBoxesRadio.type = "radio";
  27723. boundingBoxesRadio.name = name;
  27724. boundingBoxesRadio.checked = initialState;
  27725. boundingBoxesRadio.addEventListener("change", function (evt) {
  27726. task(evt.target, tag);
  27727. });
  27728. label.appendChild(boundingBoxesRadio);
  27729. label.appendChild(document.createTextNode(title));
  27730. root.appendChild(label);
  27731. root.appendChild(document.createElement("br"));
  27732. };
  27733. DebugLayer.prototype._generateDOMelements = function () {
  27734. var _this = this;
  27735. this._globalDiv.id = "DebugLayer";
  27736. this._globalDiv.style.position = "absolute";
  27737. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27738. this._globalDiv.style.fontSize = "14px";
  27739. this._globalDiv.style.color = "white";
  27740. // Drawing canvas
  27741. this._drawingCanvas = document.createElement("canvas");
  27742. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27743. this._drawingCanvas.style.position = "absolute";
  27744. this._drawingCanvas.style.pointerEvents = "none";
  27745. this._drawingContext = this._drawingCanvas.getContext("2d");
  27746. this._globalDiv.appendChild(this._drawingCanvas);
  27747. if (this._showUI) {
  27748. var background = "rgba(128, 128, 128, 0.4)";
  27749. var border = "rgb(180, 180, 180) solid 1px";
  27750. // Stats
  27751. this._statsDiv = document.createElement("div");
  27752. this._statsDiv.id = "DebugLayerStats";
  27753. this._statsDiv.style.border = border;
  27754. this._statsDiv.style.position = "absolute";
  27755. this._statsDiv.style.background = background;
  27756. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27757. this._generateheader(this._statsDiv, "STATISTICS");
  27758. this._statsSubsetDiv = document.createElement("div");
  27759. this._statsSubsetDiv.style.paddingTop = "5px";
  27760. this._statsSubsetDiv.style.paddingBottom = "5px";
  27761. this._statsSubsetDiv.style.overflowY = "auto";
  27762. this._statsDiv.appendChild(this._statsSubsetDiv);
  27763. // Tree
  27764. this._treeDiv = document.createElement("div");
  27765. this._treeDiv.id = "DebugLayerTree";
  27766. this._treeDiv.style.border = border;
  27767. this._treeDiv.style.position = "absolute";
  27768. this._treeDiv.style.background = background;
  27769. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27770. this._treeDiv.style.display = "none";
  27771. this._generateheader(this._treeDiv, "MESHES TREE");
  27772. this._treeSubsetDiv = document.createElement("div");
  27773. this._treeSubsetDiv.style.paddingTop = "5px";
  27774. this._treeSubsetDiv.style.paddingRight = "5px";
  27775. this._treeSubsetDiv.style.overflowY = "auto";
  27776. this._treeSubsetDiv.style.maxHeight = "300px";
  27777. this._treeDiv.appendChild(this._treeSubsetDiv);
  27778. this._needToRefreshMeshesTree = true;
  27779. // Logs
  27780. this._logDiv = document.createElement("div");
  27781. this._logDiv.style.border = border;
  27782. this._logDiv.id = "DebugLayerLogs";
  27783. this._logDiv.style.position = "absolute";
  27784. this._logDiv.style.background = background;
  27785. this._logDiv.style.padding = "0px 0px 0px 5px";
  27786. this._logDiv.style.display = "none";
  27787. this._generateheader(this._logDiv, "LOGS");
  27788. this._logSubsetDiv = document.createElement("div");
  27789. this._logSubsetDiv.style.height = "127px";
  27790. this._logSubsetDiv.style.paddingTop = "5px";
  27791. this._logSubsetDiv.style.overflowY = "auto";
  27792. this._logSubsetDiv.style.fontSize = "12px";
  27793. this._logSubsetDiv.style.fontFamily = "consolas";
  27794. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27795. this._logDiv.appendChild(this._logSubsetDiv);
  27796. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27797. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27798. };
  27799. // Options
  27800. this._optionsDiv = document.createElement("div");
  27801. this._optionsDiv.id = "DebugLayerOptions";
  27802. this._optionsDiv.style.border = border;
  27803. this._optionsDiv.style.position = "absolute";
  27804. this._optionsDiv.style.background = background;
  27805. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27806. this._optionsDiv.style.overflowY = "auto";
  27807. this._generateheader(this._optionsDiv, "OPTIONS");
  27808. this._optionsSubsetDiv = document.createElement("div");
  27809. this._optionsSubsetDiv.style.paddingTop = "5px";
  27810. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27811. this._optionsSubsetDiv.style.overflowY = "auto";
  27812. this._optionsSubsetDiv.style.maxHeight = "200px";
  27813. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27814. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27815. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27816. _this._displayStatistics = element.checked;
  27817. });
  27818. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27819. _this._displayLogs = element.checked;
  27820. });
  27821. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27822. _this._displayTree = element.checked;
  27823. _this._needToRefreshMeshesTree = true;
  27824. });
  27825. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27826. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27827. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27828. _this._scene.forceShowBoundingBoxes = element.checked;
  27829. });
  27830. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27831. _this._labelsEnabled = element.checked;
  27832. if (!_this._labelsEnabled) {
  27833. _this._clearLabels();
  27834. }
  27835. });
  27836. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27837. if (element.checked) {
  27838. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27839. }
  27840. else {
  27841. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27842. }
  27843. });
  27844. ;
  27845. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27846. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27847. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27848. if (element.checked) {
  27849. _this._scene.forceWireframe = false;
  27850. _this._scene.forcePointsCloud = false;
  27851. }
  27852. });
  27853. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27854. if (element.checked) {
  27855. _this._scene.forceWireframe = true;
  27856. _this._scene.forcePointsCloud = false;
  27857. }
  27858. });
  27859. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27860. if (element.checked) {
  27861. _this._scene.forceWireframe = false;
  27862. _this._scene.forcePointsCloud = true;
  27863. }
  27864. });
  27865. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27866. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27867. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27868. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27869. });
  27870. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27871. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27872. });
  27873. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27874. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27875. });
  27876. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27877. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27878. });
  27879. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27880. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27881. });
  27882. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27883. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27884. });
  27885. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27886. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27887. });
  27888. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27889. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27890. });
  27891. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27892. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27893. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27894. _this._scene.animationsEnabled = element.checked;
  27895. });
  27896. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27897. _this._scene.collisionsEnabled = element.checked;
  27898. });
  27899. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27900. _this._scene.fogEnabled = element.checked;
  27901. });
  27902. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27903. _this._scene.lensFlaresEnabled = element.checked;
  27904. });
  27905. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27906. _this._scene.lightsEnabled = element.checked;
  27907. });
  27908. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27909. _this._scene.particlesEnabled = element.checked;
  27910. });
  27911. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27912. _this._scene.postProcessesEnabled = element.checked;
  27913. });
  27914. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27915. _this._scene.proceduralTexturesEnabled = element.checked;
  27916. });
  27917. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27918. _this._scene.renderTargetsEnabled = element.checked;
  27919. });
  27920. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27921. _this._scene.shadowsEnabled = element.checked;
  27922. });
  27923. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27924. _this._scene.skeletonsEnabled = element.checked;
  27925. });
  27926. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27927. _this._scene.spritesEnabled = element.checked;
  27928. });
  27929. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27930. _this._scene.texturesEnabled = element.checked;
  27931. });
  27932. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27933. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27934. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27935. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27936. if (element.checked) {
  27937. _this._scene.headphone = true;
  27938. }
  27939. });
  27940. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27941. if (element.checked) {
  27942. _this._scene.headphone = false;
  27943. }
  27944. });
  27945. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27946. _this._scene.audioEnabled = !element.checked;
  27947. });
  27948. }
  27949. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27950. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27951. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27952. _this._scene.dumpNextRenderTargets = true;
  27953. });
  27954. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27955. this._globalDiv.appendChild(this._statsDiv);
  27956. this._globalDiv.appendChild(this._logDiv);
  27957. this._globalDiv.appendChild(this._optionsDiv);
  27958. this._globalDiv.appendChild(this._treeDiv);
  27959. }
  27960. };
  27961. DebugLayer.prototype._displayStats = function () {
  27962. var scene = this._scene;
  27963. var engine = scene.getEngine();
  27964. var glInfo = engine.getGlInfo();
  27965. 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>";
  27966. if (this.customStatsFunction) {
  27967. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27968. }
  27969. };
  27970. return DebugLayer;
  27971. })();
  27972. BABYLON.DebugLayer = DebugLayer;
  27973. })(BABYLON || (BABYLON = {}));
  27974. //# sourceMappingURL=babylon.debugLayer.js.map
  27975. var BABYLON;
  27976. (function (BABYLON) {
  27977. var RawTexture = (function (_super) {
  27978. __extends(RawTexture, _super);
  27979. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27980. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27981. if (invertY === void 0) { invertY = false; }
  27982. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27983. _super.call(this, null, scene, !generateMipMaps, invertY);
  27984. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27985. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27986. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27987. }
  27988. // Statics
  27989. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27990. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27991. if (invertY === void 0) { invertY = false; }
  27992. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27993. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27994. };
  27995. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27996. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27997. if (invertY === void 0) { invertY = false; }
  27998. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27999. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28000. };
  28001. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28002. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28003. if (invertY === void 0) { invertY = false; }
  28004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28005. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28006. };
  28007. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28008. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28009. if (invertY === void 0) { invertY = false; }
  28010. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28011. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28012. };
  28013. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28014. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28015. if (invertY === void 0) { invertY = false; }
  28016. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28017. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28018. };
  28019. return RawTexture;
  28020. })(BABYLON.Texture);
  28021. BABYLON.RawTexture = RawTexture;
  28022. })(BABYLON || (BABYLON = {}));
  28023. //# sourceMappingURL=babylon.rawTexture.js.map
  28024. var BABYLON;
  28025. (function (BABYLON) {
  28026. var IndexedVector2 = (function (_super) {
  28027. __extends(IndexedVector2, _super);
  28028. function IndexedVector2(original, index) {
  28029. _super.call(this, original.x, original.y);
  28030. this.index = index;
  28031. }
  28032. return IndexedVector2;
  28033. })(BABYLON.Vector2);
  28034. var PolygonPoints = (function () {
  28035. function PolygonPoints() {
  28036. this.elements = new Array();
  28037. }
  28038. PolygonPoints.prototype.add = function (originalPoints) {
  28039. var _this = this;
  28040. var result = new Array();
  28041. originalPoints.forEach(function (point) {
  28042. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28043. var newPoint = new IndexedVector2(point, _this.elements.length);
  28044. result.push(newPoint);
  28045. _this.elements.push(newPoint);
  28046. }
  28047. });
  28048. return result;
  28049. };
  28050. PolygonPoints.prototype.computeBounds = function () {
  28051. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28052. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28053. this.elements.forEach(function (point) {
  28054. // x
  28055. if (point.x < lmin.x) {
  28056. lmin.x = point.x;
  28057. }
  28058. else if (point.x > lmax.x) {
  28059. lmax.x = point.x;
  28060. }
  28061. // y
  28062. if (point.y < lmin.y) {
  28063. lmin.y = point.y;
  28064. }
  28065. else if (point.y > lmax.y) {
  28066. lmax.y = point.y;
  28067. }
  28068. });
  28069. return {
  28070. min: lmin,
  28071. max: lmax,
  28072. width: lmax.x - lmin.x,
  28073. height: lmax.y - lmin.y
  28074. };
  28075. };
  28076. return PolygonPoints;
  28077. })();
  28078. var Polygon = (function () {
  28079. function Polygon() {
  28080. }
  28081. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28082. return [
  28083. new BABYLON.Vector2(xmin, ymin),
  28084. new BABYLON.Vector2(xmax, ymin),
  28085. new BABYLON.Vector2(xmax, ymax),
  28086. new BABYLON.Vector2(xmin, ymax)
  28087. ];
  28088. };
  28089. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28090. if (cx === void 0) { cx = 0; }
  28091. if (cy === void 0) { cy = 0; }
  28092. if (numberOfSides === void 0) { numberOfSides = 32; }
  28093. var result = new Array();
  28094. var angle = 0;
  28095. var increment = (Math.PI * 2) / numberOfSides;
  28096. for (var i = 0; i < numberOfSides; i++) {
  28097. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28098. angle -= increment;
  28099. }
  28100. return result;
  28101. };
  28102. Polygon.Parse = function (input) {
  28103. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28104. var i, result = [];
  28105. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28106. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28107. }
  28108. return result;
  28109. };
  28110. Polygon.StartingAt = function (x, y) {
  28111. return BABYLON.Path2.StartingAt(x, y);
  28112. };
  28113. return Polygon;
  28114. })();
  28115. BABYLON.Polygon = Polygon;
  28116. var PolygonMeshBuilder = (function () {
  28117. function PolygonMeshBuilder(name, contours, scene) {
  28118. this._points = new PolygonPoints();
  28119. if (!("poly2tri" in window)) {
  28120. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28121. }
  28122. this._name = name;
  28123. this._scene = scene;
  28124. var points;
  28125. if (contours instanceof BABYLON.Path2) {
  28126. points = contours.getPoints();
  28127. }
  28128. else {
  28129. points = contours;
  28130. }
  28131. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28132. }
  28133. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28134. this._swctx.addHole(this._points.add(hole));
  28135. return this;
  28136. };
  28137. PolygonMeshBuilder.prototype.build = function (updatable) {
  28138. if (updatable === void 0) { updatable = false; }
  28139. var result = new BABYLON.Mesh(this._name, this._scene);
  28140. var normals = [];
  28141. var positions = [];
  28142. var uvs = [];
  28143. var bounds = this._points.computeBounds();
  28144. this._points.elements.forEach(function (p) {
  28145. normals.push(0, 1.0, 0);
  28146. positions.push(p.x, 0, p.y);
  28147. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28148. });
  28149. var indices = [];
  28150. this._swctx.triangulate();
  28151. this._swctx.getTriangles().forEach(function (triangle) {
  28152. triangle.getPoints().forEach(function (point) {
  28153. indices.push(point.index);
  28154. });
  28155. });
  28156. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28157. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28158. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28159. result.setIndices(indices);
  28160. return result;
  28161. };
  28162. return PolygonMeshBuilder;
  28163. })();
  28164. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28165. })(BABYLON || (BABYLON = {}));
  28166. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28167. (function (BABYLON) {
  28168. var SimplificationSettings = (function () {
  28169. function SimplificationSettings(quality, distance) {
  28170. this.quality = quality;
  28171. this.distance = distance;
  28172. }
  28173. return SimplificationSettings;
  28174. })();
  28175. BABYLON.SimplificationSettings = SimplificationSettings;
  28176. var SimplificationQueue = (function () {
  28177. function SimplificationQueue() {
  28178. this.running = false;
  28179. this._simplificationArray = [];
  28180. }
  28181. SimplificationQueue.prototype.addTask = function (task) {
  28182. this._simplificationArray.push(task);
  28183. };
  28184. SimplificationQueue.prototype.executeNext = function () {
  28185. var task = this._simplificationArray.pop();
  28186. if (task) {
  28187. this.running = true;
  28188. this.runSimplification(task);
  28189. }
  28190. else {
  28191. this.running = false;
  28192. }
  28193. };
  28194. SimplificationQueue.prototype.runSimplification = function (task) {
  28195. var _this = this;
  28196. if (task.parallelProcessing) {
  28197. //parallel simplifier
  28198. task.settings.forEach(function (setting) {
  28199. var simplifier = _this.getSimplifier(task);
  28200. simplifier.simplify(setting, function (newMesh) {
  28201. task.mesh.addLODLevel(setting.distance, newMesh);
  28202. newMesh.isVisible = true;
  28203. //check if it is the last
  28204. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28205. //all done, run the success callback.
  28206. task.successCallback();
  28207. }
  28208. _this.executeNext();
  28209. });
  28210. });
  28211. }
  28212. else {
  28213. //single simplifier.
  28214. var simplifier = this.getSimplifier(task);
  28215. var runDecimation = function (setting, callback) {
  28216. simplifier.simplify(setting, function (newMesh) {
  28217. task.mesh.addLODLevel(setting.distance, newMesh);
  28218. newMesh.isVisible = true;
  28219. //run the next quality level
  28220. callback();
  28221. });
  28222. };
  28223. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28224. runDecimation(task.settings[loop.index], function () {
  28225. loop.executeNext();
  28226. });
  28227. }, function () {
  28228. //execution ended, run the success callback.
  28229. if (task.successCallback) {
  28230. task.successCallback();
  28231. }
  28232. _this.executeNext();
  28233. });
  28234. }
  28235. };
  28236. SimplificationQueue.prototype.getSimplifier = function (task) {
  28237. switch (task.simplificationType) {
  28238. case 0 /* QUADRATIC */:
  28239. default:
  28240. return new QuadraticErrorSimplification(task.mesh);
  28241. }
  28242. };
  28243. return SimplificationQueue;
  28244. })();
  28245. BABYLON.SimplificationQueue = SimplificationQueue;
  28246. /**
  28247. * The implemented types of simplification.
  28248. * At the moment only Quadratic Error Decimation is implemented.
  28249. */
  28250. (function (SimplificationType) {
  28251. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28252. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28253. var SimplificationType = BABYLON.SimplificationType;
  28254. var DecimationTriangle = (function () {
  28255. function DecimationTriangle(vertices) {
  28256. this.vertices = vertices;
  28257. this.error = new Array(4);
  28258. this.deleted = false;
  28259. this.isDirty = false;
  28260. this.deletePending = false;
  28261. this.borderFactor = 0;
  28262. }
  28263. return DecimationTriangle;
  28264. })();
  28265. BABYLON.DecimationTriangle = DecimationTriangle;
  28266. var DecimationVertex = (function () {
  28267. function DecimationVertex(position, normal, uv, id) {
  28268. this.position = position;
  28269. this.normal = normal;
  28270. this.uv = uv;
  28271. this.id = id;
  28272. this.isBorder = true;
  28273. this.q = new QuadraticMatrix();
  28274. this.triangleCount = 0;
  28275. this.triangleStart = 0;
  28276. }
  28277. return DecimationVertex;
  28278. })();
  28279. BABYLON.DecimationVertex = DecimationVertex;
  28280. var QuadraticMatrix = (function () {
  28281. function QuadraticMatrix(data) {
  28282. this.data = new Array(10);
  28283. for (var i = 0; i < 10; ++i) {
  28284. if (data && data[i]) {
  28285. this.data[i] = data[i];
  28286. }
  28287. else {
  28288. this.data[i] = 0;
  28289. }
  28290. }
  28291. }
  28292. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28293. 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];
  28294. return det;
  28295. };
  28296. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28297. for (var i = 0; i < 10; ++i) {
  28298. this.data[i] += matrix.data[i];
  28299. }
  28300. };
  28301. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28302. for (var i = 0; i < 10; ++i) {
  28303. this.data[i] += data[i];
  28304. }
  28305. };
  28306. QuadraticMatrix.prototype.add = function (matrix) {
  28307. var m = new QuadraticMatrix();
  28308. for (var i = 0; i < 10; ++i) {
  28309. m.data[i] = this.data[i] + matrix.data[i];
  28310. }
  28311. return m;
  28312. };
  28313. QuadraticMatrix.FromData = function (a, b, c, d) {
  28314. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28315. };
  28316. //returning an array to avoid garbage collection
  28317. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28318. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28319. };
  28320. return QuadraticMatrix;
  28321. })();
  28322. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28323. var Reference = (function () {
  28324. function Reference(vertexId, triangleId) {
  28325. this.vertexId = vertexId;
  28326. this.triangleId = triangleId;
  28327. }
  28328. return Reference;
  28329. })();
  28330. BABYLON.Reference = Reference;
  28331. /**
  28332. * An implementation of the Quadratic Error simplification algorithm.
  28333. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28334. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28335. * @author RaananW
  28336. */
  28337. var QuadraticErrorSimplification = (function () {
  28338. function QuadraticErrorSimplification(_mesh) {
  28339. this._mesh = _mesh;
  28340. this.initialised = false;
  28341. this.syncIterations = 5000;
  28342. this.aggressiveness = 7;
  28343. this.decimationIterations = 100;
  28344. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28345. }
  28346. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28347. var _this = this;
  28348. this.initDecimatedMesh();
  28349. //iterating through the submeshes array, one after the other.
  28350. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28351. _this.initWithMesh(_this._mesh, loop.index, function () {
  28352. _this.runDecimation(settings, loop.index, function () {
  28353. loop.executeNext();
  28354. });
  28355. });
  28356. }, function () {
  28357. setTimeout(function () {
  28358. successCallback(_this._reconstructedMesh);
  28359. }, 0);
  28360. });
  28361. };
  28362. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28363. var _this = this;
  28364. var gCount = 0;
  28365. triangle.vertices.forEach(function (vId) {
  28366. var count = 0;
  28367. var vPos = _this.vertices[vId].position;
  28368. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28369. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28370. ++count;
  28371. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28372. ++count;
  28373. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28374. ++count;
  28375. if (count > 1) {
  28376. ++gCount;
  28377. }
  28378. ;
  28379. });
  28380. if (gCount > 1) {
  28381. console.log(triangle, gCount);
  28382. }
  28383. return gCount > 1;
  28384. };
  28385. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28386. var _this = this;
  28387. var targetCount = ~~(this.triangles.length * settings.quality);
  28388. var deletedTriangles = 0;
  28389. var triangleCount = this.triangles.length;
  28390. var iterationFunction = function (iteration, callback) {
  28391. setTimeout(function () {
  28392. if (iteration % 5 === 0) {
  28393. _this.updateMesh(iteration === 0);
  28394. }
  28395. for (var i = 0; i < _this.triangles.length; ++i) {
  28396. _this.triangles[i].isDirty = false;
  28397. }
  28398. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28399. var trianglesIterator = function (i) {
  28400. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28401. var t = _this.triangles[tIdx];
  28402. if (!t)
  28403. return;
  28404. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28405. return;
  28406. }
  28407. for (var j = 0; j < 3; ++j) {
  28408. if (t.error[j] < threshold) {
  28409. var deleted0 = [];
  28410. var deleted1 = [];
  28411. var i0 = t.vertices[j];
  28412. var i1 = t.vertices[(j + 1) % 3];
  28413. var v0 = _this.vertices[i0];
  28414. var v1 = _this.vertices[i1];
  28415. if (v0.isBorder !== v1.isBorder)
  28416. continue;
  28417. var p = BABYLON.Vector3.Zero();
  28418. var n = BABYLON.Vector3.Zero();
  28419. var uv = BABYLON.Vector2.Zero();
  28420. var color = new BABYLON.Color4(0, 0, 0, 1);
  28421. _this.calculateError(v0, v1, p, n, uv, color);
  28422. var delTr = [];
  28423. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  28424. continue;
  28425. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  28426. continue;
  28427. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28428. continue;
  28429. var uniqueArray = [];
  28430. delTr.forEach(function (deletedT) {
  28431. if (uniqueArray.indexOf(deletedT) === -1) {
  28432. deletedT.deletePending = true;
  28433. uniqueArray.push(deletedT);
  28434. }
  28435. });
  28436. if (uniqueArray.length % 2 != 0) {
  28437. continue;
  28438. }
  28439. v0.normal = n;
  28440. if (v0.uv)
  28441. v0.uv = uv;
  28442. else if (v0.color)
  28443. v0.color = color;
  28444. v0.q = v1.q.add(v0.q);
  28445. v0.position = p;
  28446. var tStart = _this.references.length;
  28447. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  28448. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  28449. var tCount = _this.references.length - tStart;
  28450. if (tCount <= v0.triangleCount) {
  28451. if (tCount) {
  28452. for (var c = 0; c < tCount; c++) {
  28453. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28454. }
  28455. }
  28456. }
  28457. else {
  28458. v0.triangleStart = tStart;
  28459. }
  28460. v0.triangleCount = tCount;
  28461. break;
  28462. }
  28463. }
  28464. };
  28465. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28466. return (triangleCount - deletedTriangles <= targetCount);
  28467. });
  28468. }, 0);
  28469. };
  28470. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28471. if (triangleCount - deletedTriangles <= targetCount)
  28472. loop.breakLoop();
  28473. else {
  28474. iterationFunction(loop.index, function () {
  28475. loop.executeNext();
  28476. });
  28477. }
  28478. }, function () {
  28479. setTimeout(function () {
  28480. //reconstruct this part of the mesh
  28481. _this.reconstructMesh(submeshIndex);
  28482. successCallback();
  28483. }, 0);
  28484. });
  28485. };
  28486. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  28487. var _this = this;
  28488. if (!mesh)
  28489. return;
  28490. this.vertices = [];
  28491. this.triangles = [];
  28492. this._mesh = mesh;
  28493. //It is assumed that a mesh has positions, normals and either uvs or colors.
  28494. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28495. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28496. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28497. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28498. var indices = mesh.getIndices();
  28499. var submesh = mesh.subMeshes[submeshIndex];
  28500. var vertexInit = function (i) {
  28501. var offset = i + submesh.verticesStart;
  28502. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  28503. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28504. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  28505. }
  28506. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28507. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  28508. }
  28509. _this.vertices.push(vertex);
  28510. };
  28511. //var totalVertices = mesh.getTotalVertices();
  28512. var totalVertices = submesh.verticesCount;
  28513. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  28514. var indicesInit = function (i) {
  28515. var offset = (submesh.indexStart / 3) + i;
  28516. var pos = (offset * 3);
  28517. var i0 = indices[pos + 0] - submesh.verticesStart;
  28518. var i1 = indices[pos + 1] - submesh.verticesStart;
  28519. var i2 = indices[pos + 2] - submesh.verticesStart;
  28520. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  28521. _this.triangles.push(triangle);
  28522. };
  28523. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28524. _this.init(callback);
  28525. });
  28526. });
  28527. };
  28528. QuadraticErrorSimplification.prototype.init = function (callback) {
  28529. var _this = this;
  28530. var triangleInit1 = function (i) {
  28531. var t = _this.triangles[i];
  28532. 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();
  28533. for (var j = 0; j < 3; j++) {
  28534. _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))));
  28535. }
  28536. };
  28537. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28538. var triangleInit2 = function (i) {
  28539. var t = _this.triangles[i];
  28540. for (var j = 0; j < 3; ++j) {
  28541. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  28542. }
  28543. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28544. };
  28545. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28546. _this.initialised = true;
  28547. callback();
  28548. });
  28549. });
  28550. };
  28551. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28552. var newTriangles = [];
  28553. var i;
  28554. for (i = 0; i < this.vertices.length; ++i) {
  28555. this.vertices[i].triangleCount = 0;
  28556. }
  28557. var t;
  28558. var j;
  28559. for (i = 0; i < this.triangles.length; ++i) {
  28560. if (!this.triangles[i].deleted) {
  28561. t = this.triangles[i];
  28562. for (j = 0; j < 3; ++j) {
  28563. this.vertices[t.vertices[j]].triangleCount = 1;
  28564. }
  28565. newTriangles.push(t);
  28566. }
  28567. }
  28568. var newVerticesOrder = [];
  28569. //compact vertices, get the IDs of the vertices used.
  28570. var dst = 0;
  28571. for (i = 0; i < this.vertices.length; ++i) {
  28572. if (this.vertices[i].triangleCount) {
  28573. this.vertices[i].triangleStart = dst;
  28574. this.vertices[dst].position = this.vertices[i].position;
  28575. this.vertices[dst].normal = this.vertices[i].normal;
  28576. this.vertices[dst].uv = this.vertices[i].uv;
  28577. this.vertices[dst].color = this.vertices[i].color;
  28578. newVerticesOrder.push(dst);
  28579. dst++;
  28580. }
  28581. }
  28582. for (i = 0; i < newTriangles.length; ++i) {
  28583. t = newTriangles[i];
  28584. for (j = 0; j < 3; ++j) {
  28585. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  28586. }
  28587. }
  28588. this.vertices = this.vertices.slice(0, dst);
  28589. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28590. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28591. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28592. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28593. for (i = 0; i < newVerticesOrder.length; ++i) {
  28594. newPositionData.push(this.vertices[i].position.x);
  28595. newPositionData.push(this.vertices[i].position.y);
  28596. newPositionData.push(this.vertices[i].position.z);
  28597. newNormalData.push(this.vertices[i].normal.x);
  28598. newNormalData.push(this.vertices[i].normal.y);
  28599. newNormalData.push(this.vertices[i].normal.z);
  28600. if (this.vertices[i].uv) {
  28601. newUVsData.push(this.vertices[i].uv.x);
  28602. newUVsData.push(this.vertices[i].uv.y);
  28603. }
  28604. else if (this.vertices[i].color) {
  28605. newColorsData.push(this.vertices[i].color.r);
  28606. newColorsData.push(this.vertices[i].color.g);
  28607. newColorsData.push(this.vertices[i].color.b);
  28608. newColorsData.push(this.vertices[i].color.a);
  28609. }
  28610. }
  28611. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28612. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28613. var submeshesArray = this._reconstructedMesh.subMeshes;
  28614. this._reconstructedMesh.subMeshes = [];
  28615. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28616. for (i = 0; i < newTriangles.length; ++i) {
  28617. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  28618. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  28619. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  28620. }
  28621. //overwriting the old vertex buffers and indices.
  28622. this._reconstructedMesh.setIndices(newIndicesArray);
  28623. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28624. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28625. if (newUVsData.length > 0)
  28626. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28627. if (newColorsData.length > 0)
  28628. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28629. //create submesh
  28630. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28631. if (submeshIndex > 0) {
  28632. this._reconstructedMesh.subMeshes = [];
  28633. submeshesArray.forEach(function (submesh) {
  28634. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28635. });
  28636. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28637. }
  28638. };
  28639. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28640. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28641. this._reconstructedMesh.material = this._mesh.material;
  28642. this._reconstructedMesh.parent = this._mesh.parent;
  28643. this._reconstructedMesh.isVisible = false;
  28644. };
  28645. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  28646. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28647. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28648. if (t.deleted)
  28649. continue;
  28650. var s = this.references[vertex1.triangleStart + i].vertexId;
  28651. var id1 = t.vertices[(s + 1) % 3];
  28652. var id2 = t.vertices[(s + 2) % 3];
  28653. if ((id1 === index2 || id2 === index2)) {
  28654. deletedArray[i] = true;
  28655. delTr.push(t);
  28656. continue;
  28657. }
  28658. var d1 = this.vertices[id1].position.subtract(point);
  28659. d1 = d1.normalize();
  28660. var d2 = this.vertices[id2].position.subtract(point);
  28661. d2 = d2.normalize();
  28662. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28663. return true;
  28664. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28665. deletedArray[i] = false;
  28666. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28667. return true;
  28668. }
  28669. return false;
  28670. };
  28671. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  28672. var newDeleted = deletedTriangles;
  28673. for (var i = 0; i < vertex.triangleCount; ++i) {
  28674. var ref = this.references[vertex.triangleStart + i];
  28675. var t = this.triangles[ref.triangleId];
  28676. if (t.deleted)
  28677. continue;
  28678. if (deletedArray[i] && t.deletePending) {
  28679. t.deleted = true;
  28680. newDeleted++;
  28681. continue;
  28682. }
  28683. t.vertices[ref.vertexId] = vertexId;
  28684. t.isDirty = true;
  28685. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  28686. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  28687. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  28688. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28689. this.references.push(ref);
  28690. }
  28691. return newDeleted;
  28692. };
  28693. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28694. for (var i = 0; i < this.vertices.length; ++i) {
  28695. var vCount = [];
  28696. var vId = [];
  28697. var v = this.vertices[i];
  28698. var j;
  28699. for (j = 0; j < v.triangleCount; ++j) {
  28700. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28701. for (var ii = 0; ii < 3; ii++) {
  28702. var ofs = 0;
  28703. var id = triangle.vertices[ii];
  28704. while (ofs < vCount.length) {
  28705. if (vId[ofs] === id)
  28706. break;
  28707. ++ofs;
  28708. }
  28709. if (ofs === vCount.length) {
  28710. vCount.push(1);
  28711. vId.push(id);
  28712. }
  28713. else {
  28714. vCount[ofs]++;
  28715. }
  28716. }
  28717. }
  28718. for (j = 0; j < vCount.length; ++j) {
  28719. if (vCount[j] === 1) {
  28720. this.vertices[vId[j]].isBorder = true;
  28721. }
  28722. else {
  28723. this.vertices[vId[j]].isBorder = false;
  28724. }
  28725. }
  28726. }
  28727. };
  28728. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28729. if (identifyBorders === void 0) { identifyBorders = false; }
  28730. var i;
  28731. if (!identifyBorders) {
  28732. var newTrianglesVector = [];
  28733. for (i = 0; i < this.triangles.length; ++i) {
  28734. if (!this.triangles[i].deleted) {
  28735. newTrianglesVector.push(this.triangles[i]);
  28736. }
  28737. }
  28738. this.triangles = newTrianglesVector;
  28739. }
  28740. for (i = 0; i < this.vertices.length; ++i) {
  28741. this.vertices[i].triangleCount = 0;
  28742. this.vertices[i].triangleStart = 0;
  28743. }
  28744. var t;
  28745. var j;
  28746. var v;
  28747. for (i = 0; i < this.triangles.length; ++i) {
  28748. t = this.triangles[i];
  28749. for (j = 0; j < 3; ++j) {
  28750. v = this.vertices[t.vertices[j]];
  28751. v.triangleCount++;
  28752. }
  28753. }
  28754. var tStart = 0;
  28755. for (i = 0; i < this.vertices.length; ++i) {
  28756. this.vertices[i].triangleStart = tStart;
  28757. tStart += this.vertices[i].triangleCount;
  28758. this.vertices[i].triangleCount = 0;
  28759. }
  28760. var newReferences = new Array(this.triangles.length * 3);
  28761. for (i = 0; i < this.triangles.length; ++i) {
  28762. t = this.triangles[i];
  28763. for (j = 0; j < 3; ++j) {
  28764. v = this.vertices[t.vertices[j]];
  28765. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28766. v.triangleCount++;
  28767. }
  28768. }
  28769. this.references = newReferences;
  28770. if (identifyBorders) {
  28771. this.identifyBorder();
  28772. }
  28773. };
  28774. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28775. var x = point.x;
  28776. var y = point.y;
  28777. var z = point.z;
  28778. 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];
  28779. };
  28780. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28781. var q = vertex1.q.add(vertex2.q);
  28782. var border = vertex1.isBorder && vertex2.isBorder;
  28783. var error = 0;
  28784. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28785. if (qDet !== 0 && !border) {
  28786. if (!pointResult) {
  28787. pointResult = BABYLON.Vector3.Zero();
  28788. }
  28789. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28790. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28791. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28792. error = this.vertexError(q, pointResult);
  28793. //TODO this should be correctly calculated
  28794. if (normalResult) {
  28795. normalResult.copyFrom(vertex1.normal);
  28796. if (vertex1.uv)
  28797. uvResult.copyFrom(vertex1.uv);
  28798. else if (vertex1.color)
  28799. colorResult.copyFrom(vertex1.color);
  28800. }
  28801. }
  28802. else {
  28803. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28804. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28805. var error1 = this.vertexError(q, vertex1.position);
  28806. var error2 = this.vertexError(q, vertex2.position);
  28807. var error3 = this.vertexError(q, p3);
  28808. error = Math.min(error1, error2, error3);
  28809. if (error === error1) {
  28810. if (pointResult) {
  28811. pointResult.copyFrom(vertex1.position);
  28812. normalResult.copyFrom(vertex1.normal);
  28813. if (vertex1.uv)
  28814. uvResult.copyFrom(vertex1.uv);
  28815. else if (vertex1.color)
  28816. colorResult.copyFrom(vertex1.color);
  28817. }
  28818. }
  28819. else if (error === error2) {
  28820. if (pointResult) {
  28821. pointResult.copyFrom(vertex2.position);
  28822. normalResult.copyFrom(vertex2.normal);
  28823. if (vertex2.uv)
  28824. uvResult.copyFrom(vertex2.uv);
  28825. else if (vertex2.color)
  28826. colorResult.copyFrom(vertex2.color);
  28827. }
  28828. }
  28829. else {
  28830. if (pointResult) {
  28831. pointResult.copyFrom(p3);
  28832. normalResult.copyFrom(vertex1.normal);
  28833. if (vertex1.uv)
  28834. uvResult.copyFrom(vertex1.uv);
  28835. else if (vertex1.color)
  28836. colorResult.copyFrom(vertex1.color);
  28837. }
  28838. }
  28839. }
  28840. return error;
  28841. };
  28842. return QuadraticErrorSimplification;
  28843. })();
  28844. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28845. })(BABYLON || (BABYLON = {}));
  28846. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28847. (function (BABYLON) {
  28848. var Analyser = (function () {
  28849. function Analyser(scene) {
  28850. this.SMOOTHING = 0.75;
  28851. this.FFT_SIZE = 512;
  28852. this.BARGRAPHAMPLITUDE = 256;
  28853. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28854. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28855. this._scene = scene;
  28856. this._audioEngine = BABYLON.Engine.audioEngine;
  28857. if (this._audioEngine.canUseWebAudio) {
  28858. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28859. this._webAudioAnalyser.minDecibels = -140;
  28860. this._webAudioAnalyser.maxDecibels = 0;
  28861. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28862. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28863. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28864. }
  28865. }
  28866. Analyser.prototype.getFrequencyBinCount = function () {
  28867. if (this._audioEngine.canUseWebAudio) {
  28868. return this._webAudioAnalyser.frequencyBinCount;
  28869. }
  28870. else {
  28871. return 0;
  28872. }
  28873. };
  28874. Analyser.prototype.getByteFrequencyData = function () {
  28875. if (this._audioEngine.canUseWebAudio) {
  28876. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28877. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28878. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28879. }
  28880. return this._byteFreqs;
  28881. };
  28882. Analyser.prototype.getByteTimeDomainData = function () {
  28883. if (this._audioEngine.canUseWebAudio) {
  28884. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28885. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28886. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28887. }
  28888. return this._byteTime;
  28889. };
  28890. Analyser.prototype.getFloatFrequencyData = function () {
  28891. if (this._audioEngine.canUseWebAudio) {
  28892. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28893. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28894. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28895. }
  28896. return this._floatFreqs;
  28897. };
  28898. Analyser.prototype.drawDebugCanvas = function () {
  28899. var _this = this;
  28900. if (this._audioEngine.canUseWebAudio) {
  28901. if (!this._debugCanvas) {
  28902. this._debugCanvas = document.createElement("canvas");
  28903. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28904. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28905. this._debugCanvas.style.position = "absolute";
  28906. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28907. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28908. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28909. document.body.appendChild(this._debugCanvas);
  28910. this._registerFunc = function () {
  28911. _this.drawDebugCanvas();
  28912. };
  28913. this._scene.registerBeforeRender(this._registerFunc);
  28914. }
  28915. if (this._registerFunc) {
  28916. var workingArray = this.getByteFrequencyData();
  28917. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28918. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28919. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28920. var value = workingArray[i];
  28921. var percent = value / this.BARGRAPHAMPLITUDE;
  28922. var height = this.DEBUGCANVASSIZE.height * percent;
  28923. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28924. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28925. var hue = i / this.getFrequencyBinCount() * 360;
  28926. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28927. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28928. }
  28929. }
  28930. }
  28931. };
  28932. Analyser.prototype.stopDebugCanvas = function () {
  28933. if (this._debugCanvas) {
  28934. this._scene.unregisterBeforeRender(this._registerFunc);
  28935. this._registerFunc = null;
  28936. document.body.removeChild(this._debugCanvas);
  28937. this._debugCanvas = null;
  28938. this._debugCanvasContext = null;
  28939. }
  28940. };
  28941. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28942. if (this._audioEngine.canUseWebAudio) {
  28943. inputAudioNode.connect(this._webAudioAnalyser);
  28944. this._webAudioAnalyser.connect(outputAudioNode);
  28945. }
  28946. };
  28947. Analyser.prototype.dispose = function () {
  28948. if (this._audioEngine.canUseWebAudio) {
  28949. this._webAudioAnalyser.disconnect();
  28950. }
  28951. };
  28952. return Analyser;
  28953. })();
  28954. BABYLON.Analyser = Analyser;
  28955. })(BABYLON || (BABYLON = {}));
  28956. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28957. (function (BABYLON) {
  28958. var DepthRenderer = (function () {
  28959. function DepthRenderer(scene, type) {
  28960. var _this = this;
  28961. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28962. this._viewMatrix = BABYLON.Matrix.Zero();
  28963. this._projectionMatrix = BABYLON.Matrix.Zero();
  28964. this._transformMatrix = BABYLON.Matrix.Zero();
  28965. this._worldViewProjection = BABYLON.Matrix.Zero();
  28966. this._scene = scene;
  28967. var engine = scene.getEngine();
  28968. // Render target
  28969. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28970. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28971. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28972. this._depthMap.refreshRate = 1;
  28973. this._depthMap.renderParticles = false;
  28974. this._depthMap.renderList = null;
  28975. // Custom render function
  28976. var renderSubMesh = function (subMesh) {
  28977. var mesh = subMesh.getRenderingMesh();
  28978. var scene = _this._scene;
  28979. var engine = scene.getEngine();
  28980. // Culling
  28981. engine.setState(subMesh.getMaterial().backFaceCulling);
  28982. // Managing instances
  28983. var batch = mesh._getInstancesRenderList(subMesh._id);
  28984. if (batch.mustReturn) {
  28985. return;
  28986. }
  28987. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28988. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28989. engine.enableEffect(_this._effect);
  28990. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28991. var material = subMesh.getMaterial();
  28992. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28993. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28994. // Alpha test
  28995. if (material && material.needAlphaTesting()) {
  28996. var alphaTexture = material.getAlphaTestTexture();
  28997. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28998. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28999. }
  29000. // Bones
  29001. if (mesh.useBones) {
  29002. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29003. }
  29004. // Draw
  29005. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29006. }
  29007. };
  29008. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29009. var index;
  29010. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29011. renderSubMesh(opaqueSubMeshes.data[index]);
  29012. }
  29013. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29014. renderSubMesh(alphaTestSubMeshes.data[index]);
  29015. }
  29016. };
  29017. }
  29018. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29019. var defines = [];
  29020. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29021. var mesh = subMesh.getMesh();
  29022. var scene = mesh.getScene();
  29023. var material = subMesh.getMaterial();
  29024. // Alpha test
  29025. if (material && material.needAlphaTesting()) {
  29026. defines.push("#define ALPHATEST");
  29027. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29028. attribs.push(BABYLON.VertexBuffer.UVKind);
  29029. defines.push("#define UV1");
  29030. }
  29031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29032. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29033. defines.push("#define UV2");
  29034. }
  29035. }
  29036. // Bones
  29037. if (mesh.useBones) {
  29038. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29039. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29040. defines.push("#define BONES");
  29041. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29042. }
  29043. // Instances
  29044. if (useInstances) {
  29045. defines.push("#define INSTANCES");
  29046. attribs.push("world0");
  29047. attribs.push("world1");
  29048. attribs.push("world2");
  29049. attribs.push("world3");
  29050. }
  29051. // Get correct effect
  29052. var join = defines.join("\n");
  29053. if (this._cachedDefines !== join) {
  29054. this._cachedDefines = join;
  29055. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29056. }
  29057. return this._effect.isReady();
  29058. };
  29059. DepthRenderer.prototype.getDepthMap = function () {
  29060. return this._depthMap;
  29061. };
  29062. // Methods
  29063. DepthRenderer.prototype.dispose = function () {
  29064. this._depthMap.dispose();
  29065. };
  29066. return DepthRenderer;
  29067. })();
  29068. BABYLON.DepthRenderer = DepthRenderer;
  29069. })(BABYLON || (BABYLON = {}));
  29070. //# sourceMappingURL=babylon.depthRenderer.js.map
  29071. var BABYLON;
  29072. (function (BABYLON) {
  29073. var SSAORenderingPipeline = (function (_super) {
  29074. __extends(SSAORenderingPipeline, _super);
  29075. /**
  29076. * @constructor
  29077. * @param {string} name - The rendering pipeline name
  29078. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29079. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  29080. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29081. */
  29082. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29083. var _this = this;
  29084. _super.call(this, scene.getEngine(), name);
  29085. // Members
  29086. /**
  29087. * The PassPostProcess id in the pipeline that contains the original scene color
  29088. * @type {string}
  29089. */
  29090. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29091. /**
  29092. * The SSAO PostProcess id in the pipeline
  29093. * @type {string}
  29094. */
  29095. this.SSAORenderEffect = "SSAORenderEffect";
  29096. /**
  29097. * The horizontal blur PostProcess id in the pipeline
  29098. * @type {string}
  29099. */
  29100. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29101. /**
  29102. * The vertical blur PostProcess id in the pipeline
  29103. * @type {string}
  29104. */
  29105. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29106. /**
  29107. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29108. * @type {string}
  29109. */
  29110. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29111. /**
  29112. * The output strength of the SSAO post-process. Default value is 1.0.
  29113. * @type {number}
  29114. */
  29115. this.totalStrength = 1.0;
  29116. /**
  29117. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.002
  29118. * @type {number}
  29119. */
  29120. this.radius = 0.0002;
  29121. /**
  29122. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29123. * Must not be equal to fallOff and superior to fallOff.
  29124. * Default value is 0.0075
  29125. * @type {number}
  29126. */
  29127. this.area = 0.0075;
  29128. /**
  29129. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29130. * Must not be equal to area and inferior to area.
  29131. * Default value is 0.0003
  29132. * @type {number}
  29133. */
  29134. this.fallOff = 0.0003;
  29135. this._firstUpdate = true;
  29136. this._scene = scene;
  29137. // Set up assets
  29138. this._createRandomTexture();
  29139. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29140. var ssaoRatio = ratio.ssaoRatio || ratio;
  29141. var combineRatio = ratio.combineRatio || ratio;
  29142. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29143. this._createSSAOPostProcess(ssaoRatio);
  29144. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29145. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29146. this._createSSAOCombinePostProcess(combineRatio);
  29147. // Set up pipeline
  29148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29149. return _this._originalColorPostProcess;
  29150. }, true));
  29151. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29152. return _this._ssaoPostProcess;
  29153. }, true));
  29154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29155. return _this._blurHPostProcess;
  29156. }, true));
  29157. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29158. return _this._blurVPostProcess;
  29159. }, true));
  29160. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29161. return _this._ssaoCombinePostProcess;
  29162. }, true));
  29163. // Finish
  29164. scene.postProcessRenderPipelineManager.addPipeline(this);
  29165. if (cameras)
  29166. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29167. }
  29168. // Public Methods
  29169. /**
  29170. * Returns the horizontal blur PostProcess
  29171. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29172. */
  29173. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29174. return this._blurHPostProcess;
  29175. };
  29176. /**
  29177. * Returns the vertical blur PostProcess
  29178. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29179. */
  29180. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29181. return this._blurVPostProcess;
  29182. };
  29183. /**
  29184. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29185. */
  29186. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29187. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29188. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29189. this._originalColorPostProcess = undefined;
  29190. this._ssaoPostProcess = undefined;
  29191. this._blurHPostProcess = undefined;
  29192. this._blurVPostProcess = undefined;
  29193. this._ssaoCombinePostProcess = undefined;
  29194. this._randomTexture.dispose();
  29195. if (disableDepthRender)
  29196. this._scene.disableDepthRenderer();
  29197. };
  29198. // Private Methods
  29199. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29200. var _this = this;
  29201. var sampleSphere = [
  29202. 0.5381,
  29203. 0.1856,
  29204. -0.4319,
  29205. 0.1379,
  29206. 0.2486,
  29207. 0.4430,
  29208. 0.3371,
  29209. 0.5679,
  29210. -0.0057,
  29211. -0.6999,
  29212. -0.0451,
  29213. -0.0019,
  29214. 0.0689,
  29215. -0.1598,
  29216. -0.8547,
  29217. 0.0560,
  29218. 0.0069,
  29219. -0.1843,
  29220. -0.0146,
  29221. 0.1402,
  29222. 0.0762,
  29223. 0.0100,
  29224. -0.1924,
  29225. -0.0344,
  29226. -0.3577,
  29227. -0.5301,
  29228. -0.4358,
  29229. -0.3169,
  29230. 0.1063,
  29231. 0.0158,
  29232. 0.0103,
  29233. -0.5869,
  29234. 0.0046,
  29235. -0.0897,
  29236. -0.4940,
  29237. 0.3287,
  29238. 0.7119,
  29239. -0.0154,
  29240. -0.0918,
  29241. -0.0533,
  29242. 0.0596,
  29243. -0.5411,
  29244. 0.0352,
  29245. -0.0631,
  29246. 0.5460,
  29247. -0.4776,
  29248. 0.2847,
  29249. -0.0271
  29250. ];
  29251. var samplesFactor = 1.0 / 16.0;
  29252. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29253. this._ssaoPostProcess.onApply = function (effect) {
  29254. if (_this._firstUpdate) {
  29255. effect.setArray3("sampleSphere", sampleSphere);
  29256. effect.setFloat("samplesFactor", samplesFactor);
  29257. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29258. _this._firstUpdate = false;
  29259. }
  29260. effect.setFloat("totalStrength", _this.totalStrength);
  29261. effect.setFloat("radius", _this.radius);
  29262. effect.setFloat("area", _this.area);
  29263. effect.setFloat("fallOff", _this.fallOff);
  29264. effect.setTexture("textureSampler", _this._depthTexture);
  29265. effect.setTexture("randomSampler", _this._randomTexture);
  29266. };
  29267. };
  29268. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29269. var _this = this;
  29270. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29271. this._ssaoCombinePostProcess.onApply = function (effect) {
  29272. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29273. };
  29274. };
  29275. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29276. var size = 512;
  29277. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29278. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29279. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29280. var context = this._randomTexture.getContext();
  29281. var rand = function (min, max) {
  29282. return Math.random() * (max - min) + min;
  29283. };
  29284. for (var x = 0; x < size; x++) {
  29285. for (var y = 0; y < size; y++) {
  29286. var randVector = BABYLON.Vector3.Zero();
  29287. randVector.x = randVector.y = randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29288. //randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29289. //randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29290. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29291. context.fillRect(x, y, 1, 1);
  29292. }
  29293. }
  29294. this._randomTexture.update(false);
  29295. };
  29296. return SSAORenderingPipeline;
  29297. })(BABYLON.PostProcessRenderPipeline);
  29298. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29299. })(BABYLON || (BABYLON = {}));
  29300. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29301. var BABYLON;
  29302. (function (BABYLON) {
  29303. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29304. var VolumetricLightScatteringPostProcess = (function (_super) {
  29305. __extends(VolumetricLightScatteringPostProcess, _super);
  29306. /**
  29307. * @constructor
  29308. * @param {string} name - The post-process name
  29309. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  29310. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29311. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29312. * @param {number} samples - The post-process quality, default 100
  29313. * @param {number} samplingMode - The post-process filtering mode
  29314. * @param {BABYLON.Engine} engine - The babylon engine
  29315. * @param {boolean} reusable - If the post-process is reusable
  29316. */
  29317. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29318. var _this = this;
  29319. if (samples === void 0) { samples = 100; }
  29320. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29321. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29322. this._screenCoordinates = BABYLON.Vector2.Zero();
  29323. /**
  29324. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29325. * @type {boolean}
  29326. */
  29327. this.useCustomMeshPosition = false;
  29328. /**
  29329. * If the post-process should inverse the light scattering direction
  29330. * @type {boolean}
  29331. */
  29332. this.invert = true;
  29333. /**
  29334. * Array containing the excluded meshes not rendered in the internal pass
  29335. */
  29336. this.excludedMeshes = new Array();
  29337. this.exposure = 0.3;
  29338. this.decay = 0.96815;
  29339. this.weight = 0.58767;
  29340. this.density = 0.926;
  29341. var scene = camera.getScene();
  29342. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29343. // Configure mesh
  29344. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29345. // Configure
  29346. this._createPass(scene, ratio.passRatio || ratio);
  29347. this.onApply = function (effect) {
  29348. _this._updateMeshScreenCoordinates(scene);
  29349. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29350. effect.setFloat("exposure", _this.exposure);
  29351. effect.setFloat("decay", _this.decay);
  29352. effect.setFloat("weight", _this.weight);
  29353. effect.setFloat("density", _this.density);
  29354. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29355. };
  29356. }
  29357. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29358. var mesh = subMesh.getMesh();
  29359. var defines = [];
  29360. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29361. var material = subMesh.getMaterial();
  29362. var needUV = false;
  29363. // Render this.mesh as default
  29364. if (mesh === this.mesh) {
  29365. defines.push("#define BASIC_RENDER");
  29366. defines.push("#define NEED_UV");
  29367. needUV = true;
  29368. }
  29369. // Alpha test
  29370. if (material) {
  29371. if (material.needAlphaTesting() || mesh === this.mesh)
  29372. defines.push("#define ALPHATEST");
  29373. if (material.opacityTexture !== undefined) {
  29374. defines.push("#define OPACITY");
  29375. if (material.opacityTexture.getAlphaFromRGB)
  29376. defines.push("#define OPACITYRGB");
  29377. if (!needUV)
  29378. defines.push("#define NEED_UV");
  29379. }
  29380. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29381. attribs.push(BABYLON.VertexBuffer.UVKind);
  29382. defines.push("#define UV1");
  29383. }
  29384. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29385. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29386. defines.push("#define UV2");
  29387. }
  29388. }
  29389. // Bones
  29390. if (mesh.useBones) {
  29391. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29392. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29393. defines.push("#define BONES");
  29394. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29395. }
  29396. // Instances
  29397. if (useInstances) {
  29398. defines.push("#define INSTANCES");
  29399. attribs.push("world0");
  29400. attribs.push("world1");
  29401. attribs.push("world2");
  29402. attribs.push("world3");
  29403. }
  29404. // Get correct effect
  29405. var join = defines.join("\n");
  29406. if (this._cachedDefines !== join) {
  29407. this._cachedDefines = join;
  29408. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29409. }
  29410. return this._volumetricLightScatteringPass.isReady();
  29411. };
  29412. /**
  29413. * Sets the new light position for light scattering effect
  29414. * @param {BABYLON.Vector3} The new custom light position
  29415. */
  29416. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29417. this._customMeshPosition = position;
  29418. };
  29419. /**
  29420. * Returns the light position for light scattering effect
  29421. * @return {BABYLON.Vector3} The custom light position
  29422. */
  29423. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29424. return this._customMeshPosition;
  29425. };
  29426. /**
  29427. * Disposes the internal assets and detaches the post-process from the camera
  29428. */
  29429. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29430. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29431. if (rttIndex !== -1) {
  29432. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29433. }
  29434. this._volumetricLightScatteringRTT.dispose();
  29435. _super.prototype.dispose.call(this, camera);
  29436. };
  29437. /**
  29438. * Returns the render target texture used by the post-process
  29439. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29440. */
  29441. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29442. return this._volumetricLightScatteringRTT;
  29443. };
  29444. // Private methods
  29445. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29446. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29447. return true;
  29448. }
  29449. return false;
  29450. };
  29451. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29452. var _this = this;
  29453. var engine = scene.getEngine();
  29454. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29455. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29456. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29457. this._volumetricLightScatteringRTT.renderList = null;
  29458. this._volumetricLightScatteringRTT.renderParticles = false;
  29459. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29460. // Custom render function for submeshes
  29461. var renderSubMesh = function (subMesh) {
  29462. var mesh = subMesh.getRenderingMesh();
  29463. if (_this._meshExcluded(mesh)) {
  29464. return;
  29465. }
  29466. var scene = mesh.getScene();
  29467. var engine = scene.getEngine();
  29468. // Culling
  29469. engine.setState(subMesh.getMaterial().backFaceCulling);
  29470. // Managing instances
  29471. var batch = mesh._getInstancesRenderList(subMesh._id);
  29472. if (batch.mustReturn) {
  29473. return;
  29474. }
  29475. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29476. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29477. engine.enableEffect(_this._volumetricLightScatteringPass);
  29478. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29479. var material = subMesh.getMaterial();
  29480. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29481. // Alpha test
  29482. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29483. var alphaTexture = material.getAlphaTestTexture();
  29484. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29485. if (alphaTexture) {
  29486. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29487. }
  29488. if (material.opacityTexture !== undefined) {
  29489. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29490. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  29491. }
  29492. }
  29493. // Bones
  29494. if (mesh.useBones) {
  29495. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29496. }
  29497. // Draw
  29498. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29499. }
  29500. };
  29501. // Render target texture callbacks
  29502. var savedSceneClearColor;
  29503. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  29504. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29505. savedSceneClearColor = scene.clearColor;
  29506. scene.clearColor = sceneClearColor;
  29507. };
  29508. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29509. scene.clearColor = savedSceneClearColor;
  29510. };
  29511. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29512. var engine = scene.getEngine();
  29513. var index;
  29514. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29515. renderSubMesh(opaqueSubMeshes.data[index]);
  29516. }
  29517. engine.setAlphaTesting(true);
  29518. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29519. renderSubMesh(alphaTestSubMeshes.data[index]);
  29520. }
  29521. engine.setAlphaTesting(false);
  29522. if (transparentSubMeshes.length) {
  29523. for (index = 0; index < transparentSubMeshes.length; index++) {
  29524. var submesh = transparentSubMeshes.data[index];
  29525. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  29526. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  29527. }
  29528. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  29529. sortedArray.sort(function (a, b) {
  29530. // Alpha index first
  29531. if (a._alphaIndex > b._alphaIndex) {
  29532. return 1;
  29533. }
  29534. if (a._alphaIndex < b._alphaIndex) {
  29535. return -1;
  29536. }
  29537. // Then distance to camera
  29538. if (a._distanceToCamera < b._distanceToCamera) {
  29539. return 1;
  29540. }
  29541. if (a._distanceToCamera > b._distanceToCamera) {
  29542. return -1;
  29543. }
  29544. return 0;
  29545. });
  29546. // Render sub meshes
  29547. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29548. for (index = 0; index < sortedArray.length; index++) {
  29549. renderSubMesh(sortedArray[index]);
  29550. }
  29551. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29552. }
  29553. };
  29554. };
  29555. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29556. var transform = scene.getTransformMatrix();
  29557. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29558. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29559. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29560. if (this.invert)
  29561. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29562. };
  29563. // Static methods
  29564. /**
  29565. * Creates a default mesh for the Volumeric Light Scattering post-process
  29566. * @param {string} The mesh name
  29567. * @param {BABYLON.Scene} The scene where to create the mesh
  29568. * @return {BABYLON.Mesh} the default mesh
  29569. */
  29570. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29571. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29572. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29573. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29574. return mesh;
  29575. };
  29576. return VolumetricLightScatteringPostProcess;
  29577. })(BABYLON.PostProcess);
  29578. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29579. })(BABYLON || (BABYLON = {}));
  29580. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29581. var BABYLON;
  29582. (function (BABYLON) {
  29583. var LensRenderingPipeline = (function (_super) {
  29584. __extends(LensRenderingPipeline, _super);
  29585. /**
  29586. * @constructor
  29587. * @param {string} name - The rendering pipeline name
  29588. * @param {object} parameters - An object containing all parameters (see below)
  29589. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29590. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  29591. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29592. Effect parameters are as follow:
  29593. {
  29594. chromatic_aberration: number; // from 0 to x (1 for realism)
  29595. edge_blur: number; // from 0 to x (1 for realism)
  29596. distortion: number; // from 0 to x (1 for realism)
  29597. grain_amount: number; // from 0 to 1
  29598. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29599. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  29600. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29601. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29602. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  29603. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  29604. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29605. }
  29606. Note: if an effect parameter is unset, effect is disabled
  29607. */
  29608. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29609. var _this = this;
  29610. if (ratio === void 0) { ratio = 1.0; }
  29611. _super.call(this, scene.getEngine(), name);
  29612. // Lens effects can be of the following:
  29613. // - chromatic aberration (slight shift of RGB colors)
  29614. // - blur on the edge of the lens
  29615. // - lens distortion
  29616. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  29617. // - grain/dust-on-lens effect
  29618. // Two additional texture samplers are needed:
  29619. // - depth map (for depth-of-field)
  29620. // - grain texture
  29621. /**
  29622. * The chromatic aberration PostProcess id in the pipeline
  29623. * @type {string}
  29624. */
  29625. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29626. /**
  29627. * The depth-of-field PostProcess id in the pipeline
  29628. * @type {string}
  29629. */
  29630. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29631. this._scene = scene;
  29632. // Fetch texture samplers
  29633. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29634. if (parameters.grain_texture) {
  29635. this._grainTexture = parameters.grain_texture;
  29636. }
  29637. else {
  29638. this._createGrainTexture();
  29639. }
  29640. // save parameters
  29641. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29642. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29643. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29644. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29645. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29646. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29647. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29648. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29649. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29650. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29651. // Create effects
  29652. this._createChromaticAberrationPostProcess(ratio);
  29653. this._createDepthOfFieldPostProcess(ratio);
  29654. // Set up pipeline
  29655. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29656. return _this._chromaticAberrationPostProcess;
  29657. }, true));
  29658. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29659. return _this._depthOfFieldPostProcess;
  29660. }, true));
  29661. // Finish
  29662. scene.postProcessRenderPipelineManager.addPipeline(this);
  29663. if (cameras) {
  29664. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29665. }
  29666. }
  29667. // public methods
  29668. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29669. this._edgeBlur = amount;
  29670. };
  29671. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29672. this._edgeBlur = 0;
  29673. };
  29674. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29675. this._grainAmount = amount;
  29676. };
  29677. LensRenderingPipeline.prototype.disableGrain = function () {
  29678. this._grainAmount = 0;
  29679. };
  29680. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29681. this._chromaticAberration = amount;
  29682. };
  29683. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29684. this._chromaticAberration = 0;
  29685. };
  29686. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29687. this._distortion = amount;
  29688. };
  29689. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29690. this._distortion = 0;
  29691. };
  29692. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29693. this._highlightsGain = amount;
  29694. };
  29695. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29696. this._highlightsThreshold = amount;
  29697. };
  29698. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29699. this._dofDepth = amount;
  29700. };
  29701. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29702. this._dofDepth = -1;
  29703. };
  29704. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29705. this._dofAperture = amount;
  29706. };
  29707. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29708. this._dofPentagon = true;
  29709. };
  29710. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29711. this._dofPentagon = false;
  29712. };
  29713. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29714. this._blurNoise = true;
  29715. };
  29716. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29717. this._blurNoise = false;
  29718. };
  29719. /**
  29720. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29721. */
  29722. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29723. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29724. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29725. this._chromaticAberrationPostProcess = undefined;
  29726. this._depthOfFieldPostProcess = undefined;
  29727. this._grainTexture.dispose();
  29728. if (disableDepthRender)
  29729. this._scene.disableDepthRenderer();
  29730. };
  29731. // colors shifting and distortion
  29732. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29733. var _this = this;
  29734. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29735. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29736. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29737. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29738. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29739. };
  29740. };
  29741. // colors shifting and distortion
  29742. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29743. var _this = this;
  29744. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29745. "gain",
  29746. "threshold",
  29747. "focus_depth",
  29748. "aperture",
  29749. "pentagon",
  29750. "maxZ",
  29751. "edge_blur",
  29752. "chromatic_aberration",
  29753. "distortion",
  29754. "blur_noise",
  29755. "grain_amount",
  29756. "screen_width",
  29757. "screen_height"
  29758. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29759. this._depthOfFieldPostProcess.onApply = function (effect) {
  29760. effect.setBool('pentagon', _this._dofPentagon);
  29761. effect.setBool('blur_noise', _this._blurNoise);
  29762. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29763. effect.setFloat('grain_amount', _this._grainAmount);
  29764. effect.setTexture("depthSampler", _this._depthTexture);
  29765. effect.setTexture("grainSampler", _this._grainTexture);
  29766. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29767. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29768. effect.setFloat('distortion', _this._distortion);
  29769. effect.setFloat('focus_depth', _this._dofDepth);
  29770. effect.setFloat('aperture', _this._dofAperture);
  29771. effect.setFloat('gain', _this._highlightsGain);
  29772. effect.setFloat('threshold', _this._highlightsThreshold);
  29773. effect.setFloat('edge_blur', _this._edgeBlur);
  29774. };
  29775. };
  29776. // creates a black and white random noise texture, 512x512
  29777. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29778. var size = 512;
  29779. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29780. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29781. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29782. var context = this._grainTexture.getContext();
  29783. var rand = function (min, max) {
  29784. return Math.random() * (max - min) + min;
  29785. };
  29786. var value;
  29787. for (var x = 0; x < size; x++) {
  29788. for (var y = 0; y < size; y++) {
  29789. value = Math.floor(rand(0.42, 0.58) * 255);
  29790. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29791. context.fillRect(x, y, 1, 1);
  29792. }
  29793. }
  29794. this._grainTexture.update(false);
  29795. };
  29796. return LensRenderingPipeline;
  29797. })(BABYLON.PostProcessRenderPipeline);
  29798. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29799. })(BABYLON || (BABYLON = {}));
  29800. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  29801. // This post-process allows the modification of rendered colors by using
  29802. // a 'look-up table' (LUT). This effect is also called Color Grading.
  29803. //
  29804. // The object needs to be provided an url to a texture containing the color
  29805. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  29806. // Use an image editing software to tweak the LUT to match your needs.
  29807. //
  29808. // For an example of a color LUT, see here:
  29809. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  29810. // For explanations on color grading, see here:
  29811. // http://udn.epicgames.com/Three/ColorGrading.html
  29812. //
  29813. var BABYLON;
  29814. (function (BABYLON) {
  29815. var ColorCorrectionPostProcess = (function (_super) {
  29816. __extends(ColorCorrectionPostProcess, _super);
  29817. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  29818. var _this = this;
  29819. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  29820. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  29821. this._colorTableTexture.anisotropicFilteringLevel = 1;
  29822. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29823. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29824. this.onApply = function (effect) {
  29825. effect.setTexture("colorTable", _this._colorTableTexture);
  29826. };
  29827. }
  29828. return ColorCorrectionPostProcess;
  29829. })(BABYLON.PostProcess);
  29830. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  29831. })(BABYLON || (BABYLON = {}));
  29832. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  29833. (function (BABYLON) {
  29834. var SmartCollection = (function () {
  29835. function SmartCollection(capacity) {
  29836. if (capacity === void 0) { capacity = 10; }
  29837. this.count = 0;
  29838. this._initialCapacity = capacity;
  29839. this.items = {};
  29840. this._keys = new Array(this._initialCapacity);
  29841. }
  29842. SmartCollection.prototype.add = function (key, item) {
  29843. if (this.items[key] != undefined) {
  29844. return -1;
  29845. }
  29846. this.items[key] = item;
  29847. //literal keys are always strings, but we keep source type of key in _keys array
  29848. this._keys[this.count++] = key;
  29849. if (this.count > this._keys.length) {
  29850. this._keys.length *= 2;
  29851. }
  29852. return this.count;
  29853. };
  29854. SmartCollection.prototype.remove = function (key) {
  29855. if (this.items[key] == undefined) {
  29856. return -1;
  29857. }
  29858. return this.removeItemOfIndex(this.indexOf(key));
  29859. };
  29860. SmartCollection.prototype.removeItemOfIndex = function (index) {
  29861. if (index < this.count && index > -1) {
  29862. delete this.items[this._keys[index]];
  29863. while (index < this.count) {
  29864. this._keys[index] = this._keys[index + 1];
  29865. index++;
  29866. }
  29867. }
  29868. else {
  29869. return -1;
  29870. }
  29871. return --this.count;
  29872. };
  29873. SmartCollection.prototype.indexOf = function (key) {
  29874. for (var i = 0; i !== this.count; i++) {
  29875. if (this._keys[i] === key) {
  29876. return i;
  29877. }
  29878. }
  29879. return -1;
  29880. };
  29881. SmartCollection.prototype.item = function (key) {
  29882. return this.items[key];
  29883. };
  29884. SmartCollection.prototype.getAllKeys = function () {
  29885. if (this.count > 0) {
  29886. var keys = new Array(this.count);
  29887. for (var i = 0; i < this.count; i++) {
  29888. keys[i] = this._keys[i];
  29889. }
  29890. return keys;
  29891. }
  29892. else {
  29893. return undefined;
  29894. }
  29895. };
  29896. SmartCollection.prototype.getKeyByIndex = function (index) {
  29897. if (index < this.count && index > -1) {
  29898. return this._keys[index];
  29899. }
  29900. else {
  29901. return undefined;
  29902. }
  29903. };
  29904. SmartCollection.prototype.getItemByIndex = function (index) {
  29905. if (index < this.count && index > -1) {
  29906. return this.items[this._keys[index]];
  29907. }
  29908. else {
  29909. return undefined;
  29910. }
  29911. };
  29912. SmartCollection.prototype.empty = function () {
  29913. if (this.count > 0) {
  29914. this.count = 0;
  29915. this.items = {};
  29916. this._keys = new Array(this._initialCapacity);
  29917. }
  29918. };
  29919. return SmartCollection;
  29920. })();
  29921. BABYLON.SmartCollection = SmartCollection;
  29922. })(BABYLON || (BABYLON = {}));
  29923. //# sourceMappingURL=babylon.smartCollection.js.map