babylon.2.1-alpha.debug.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285
  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.GetClipFactor = function (vector0, vector1, axis, size) {
  589. var d0 = Vector3.Dot(vector0, axis) - size;
  590. var d1 = Vector3.Dot(vector1, axis) - size;
  591. var s = d0 / (d0 - d1);
  592. return s;
  593. };
  594. Vector3.FromArray = function (array, offset) {
  595. if (!offset) {
  596. offset = 0;
  597. }
  598. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  599. };
  600. Vector3.FromArrayToRef = function (array, offset, result) {
  601. result.x = array[offset];
  602. result.y = array[offset + 1];
  603. result.z = array[offset + 2];
  604. };
  605. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  606. result.x = array[offset];
  607. result.y = array[offset + 1];
  608. result.z = array[offset + 2];
  609. };
  610. Vector3.FromFloatsToRef = function (x, y, z, result) {
  611. result.x = x;
  612. result.y = y;
  613. result.z = z;
  614. };
  615. Vector3.Zero = function () {
  616. return new Vector3(0, 0, 0);
  617. };
  618. Vector3.Up = function () {
  619. return new Vector3(0, 1.0, 0);
  620. };
  621. Vector3.TransformCoordinates = function (vector, transformation) {
  622. var result = Vector3.Zero();
  623. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  624. return result;
  625. };
  626. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  627. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  628. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  629. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  630. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  631. result.x = x / w;
  632. result.y = y / w;
  633. result.z = z / w;
  634. };
  635. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  636. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  637. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  638. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  639. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  640. result.x = rx / rw;
  641. result.y = ry / rw;
  642. result.z = rz / rw;
  643. };
  644. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  645. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  646. var m0 = SIMD.float32x4.load(transformation.m, 0);
  647. var m1 = SIMD.float32x4.load(transformation.m, 4);
  648. var m2 = SIMD.float32x4.load(transformation.m, 8);
  649. var m3 = SIMD.float32x4.load(transformation.m, 12);
  650. 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));
  651. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  652. SIMD.float32x4.storeXYZ(result._data, 0, r);
  653. };
  654. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  655. var v0 = SIMD.float32x4.splat(x);
  656. var v1 = SIMD.float32x4.splat(y);
  657. var v2 = SIMD.float32x4.splat(z);
  658. var m0 = SIMD.float32x4.load(transformation.m, 0);
  659. var m1 = SIMD.float32x4.load(transformation.m, 4);
  660. var m2 = SIMD.float32x4.load(transformation.m, 8);
  661. var m3 = SIMD.float32x4.load(transformation.m, 12);
  662. 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));
  663. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  664. SIMD.float32x4.storeXYZ(result._data, 0, r);
  665. };
  666. Vector3.TransformNormal = function (vector, transformation) {
  667. var result = Vector3.Zero();
  668. Vector3.TransformNormalToRef(vector, transformation, result);
  669. return result;
  670. };
  671. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  672. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  673. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  674. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  675. };
  676. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  677. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  678. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  679. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  680. };
  681. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  682. var squared = amount * amount;
  683. var cubed = amount * squared;
  684. 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));
  685. 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));
  686. 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));
  687. return new Vector3(x, y, z);
  688. };
  689. Vector3.Clamp = function (value, min, max) {
  690. var x = value.x;
  691. x = (x > max.x) ? max.x : x;
  692. x = (x < min.x) ? min.x : x;
  693. var y = value.y;
  694. y = (y > max.y) ? max.y : y;
  695. y = (y < min.y) ? min.y : y;
  696. var z = value.z;
  697. z = (z > max.z) ? max.z : z;
  698. z = (z < min.z) ? min.z : z;
  699. return new Vector3(x, y, z);
  700. };
  701. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  702. var squared = amount * amount;
  703. var cubed = amount * squared;
  704. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  705. var part2 = (-2.0 * cubed) + (3.0 * squared);
  706. var part3 = (cubed - (2.0 * squared)) + amount;
  707. var part4 = cubed - squared;
  708. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  709. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  710. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Lerp = function (start, end, amount) {
  714. var x = start.x + ((end.x - start.x) * amount);
  715. var y = start.y + ((end.y - start.y) * amount);
  716. var z = start.z + ((end.z - start.z) * amount);
  717. return new Vector3(x, y, z);
  718. };
  719. Vector3.Dot = function (left, right) {
  720. return (left.x * right.x + left.y * right.y + left.z * right.z);
  721. };
  722. Vector3.Cross = function (left, right) {
  723. var result = Vector3.Zero();
  724. Vector3.CrossToRef(left, right, result);
  725. return result;
  726. };
  727. Vector3.CrossToRef = function (left, right, result) {
  728. result.x = left.y * right.z - left.z * right.y;
  729. result.y = left.z * right.x - left.x * right.z;
  730. result.z = left.x * right.y - left.y * right.x;
  731. };
  732. Vector3.Normalize = function (vector) {
  733. var result = Vector3.Zero();
  734. Vector3.NormalizeToRef(vector, result);
  735. return result;
  736. };
  737. Vector3.NormalizeToRef = function (vector, result) {
  738. result.copyFrom(vector);
  739. result.normalize();
  740. };
  741. Vector3.Project = function (vector, world, transform, viewport) {
  742. var cw = viewport.width;
  743. var ch = viewport.height;
  744. var cx = viewport.x;
  745. var cy = viewport.y;
  746. 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);
  747. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  748. return Vector3.TransformCoordinates(vector, finalMatrix);
  749. };
  750. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  751. var matrix = world.multiply(transform);
  752. matrix.invert();
  753. source.x = source.x / viewportWidth * 2 - 1;
  754. source.y = -(source.y / viewportHeight * 2 - 1);
  755. var vector = Vector3.TransformCoordinates(source, matrix);
  756. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  757. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  758. vector = vector.scale(1.0 / num);
  759. }
  760. return vector;
  761. };
  762. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  763. var matrix = world.multiply(view).multiply(projection);
  764. matrix.invert();
  765. source.x = source.x / viewportWidth * 2 - 1;
  766. source.y = -(source.y / viewportHeight * 2 - 1);
  767. var vector = Vector3.TransformCoordinates(source, matrix);
  768. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  769. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  770. vector = vector.scale(1.0 / num);
  771. }
  772. return vector;
  773. };
  774. Vector3.Minimize = function (left, right) {
  775. var min = left.clone();
  776. min.MinimizeInPlace(right);
  777. return min;
  778. };
  779. Vector3.Maximize = function (left, right) {
  780. var max = left.clone();
  781. max.MaximizeInPlace(right);
  782. return max;
  783. };
  784. Vector3.Distance = function (value1, value2) {
  785. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  786. };
  787. Vector3.DistanceSquared = function (value1, value2) {
  788. var x = value1.x - value2.x;
  789. var y = value1.y - value2.y;
  790. var z = value1.z - value2.z;
  791. return (x * x) + (y * y) + (z * z);
  792. };
  793. Vector3.Center = function (value1, value2) {
  794. var center = value1.add(value2);
  795. center.scaleInPlace(0.5);
  796. return center;
  797. };
  798. return Vector3;
  799. })();
  800. BABYLON.Vector3 = Vector3;
  801. //Vector4 class created for EulerAngle class conversion to Quaternion
  802. var Vector4 = (function () {
  803. function Vector4(x, y, z, w) {
  804. this.x = x;
  805. this.y = y;
  806. this.z = z;
  807. this.w = w;
  808. }
  809. Vector4.prototype.toString = function () {
  810. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  811. };
  812. // Operators
  813. Vector4.prototype.asArray = function () {
  814. var result = [];
  815. this.toArray(result, 0);
  816. return result;
  817. };
  818. Vector4.prototype.toArray = function (array, index) {
  819. if (index === undefined) {
  820. index = 0;
  821. }
  822. array[index] = this.x;
  823. array[index + 1] = this.y;
  824. array[index + 2] = this.z;
  825. array[index + 3] = this.w;
  826. return this;
  827. };
  828. Vector4.prototype.addInPlace = function (otherVector) {
  829. this.x += otherVector.x;
  830. this.y += otherVector.y;
  831. this.z += otherVector.z;
  832. this.w += otherVector.w;
  833. return this;
  834. };
  835. Vector4.prototype.add = function (otherVector) {
  836. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  837. };
  838. Vector4.prototype.addToRef = function (otherVector, result) {
  839. result.x = this.x + otherVector.x;
  840. result.y = this.y + otherVector.y;
  841. result.z = this.z + otherVector.z;
  842. result.w = this.w + otherVector.w;
  843. return this;
  844. };
  845. Vector4.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. this.z -= otherVector.z;
  849. this.w -= otherVector.w;
  850. return this;
  851. };
  852. Vector4.prototype.subtract = function (otherVector) {
  853. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  854. };
  855. Vector4.prototype.subtractToRef = function (otherVector, result) {
  856. result.x = this.x - otherVector.x;
  857. result.y = this.y - otherVector.y;
  858. result.z = this.z - otherVector.z;
  859. result.w = this.w - otherVector.w;
  860. return this;
  861. };
  862. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  863. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  864. };
  865. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  866. result.x = this.x - x;
  867. result.y = this.y - y;
  868. result.z = this.z - z;
  869. result.w = this.w - w;
  870. return this;
  871. };
  872. Vector4.prototype.negate = function () {
  873. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  874. };
  875. Vector4.prototype.scaleInPlace = function (scale) {
  876. this.x *= scale;
  877. this.y *= scale;
  878. this.z *= scale;
  879. this.w *= scale;
  880. return this;
  881. };
  882. Vector4.prototype.scale = function (scale) {
  883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  884. };
  885. Vector4.prototype.scaleToRef = function (scale, result) {
  886. result.x = this.x * scale;
  887. result.y = this.y * scale;
  888. result.z = this.z * scale;
  889. result.w = this.w * scale;
  890. };
  891. Vector4.prototype.equals = function (otherVector) {
  892. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  893. };
  894. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  895. 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;
  896. };
  897. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  898. return this.x === x && this.y === y && this.z === z && this.w === w;
  899. };
  900. Vector4.prototype.multiplyInPlace = function (otherVector) {
  901. this.x *= otherVector.x;
  902. this.y *= otherVector.y;
  903. this.z *= otherVector.z;
  904. this.w *= otherVector.w;
  905. return this;
  906. };
  907. Vector4.prototype.multiply = function (otherVector) {
  908. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  909. };
  910. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  911. result.x = this.x * otherVector.x;
  912. result.y = this.y * otherVector.y;
  913. result.z = this.z * otherVector.z;
  914. result.w = this.w * otherVector.w;
  915. return this;
  916. };
  917. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  918. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  919. };
  920. Vector4.prototype.divide = function (otherVector) {
  921. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  922. };
  923. Vector4.prototype.divideToRef = function (otherVector, result) {
  924. result.x = this.x / otherVector.x;
  925. result.y = this.y / otherVector.y;
  926. result.z = this.z / otherVector.z;
  927. result.w = this.w / otherVector.w;
  928. return this;
  929. };
  930. Vector4.prototype.MinimizeInPlace = function (other) {
  931. if (other.x < this.x)
  932. this.x = other.x;
  933. if (other.y < this.y)
  934. this.y = other.y;
  935. if (other.z < this.z)
  936. this.z = other.z;
  937. if (other.w < this.w)
  938. this.w = other.w;
  939. return this;
  940. };
  941. Vector4.prototype.MaximizeInPlace = function (other) {
  942. if (other.x > this.x)
  943. this.x = other.x;
  944. if (other.y > this.y)
  945. this.y = other.y;
  946. if (other.z > this.z)
  947. this.z = other.z;
  948. if (other.w > this.w)
  949. this.w = other.w;
  950. return this;
  951. };
  952. // Properties
  953. Vector4.prototype.length = function () {
  954. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  955. };
  956. Vector4.prototype.lengthSquared = function () {
  957. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  958. };
  959. // Methods
  960. Vector4.prototype.normalize = function () {
  961. var len = this.length();
  962. if (len === 0)
  963. return this;
  964. var num = 1.0 / len;
  965. this.x *= num;
  966. this.y *= num;
  967. this.z *= num;
  968. this.w *= num;
  969. return this;
  970. };
  971. Vector4.prototype.clone = function () {
  972. return new Vector4(this.x, this.y, this.z, this.w);
  973. };
  974. Vector4.prototype.copyFrom = function (source) {
  975. this.x = source.x;
  976. this.y = source.y;
  977. this.z = source.z;
  978. this.w = source.w;
  979. return this;
  980. };
  981. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. this.w = w;
  986. return this;
  987. };
  988. // Statics
  989. Vector4.FromArray = function (array, offset) {
  990. if (!offset) {
  991. offset = 0;
  992. }
  993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  994. };
  995. Vector4.FromArrayToRef = 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.FromFloatArrayToRef = function (array, offset, result) {
  1002. result.x = array[offset];
  1003. result.y = array[offset + 1];
  1004. result.z = array[offset + 2];
  1005. result.w = array[offset + 3];
  1006. };
  1007. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1008. result.x = x;
  1009. result.y = y;
  1010. result.z = z;
  1011. result.w = w;
  1012. };
  1013. Vector4.Zero = function () {
  1014. return new Vector4(0, 0, 0, 0);
  1015. };
  1016. Vector4.Normalize = function (vector) {
  1017. var result = Vector4.Zero();
  1018. Vector4.NormalizeToRef(vector, result);
  1019. return result;
  1020. };
  1021. Vector4.NormalizeToRef = function (vector, result) {
  1022. result.copyFrom(vector);
  1023. result.normalize();
  1024. };
  1025. Vector4.Minimize = function (left, right) {
  1026. var min = left.clone();
  1027. min.MinimizeInPlace(right);
  1028. return min;
  1029. };
  1030. Vector4.Maximize = function (left, right) {
  1031. var max = left.clone();
  1032. max.MaximizeInPlace(right);
  1033. return max;
  1034. };
  1035. Vector4.Distance = function (value1, value2) {
  1036. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1037. };
  1038. Vector4.DistanceSquared = function (value1, value2) {
  1039. var x = value1.x - value2.x;
  1040. var y = value1.y - value2.y;
  1041. var z = value1.z - value2.z;
  1042. var w = value1.w - value2.w;
  1043. return (x * x) + (y * y) + (z * z) + (w * w);
  1044. };
  1045. Vector4.Center = function (value1, value2) {
  1046. var center = value1.add(value2);
  1047. center.scaleInPlace(0.5);
  1048. return center;
  1049. };
  1050. return Vector4;
  1051. })();
  1052. BABYLON.Vector4 = Vector4;
  1053. var Quaternion = (function () {
  1054. function Quaternion(x, y, z, w) {
  1055. if (x === void 0) { x = 0; }
  1056. if (y === void 0) { y = 0; }
  1057. if (z === void 0) { z = 0; }
  1058. if (w === void 0) { w = 1; }
  1059. this.x = x;
  1060. this.y = y;
  1061. this.z = z;
  1062. this.w = w;
  1063. }
  1064. Quaternion.prototype.toString = function () {
  1065. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1066. };
  1067. Quaternion.prototype.asArray = function () {
  1068. return [this.x, this.y, this.z, this.w];
  1069. };
  1070. Quaternion.prototype.equals = function (otherQuaternion) {
  1071. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1072. };
  1073. Quaternion.prototype.clone = function () {
  1074. return new Quaternion(this.x, this.y, this.z, this.w);
  1075. };
  1076. Quaternion.prototype.copyFrom = function (other) {
  1077. this.x = other.x;
  1078. this.y = other.y;
  1079. this.z = other.z;
  1080. this.w = other.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1084. this.x = x;
  1085. this.y = y;
  1086. this.z = z;
  1087. this.w = w;
  1088. return this;
  1089. };
  1090. Quaternion.prototype.add = function (other) {
  1091. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1092. };
  1093. Quaternion.prototype.subtract = function (other) {
  1094. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1095. };
  1096. Quaternion.prototype.scale = function (value) {
  1097. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1098. };
  1099. Quaternion.prototype.multiply = function (q1) {
  1100. var result = new Quaternion(0, 0, 0, 1.0);
  1101. this.multiplyToRef(q1, result);
  1102. return result;
  1103. };
  1104. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1105. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1106. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1107. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1108. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1109. return this;
  1110. };
  1111. Quaternion.prototype.length = function () {
  1112. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1113. };
  1114. Quaternion.prototype.normalize = function () {
  1115. var length = 1.0 / this.length();
  1116. this.x *= length;
  1117. this.y *= length;
  1118. this.z *= length;
  1119. this.w *= length;
  1120. return this;
  1121. };
  1122. Quaternion.prototype.toEulerAngles = function () {
  1123. var result = Vector3.Zero();
  1124. this.toEulerAnglesToRef(result);
  1125. return result;
  1126. };
  1127. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1128. //result is an EulerAngles in the in the z-x-z convention
  1129. var qx = this.x;
  1130. var qy = this.y;
  1131. var qz = this.z;
  1132. var qw = this.w;
  1133. var qxy = qx * qy;
  1134. var qxz = qx * qz;
  1135. var qwy = qw * qy;
  1136. var qwz = qw * qz;
  1137. var qwx = qw * qx;
  1138. var qyz = qy * qz;
  1139. var sqx = qx * qx;
  1140. var sqy = qy * qy;
  1141. var determinant = sqx + sqy;
  1142. if (determinant !== 0.000 && determinant !== 1.000) {
  1143. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1144. result.y = Math.acos(1 - 2 * determinant);
  1145. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1146. }
  1147. else {
  1148. if (determinant === 0.0) {
  1149. result.x = 0.0;
  1150. result.y = 0.0;
  1151. 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)
  1152. }
  1153. else {
  1154. 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)
  1155. result.y = Math.PI;
  1156. result.z = 0.0;
  1157. }
  1158. }
  1159. return this;
  1160. };
  1161. Quaternion.prototype.toRotationMatrix = function (result) {
  1162. var xx = this.x * this.x;
  1163. var yy = this.y * this.y;
  1164. var zz = this.z * this.z;
  1165. var xy = this.x * this.y;
  1166. var zw = this.z * this.w;
  1167. var zx = this.z * this.x;
  1168. var yw = this.y * this.w;
  1169. var yz = this.y * this.z;
  1170. var xw = this.x * this.w;
  1171. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1172. result.m[1] = 2.0 * (xy + zw);
  1173. result.m[2] = 2.0 * (zx - yw);
  1174. result.m[3] = 0;
  1175. result.m[4] = 2.0 * (xy - zw);
  1176. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1177. result.m[6] = 2.0 * (yz + xw);
  1178. result.m[7] = 0;
  1179. result.m[8] = 2.0 * (zx + yw);
  1180. result.m[9] = 2.0 * (yz - xw);
  1181. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1182. result.m[11] = 0;
  1183. result.m[12] = 0;
  1184. result.m[13] = 0;
  1185. result.m[14] = 0;
  1186. result.m[15] = 1.0;
  1187. return this;
  1188. };
  1189. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1190. Quaternion.FromRotationMatrixToRef(matrix, this);
  1191. return this;
  1192. };
  1193. // Statics
  1194. Quaternion.FromRotationMatrix = function (matrix) {
  1195. var result = new Quaternion();
  1196. Quaternion.FromRotationMatrixToRef(matrix, result);
  1197. return result;
  1198. };
  1199. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1200. var data = matrix.m;
  1201. var m11 = data[0], m12 = data[4], m13 = data[8];
  1202. var m21 = data[1], m22 = data[5], m23 = data[9];
  1203. var m31 = data[2], m32 = data[6], m33 = data[10];
  1204. var trace = m11 + m22 + m33;
  1205. var s;
  1206. if (trace > 0) {
  1207. s = 0.5 / Math.sqrt(trace + 1.0);
  1208. result.w = 0.25 / s;
  1209. result.x = (m32 - m23) * s;
  1210. result.y = (m13 - m31) * s;
  1211. result.z = (m21 - m12) * s;
  1212. }
  1213. else if (m11 > m22 && m11 > m33) {
  1214. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1215. result.w = (m32 - m23) / s;
  1216. result.x = 0.25 * s;
  1217. result.y = (m12 + m21) / s;
  1218. result.z = (m13 + m31) / s;
  1219. }
  1220. else if (m22 > m33) {
  1221. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1222. result.w = (m13 - m31) / s;
  1223. result.x = (m12 + m21) / s;
  1224. result.y = 0.25 * s;
  1225. result.z = (m23 + m32) / s;
  1226. }
  1227. else {
  1228. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1229. result.w = (m21 - m12) / s;
  1230. result.x = (m13 + m31) / s;
  1231. result.y = (m23 + m32) / s;
  1232. result.z = 0.25 * s;
  1233. }
  1234. };
  1235. Quaternion.Inverse = function (q) {
  1236. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1237. };
  1238. Quaternion.Identity = function () {
  1239. return new Quaternion(0, 0, 0, 1);
  1240. };
  1241. Quaternion.RotationAxis = function (axis, angle) {
  1242. var result = new Quaternion();
  1243. var sin = Math.sin(angle / 2);
  1244. result.w = Math.cos(angle / 2);
  1245. result.x = axis.x * sin;
  1246. result.y = axis.y * sin;
  1247. result.z = axis.z * sin;
  1248. return result;
  1249. };
  1250. Quaternion.FromArray = function (array, offset) {
  1251. if (!offset) {
  1252. offset = 0;
  1253. }
  1254. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1255. };
  1256. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1257. var result = new Quaternion();
  1258. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1259. return result;
  1260. };
  1261. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1262. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1263. var halfRoll = roll * 0.5;
  1264. var halfPitch = pitch * 0.5;
  1265. var halfYaw = yaw * 0.5;
  1266. var sinRoll = Math.sin(halfRoll);
  1267. var cosRoll = Math.cos(halfRoll);
  1268. var sinPitch = Math.sin(halfPitch);
  1269. var cosPitch = Math.cos(halfPitch);
  1270. var sinYaw = Math.sin(halfYaw);
  1271. var cosYaw = Math.cos(halfYaw);
  1272. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1273. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1274. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1275. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1276. };
  1277. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1278. var result = new Quaternion();
  1279. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1280. return result;
  1281. };
  1282. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1283. // Produces a quaternion from Euler angles in the z-x-z orientation
  1284. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1285. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1286. var halfBeta = beta * 0.5;
  1287. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1288. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1289. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1290. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1291. };
  1292. Quaternion.Slerp = function (left, right, amount) {
  1293. var num2;
  1294. var num3;
  1295. var num = amount;
  1296. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1297. var flag = false;
  1298. if (num4 < 0) {
  1299. flag = true;
  1300. num4 = -num4;
  1301. }
  1302. if (num4 > 0.999999) {
  1303. num3 = 1 - num;
  1304. num2 = flag ? -num : num;
  1305. }
  1306. else {
  1307. var num5 = Math.acos(num4);
  1308. var num6 = (1.0 / Math.sin(num5));
  1309. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1310. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1311. }
  1312. 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));
  1313. };
  1314. return Quaternion;
  1315. })();
  1316. BABYLON.Quaternion = Quaternion;
  1317. var Matrix = (function () {
  1318. function Matrix() {
  1319. this.m = new Float32Array(16);
  1320. }
  1321. // Properties
  1322. Matrix.prototype.isIdentity = function () {
  1323. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1324. return false;
  1325. 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)
  1326. return false;
  1327. return true;
  1328. };
  1329. Matrix.prototype.determinant = function () {
  1330. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1331. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1332. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1333. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1334. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1335. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1336. 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))));
  1337. };
  1338. // Methods
  1339. Matrix.prototype.toArray = function () {
  1340. return this.m;
  1341. };
  1342. Matrix.prototype.asArray = function () {
  1343. return this.toArray();
  1344. };
  1345. Matrix.prototype.invert = function () {
  1346. this.invertToRef(this);
  1347. return this;
  1348. };
  1349. Matrix.prototype.invertToRef = function (other) {
  1350. var l1 = this.m[0];
  1351. var l2 = this.m[1];
  1352. var l3 = this.m[2];
  1353. var l4 = this.m[3];
  1354. var l5 = this.m[4];
  1355. var l6 = this.m[5];
  1356. var l7 = this.m[6];
  1357. var l8 = this.m[7];
  1358. var l9 = this.m[8];
  1359. var l10 = this.m[9];
  1360. var l11 = this.m[10];
  1361. var l12 = this.m[11];
  1362. var l13 = this.m[12];
  1363. var l14 = this.m[13];
  1364. var l15 = this.m[14];
  1365. var l16 = this.m[15];
  1366. var l17 = (l11 * l16) - (l12 * l15);
  1367. var l18 = (l10 * l16) - (l12 * l14);
  1368. var l19 = (l10 * l15) - (l11 * l14);
  1369. var l20 = (l9 * l16) - (l12 * l13);
  1370. var l21 = (l9 * l15) - (l11 * l13);
  1371. var l22 = (l9 * l14) - (l10 * l13);
  1372. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1373. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1374. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1375. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1376. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1377. var l28 = (l7 * l16) - (l8 * l15);
  1378. var l29 = (l6 * l16) - (l8 * l14);
  1379. var l30 = (l6 * l15) - (l7 * l14);
  1380. var l31 = (l5 * l16) - (l8 * l13);
  1381. var l32 = (l5 * l15) - (l7 * l13);
  1382. var l33 = (l5 * l14) - (l6 * l13);
  1383. var l34 = (l7 * l12) - (l8 * l11);
  1384. var l35 = (l6 * l12) - (l8 * l10);
  1385. var l36 = (l6 * l11) - (l7 * l10);
  1386. var l37 = (l5 * l12) - (l8 * l9);
  1387. var l38 = (l5 * l11) - (l7 * l9);
  1388. var l39 = (l5 * l10) - (l6 * l9);
  1389. other.m[0] = l23 * l27;
  1390. other.m[4] = l24 * l27;
  1391. other.m[8] = l25 * l27;
  1392. other.m[12] = l26 * l27;
  1393. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1394. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1395. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1396. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1397. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1398. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1399. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1400. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1401. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1402. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1403. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1404. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1405. return this;
  1406. };
  1407. Matrix.prototype.invertToRefSIMD = function (other) {
  1408. var src = this.m;
  1409. var dest = other.m;
  1410. var row0, row1, row2, row3;
  1411. var tmp1;
  1412. var minor0, minor1, minor2, minor3;
  1413. var det;
  1414. // Load the 4 rows
  1415. var src0 = SIMD.float32x4.load(src, 0);
  1416. var src1 = SIMD.float32x4.load(src, 4);
  1417. var src2 = SIMD.float32x4.load(src, 8);
  1418. var src3 = SIMD.float32x4.load(src, 12);
  1419. // Transpose the source matrix. Sort of. Not a true transpose operation
  1420. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1421. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1422. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1423. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1424. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1425. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1426. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1427. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1428. // This is a true transposition, but it will lead to an incorrect result
  1429. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1430. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1431. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1432. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1433. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1434. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1435. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1436. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1437. // ----
  1438. tmp1 = SIMD.float32x4.mul(row2, row3);
  1439. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1440. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1441. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1443. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1444. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1445. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. // ----
  1447. tmp1 = SIMD.float32x4.mul(row1, row2);
  1448. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1449. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1450. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1452. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1453. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1454. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1455. // ----
  1456. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1457. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1458. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1460. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1462. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1463. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1464. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1465. // ----
  1466. tmp1 = SIMD.float32x4.mul(row0, row1);
  1467. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1468. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1469. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1470. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1471. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1472. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1473. // ----
  1474. tmp1 = SIMD.float32x4.mul(row0, row3);
  1475. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1476. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1477. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1478. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1479. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1480. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1481. // ----
  1482. tmp1 = SIMD.float32x4.mul(row0, row2);
  1483. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1484. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1485. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1486. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1487. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1488. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1489. // Compute determinant
  1490. det = SIMD.float32x4.mul(row0, minor0);
  1491. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1492. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1493. tmp1 = SIMD.float32x4.reciprocal(det);
  1494. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1495. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1496. // These shuffles aren't necessary if the faulty transposition is done
  1497. // up at the top of this function.
  1498. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1499. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1500. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1501. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1502. // Compute final values by multiplying with 1/det
  1503. minor0 = SIMD.float32x4.mul(det, minor0);
  1504. minor1 = SIMD.float32x4.mul(det, minor1);
  1505. minor2 = SIMD.float32x4.mul(det, minor2);
  1506. minor3 = SIMD.float32x4.mul(det, minor3);
  1507. SIMD.float32x4.store(dest, 0, minor0);
  1508. SIMD.float32x4.store(dest, 4, minor1);
  1509. SIMD.float32x4.store(dest, 8, minor2);
  1510. SIMD.float32x4.store(dest, 12, minor3);
  1511. return this;
  1512. };
  1513. Matrix.prototype.setTranslation = function (vector3) {
  1514. this.m[12] = vector3.x;
  1515. this.m[13] = vector3.y;
  1516. this.m[14] = vector3.z;
  1517. return this;
  1518. };
  1519. Matrix.prototype.multiply = function (other) {
  1520. var result = new Matrix();
  1521. this.multiplyToRef(other, result);
  1522. return result;
  1523. };
  1524. Matrix.prototype.copyFrom = function (other) {
  1525. for (var index = 0; index < 16; index++) {
  1526. this.m[index] = other.m[index];
  1527. }
  1528. return this;
  1529. };
  1530. Matrix.prototype.copyToArray = function (array, offset) {
  1531. if (offset === void 0) { offset = 0; }
  1532. for (var index = 0; index < 16; index++) {
  1533. array[offset + index] = this.m[index];
  1534. }
  1535. return this;
  1536. };
  1537. Matrix.prototype.multiplyToRef = function (other, result) {
  1538. this.multiplyToArray(other, result.m, 0);
  1539. return this;
  1540. };
  1541. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1542. var tm0 = this.m[0];
  1543. var tm1 = this.m[1];
  1544. var tm2 = this.m[2];
  1545. var tm3 = this.m[3];
  1546. var tm4 = this.m[4];
  1547. var tm5 = this.m[5];
  1548. var tm6 = this.m[6];
  1549. var tm7 = this.m[7];
  1550. var tm8 = this.m[8];
  1551. var tm9 = this.m[9];
  1552. var tm10 = this.m[10];
  1553. var tm11 = this.m[11];
  1554. var tm12 = this.m[12];
  1555. var tm13 = this.m[13];
  1556. var tm14 = this.m[14];
  1557. var tm15 = this.m[15];
  1558. var om0 = other.m[0];
  1559. var om1 = other.m[1];
  1560. var om2 = other.m[2];
  1561. var om3 = other.m[3];
  1562. var om4 = other.m[4];
  1563. var om5 = other.m[5];
  1564. var om6 = other.m[6];
  1565. var om7 = other.m[7];
  1566. var om8 = other.m[8];
  1567. var om9 = other.m[9];
  1568. var om10 = other.m[10];
  1569. var om11 = other.m[11];
  1570. var om12 = other.m[12];
  1571. var om13 = other.m[13];
  1572. var om14 = other.m[14];
  1573. var om15 = other.m[15];
  1574. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1575. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1576. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1577. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1578. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1579. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1580. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1581. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1582. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1583. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1584. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1585. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1586. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1587. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1588. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1589. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1590. return this;
  1591. };
  1592. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1593. if (offset === void 0) { offset = 0; }
  1594. var tm = this.m;
  1595. var om = other.m;
  1596. var om0 = SIMD.float32x4.load(om, 0);
  1597. var om1 = SIMD.float32x4.load(om, 4);
  1598. var om2 = SIMD.float32x4.load(om, 8);
  1599. var om3 = SIMD.float32x4.load(om, 12);
  1600. var tm0 = SIMD.float32x4.load(tm, 0);
  1601. 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)))));
  1602. var tm1 = SIMD.float32x4.load(tm, 4);
  1603. 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)))));
  1604. var tm2 = SIMD.float32x4.load(tm, 8);
  1605. 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)))));
  1606. var tm3 = SIMD.float32x4.load(tm, 12);
  1607. 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)))));
  1608. };
  1609. Matrix.prototype.equals = function (value) {
  1610. 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]);
  1611. };
  1612. Matrix.prototype.clone = function () {
  1613. 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]);
  1614. };
  1615. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1616. translation.x = this.m[12];
  1617. translation.y = this.m[13];
  1618. translation.z = this.m[14];
  1619. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1620. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1621. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1622. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1623. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1624. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1625. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1626. rotation.x = 0;
  1627. rotation.y = 0;
  1628. rotation.z = 0;
  1629. rotation.w = 1;
  1630. return false;
  1631. }
  1632. 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);
  1633. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1634. return true;
  1635. };
  1636. // Statics
  1637. Matrix.FromArray = function (array, offset) {
  1638. var result = new Matrix();
  1639. if (!offset) {
  1640. offset = 0;
  1641. }
  1642. Matrix.FromArrayToRef(array, offset, result);
  1643. return result;
  1644. };
  1645. Matrix.FromArrayToRef = function (array, offset, result) {
  1646. for (var index = 0; index < 16; index++) {
  1647. result.m[index] = array[index + offset];
  1648. }
  1649. };
  1650. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1651. result.m[0] = initialM11;
  1652. result.m[1] = initialM12;
  1653. result.m[2] = initialM13;
  1654. result.m[3] = initialM14;
  1655. result.m[4] = initialM21;
  1656. result.m[5] = initialM22;
  1657. result.m[6] = initialM23;
  1658. result.m[7] = initialM24;
  1659. result.m[8] = initialM31;
  1660. result.m[9] = initialM32;
  1661. result.m[10] = initialM33;
  1662. result.m[11] = initialM34;
  1663. result.m[12] = initialM41;
  1664. result.m[13] = initialM42;
  1665. result.m[14] = initialM43;
  1666. result.m[15] = initialM44;
  1667. };
  1668. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1669. var result = new Matrix();
  1670. result.m[0] = initialM11;
  1671. result.m[1] = initialM12;
  1672. result.m[2] = initialM13;
  1673. result.m[3] = initialM14;
  1674. result.m[4] = initialM21;
  1675. result.m[5] = initialM22;
  1676. result.m[6] = initialM23;
  1677. result.m[7] = initialM24;
  1678. result.m[8] = initialM31;
  1679. result.m[9] = initialM32;
  1680. result.m[10] = initialM33;
  1681. result.m[11] = initialM34;
  1682. result.m[12] = initialM41;
  1683. result.m[13] = initialM42;
  1684. result.m[14] = initialM43;
  1685. result.m[15] = initialM44;
  1686. return result;
  1687. };
  1688. Matrix.Compose = function (scale, rotation, translation) {
  1689. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1690. var rotationMatrix = Matrix.Identity();
  1691. rotation.toRotationMatrix(rotationMatrix);
  1692. result = result.multiply(rotationMatrix);
  1693. result.setTranslation(translation);
  1694. return result;
  1695. };
  1696. Matrix.Identity = function () {
  1697. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1698. };
  1699. Matrix.IdentityToRef = function (result) {
  1700. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1701. };
  1702. Matrix.Zero = function () {
  1703. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1704. };
  1705. Matrix.RotationX = function (angle) {
  1706. var result = new Matrix();
  1707. Matrix.RotationXToRef(angle, result);
  1708. return result;
  1709. };
  1710. Matrix.Invert = function (source) {
  1711. var result = new Matrix();
  1712. source.invertToRef(result);
  1713. return result;
  1714. };
  1715. Matrix.RotationXToRef = function (angle, result) {
  1716. var s = Math.sin(angle);
  1717. var c = Math.cos(angle);
  1718. result.m[0] = 1.0;
  1719. result.m[15] = 1.0;
  1720. result.m[5] = c;
  1721. result.m[10] = c;
  1722. result.m[9] = -s;
  1723. result.m[6] = s;
  1724. result.m[1] = 0;
  1725. result.m[2] = 0;
  1726. result.m[3] = 0;
  1727. result.m[4] = 0;
  1728. result.m[7] = 0;
  1729. result.m[8] = 0;
  1730. result.m[11] = 0;
  1731. result.m[12] = 0;
  1732. result.m[13] = 0;
  1733. result.m[14] = 0;
  1734. };
  1735. Matrix.RotationY = function (angle) {
  1736. var result = new Matrix();
  1737. Matrix.RotationYToRef(angle, result);
  1738. return result;
  1739. };
  1740. Matrix.RotationYToRef = function (angle, result) {
  1741. var s = Math.sin(angle);
  1742. var c = Math.cos(angle);
  1743. result.m[5] = 1.0;
  1744. result.m[15] = 1.0;
  1745. result.m[0] = c;
  1746. result.m[2] = -s;
  1747. result.m[8] = s;
  1748. result.m[10] = c;
  1749. result.m[1] = 0;
  1750. result.m[3] = 0;
  1751. result.m[4] = 0;
  1752. result.m[6] = 0;
  1753. result.m[7] = 0;
  1754. result.m[9] = 0;
  1755. result.m[11] = 0;
  1756. result.m[12] = 0;
  1757. result.m[13] = 0;
  1758. result.m[14] = 0;
  1759. };
  1760. Matrix.RotationZ = function (angle) {
  1761. var result = new Matrix();
  1762. Matrix.RotationZToRef(angle, result);
  1763. return result;
  1764. };
  1765. Matrix.RotationZToRef = function (angle, result) {
  1766. var s = Math.sin(angle);
  1767. var c = Math.cos(angle);
  1768. result.m[10] = 1.0;
  1769. result.m[15] = 1.0;
  1770. result.m[0] = c;
  1771. result.m[1] = s;
  1772. result.m[4] = -s;
  1773. result.m[5] = c;
  1774. result.m[2] = 0;
  1775. result.m[3] = 0;
  1776. result.m[6] = 0;
  1777. result.m[7] = 0;
  1778. result.m[8] = 0;
  1779. result.m[9] = 0;
  1780. result.m[11] = 0;
  1781. result.m[12] = 0;
  1782. result.m[13] = 0;
  1783. result.m[14] = 0;
  1784. };
  1785. Matrix.RotationAxis = function (axis, angle) {
  1786. var s = Math.sin(-angle);
  1787. var c = Math.cos(-angle);
  1788. var c1 = 1 - c;
  1789. axis.normalize();
  1790. var result = Matrix.Zero();
  1791. result.m[0] = (axis.x * axis.x) * c1 + c;
  1792. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1793. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1794. result.m[3] = 0.0;
  1795. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1796. result.m[5] = (axis.y * axis.y) * c1 + c;
  1797. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1798. result.m[7] = 0.0;
  1799. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1800. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1801. result.m[10] = (axis.z * axis.z) * c1 + c;
  1802. result.m[11] = 0.0;
  1803. result.m[15] = 1.0;
  1804. return result;
  1805. };
  1806. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1807. var result = new Matrix();
  1808. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1809. return result;
  1810. };
  1811. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1812. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1813. this._tempQuaternion.toRotationMatrix(result);
  1814. };
  1815. Matrix.Scaling = function (x, y, z) {
  1816. var result = Matrix.Zero();
  1817. Matrix.ScalingToRef(x, y, z, result);
  1818. return result;
  1819. };
  1820. Matrix.ScalingToRef = function (x, y, z, result) {
  1821. result.m[0] = x;
  1822. result.m[1] = 0;
  1823. result.m[2] = 0;
  1824. result.m[3] = 0;
  1825. result.m[4] = 0;
  1826. result.m[5] = y;
  1827. result.m[6] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[9] = 0;
  1831. result.m[10] = z;
  1832. result.m[11] = 0;
  1833. result.m[12] = 0;
  1834. result.m[13] = 0;
  1835. result.m[14] = 0;
  1836. result.m[15] = 1.0;
  1837. };
  1838. Matrix.Translation = function (x, y, z) {
  1839. var result = Matrix.Identity();
  1840. Matrix.TranslationToRef(x, y, z, result);
  1841. return result;
  1842. };
  1843. Matrix.TranslationToRef = function (x, y, z, result) {
  1844. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1845. };
  1846. Matrix.LookAtLH = function (eye, target, up) {
  1847. var result = Matrix.Zero();
  1848. Matrix.LookAtLHToRef(eye, target, up, result);
  1849. return result;
  1850. };
  1851. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1852. // Z axis
  1853. target.subtractToRef(eye, this._zAxis);
  1854. this._zAxis.normalize();
  1855. // X axis
  1856. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1857. this._xAxis.normalize();
  1858. // Y axis
  1859. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1860. this._yAxis.normalize();
  1861. // Eye angles
  1862. var ex = -Vector3.Dot(this._xAxis, eye);
  1863. var ey = -Vector3.Dot(this._yAxis, eye);
  1864. var ez = -Vector3.Dot(this._zAxis, eye);
  1865. 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);
  1866. };
  1867. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1868. var out = result.m;
  1869. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1870. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1871. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1872. // cc.kmVec3Subtract(f, pCenter, pEye);
  1873. var f = SIMD.float32x4.sub(center, eye);
  1874. // cc.kmVec3Normalize(f, f);
  1875. var tmp = SIMD.float32x4.mul(f, f);
  1876. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1877. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrt(tmp));
  1878. // cc.kmVec3Assign(up, pUp);
  1879. // cc.kmVec3Normalize(up, up);
  1880. tmp = SIMD.float32x4.mul(up, up);
  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. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrt(tmp));
  1883. // cc.kmVec3Cross(s, f, up);
  1884. 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)));
  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.kmVec3Cross(u, s, f);
  1890. 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)));
  1891. // cc.kmVec3Normalize(s, s);
  1892. tmp = SIMD.float32x4.mul(s, s);
  1893. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1894. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1895. //cc.kmMat4Identity(pOut);
  1896. //pOut.mat[0] = s.x;
  1897. //pOut.mat[4] = s.y;
  1898. //pOut.mat[8] = s.z;
  1899. //pOut.mat[1] = u.x;
  1900. //pOut.mat[5] = u.y;
  1901. //pOut.mat[9] = u.z;
  1902. //pOut.mat[2] = -f.x;
  1903. //pOut.mat[6] = -f.y;
  1904. //pOut.mat[10] = -f.z;
  1905. var zero = SIMD.float32x4.splat(0.0);
  1906. s = SIMD.float32x4.neg(s);
  1907. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1908. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1909. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1910. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1911. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1912. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1913. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1914. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1915. // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z);
  1916. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1917. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1918. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1919. var b3 = SIMD.float32x4.neg(eye);
  1920. b3 = SIMD.float32x4.withW(b3, 1.0);
  1921. // cc.kmMat4Multiply(pOut, pOut, translate);
  1922. 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)))));
  1923. 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)))));
  1924. 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)))));
  1925. 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)))));
  1926. };
  1927. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1928. var matrix = Matrix.Zero();
  1929. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1930. return matrix;
  1931. };
  1932. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1933. var hw = 2.0 / width;
  1934. var hh = 2.0 / height;
  1935. var id = 1.0 / (zfar - znear);
  1936. var nid = znear / (znear - zfar);
  1937. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1938. };
  1939. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1940. var matrix = Matrix.Zero();
  1941. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1942. return matrix;
  1943. };
  1944. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1945. result.m[0] = 2.0 / (right - left);
  1946. result.m[1] = result.m[2] = result.m[3] = 0;
  1947. result.m[5] = 2.0 / (top - bottom);
  1948. result.m[4] = result.m[6] = result.m[7] = 0;
  1949. result.m[10] = -1.0 / (znear - zfar);
  1950. result.m[8] = result.m[9] = result.m[11] = 0;
  1951. result.m[12] = (left + right) / (left - right);
  1952. result.m[13] = (top + bottom) / (bottom - top);
  1953. result.m[14] = znear / (znear - zfar);
  1954. result.m[15] = 1.0;
  1955. };
  1956. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1957. var matrix = Matrix.Zero();
  1958. matrix.m[0] = (2.0 * znear) / width;
  1959. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1960. matrix.m[5] = (2.0 * znear) / height;
  1961. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1962. matrix.m[10] = -zfar / (znear - zfar);
  1963. matrix.m[8] = matrix.m[9] = 0.0;
  1964. matrix.m[11] = 1.0;
  1965. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1966. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1967. return matrix;
  1968. };
  1969. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1970. var matrix = Matrix.Zero();
  1971. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1972. return matrix;
  1973. };
  1974. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1975. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1976. var tan = 1.0 / (Math.tan(fov * 0.5));
  1977. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1978. if (v_fixed) {
  1979. result.m[0] = tan / aspect;
  1980. }
  1981. else {
  1982. result.m[0] = tan;
  1983. }
  1984. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1985. if (v_fixed) {
  1986. result.m[5] = tan;
  1987. }
  1988. else {
  1989. result.m[5] = tan * aspect;
  1990. }
  1991. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1992. result.m[8] = result.m[9] = 0.0;
  1993. result.m[10] = -zfar / (znear - zfar);
  1994. result.m[11] = 1.0;
  1995. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1996. result.m[14] = (znear * zfar) / (znear - zfar);
  1997. };
  1998. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1999. var cw = viewport.width;
  2000. var ch = viewport.height;
  2001. var cx = viewport.x;
  2002. var cy = viewport.y;
  2003. 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);
  2004. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2005. };
  2006. Matrix.Transpose = function (matrix) {
  2007. var result = new Matrix();
  2008. result.m[0] = matrix.m[0];
  2009. result.m[1] = matrix.m[4];
  2010. result.m[2] = matrix.m[8];
  2011. result.m[3] = matrix.m[12];
  2012. result.m[4] = matrix.m[1];
  2013. result.m[5] = matrix.m[5];
  2014. result.m[6] = matrix.m[9];
  2015. result.m[7] = matrix.m[13];
  2016. result.m[8] = matrix.m[2];
  2017. result.m[9] = matrix.m[6];
  2018. result.m[10] = matrix.m[10];
  2019. result.m[11] = matrix.m[14];
  2020. result.m[12] = matrix.m[3];
  2021. result.m[13] = matrix.m[7];
  2022. result.m[14] = matrix.m[11];
  2023. result.m[15] = matrix.m[15];
  2024. return result;
  2025. };
  2026. Matrix.Reflection = function (plane) {
  2027. var matrix = new Matrix();
  2028. Matrix.ReflectionToRef(plane, matrix);
  2029. return matrix;
  2030. };
  2031. Matrix.ReflectionToRef = function (plane, result) {
  2032. plane.normalize();
  2033. var x = plane.normal.x;
  2034. var y = plane.normal.y;
  2035. var z = plane.normal.z;
  2036. var temp = -2 * x;
  2037. var temp2 = -2 * y;
  2038. var temp3 = -2 * z;
  2039. result.m[0] = (temp * x) + 1;
  2040. result.m[1] = temp2 * x;
  2041. result.m[2] = temp3 * x;
  2042. result.m[3] = 0.0;
  2043. result.m[4] = temp * y;
  2044. result.m[5] = (temp2 * y) + 1;
  2045. result.m[6] = temp3 * y;
  2046. result.m[7] = 0.0;
  2047. result.m[8] = temp * z;
  2048. result.m[9] = temp2 * z;
  2049. result.m[10] = (temp3 * z) + 1;
  2050. result.m[11] = 0.0;
  2051. result.m[12] = temp * plane.d;
  2052. result.m[13] = temp2 * plane.d;
  2053. result.m[14] = temp3 * plane.d;
  2054. result.m[15] = 1.0;
  2055. };
  2056. Matrix._tempQuaternion = new Quaternion();
  2057. Matrix._xAxis = Vector3.Zero();
  2058. Matrix._yAxis = Vector3.Zero();
  2059. Matrix._zAxis = Vector3.Zero();
  2060. return Matrix;
  2061. })();
  2062. BABYLON.Matrix = Matrix;
  2063. var Plane = (function () {
  2064. function Plane(a, b, c, d) {
  2065. this.normal = new Vector3(a, b, c);
  2066. this.d = d;
  2067. }
  2068. Plane.prototype.asArray = function () {
  2069. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2070. };
  2071. // Methods
  2072. Plane.prototype.clone = function () {
  2073. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2074. };
  2075. Plane.prototype.normalize = function () {
  2076. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2077. var magnitude = 0;
  2078. if (norm !== 0) {
  2079. magnitude = 1.0 / norm;
  2080. }
  2081. this.normal.x *= magnitude;
  2082. this.normal.y *= magnitude;
  2083. this.normal.z *= magnitude;
  2084. this.d *= magnitude;
  2085. return this;
  2086. };
  2087. Plane.prototype.transform = function (transformation) {
  2088. var transposedMatrix = Matrix.Transpose(transformation);
  2089. var x = this.normal.x;
  2090. var y = this.normal.y;
  2091. var z = this.normal.z;
  2092. var d = this.d;
  2093. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2094. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2095. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2096. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2097. return new Plane(normalX, normalY, normalZ, finalD);
  2098. };
  2099. Plane.prototype.dotCoordinate = function (point) {
  2100. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2101. };
  2102. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2103. var x1 = point2.x - point1.x;
  2104. var y1 = point2.y - point1.y;
  2105. var z1 = point2.z - point1.z;
  2106. var x2 = point3.x - point1.x;
  2107. var y2 = point3.y - point1.y;
  2108. var z2 = point3.z - point1.z;
  2109. var yz = (y1 * z2) - (z1 * y2);
  2110. var xz = (z1 * x2) - (x1 * z2);
  2111. var xy = (x1 * y2) - (y1 * x2);
  2112. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2113. var invPyth;
  2114. if (pyth !== 0) {
  2115. invPyth = 1.0 / pyth;
  2116. }
  2117. else {
  2118. invPyth = 0;
  2119. }
  2120. this.normal.x = yz * invPyth;
  2121. this.normal.y = xz * invPyth;
  2122. this.normal.z = xy * invPyth;
  2123. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2124. return this;
  2125. };
  2126. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2127. var dot = Vector3.Dot(this.normal, direction);
  2128. return (dot <= epsilon);
  2129. };
  2130. Plane.prototype.signedDistanceTo = function (point) {
  2131. return Vector3.Dot(point, this.normal) + this.d;
  2132. };
  2133. // Statics
  2134. Plane.FromArray = function (array) {
  2135. return new Plane(array[0], array[1], array[2], array[3]);
  2136. };
  2137. Plane.FromPoints = function (point1, point2, point3) {
  2138. var result = new Plane(0, 0, 0, 0);
  2139. result.copyFromPoints(point1, point2, point3);
  2140. return result;
  2141. };
  2142. Plane.FromPositionAndNormal = function (origin, normal) {
  2143. var result = new Plane(0, 0, 0, 0);
  2144. normal.normalize();
  2145. result.normal = normal;
  2146. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2147. return result;
  2148. };
  2149. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2150. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2151. return Vector3.Dot(point, normal) + d;
  2152. };
  2153. return Plane;
  2154. })();
  2155. BABYLON.Plane = Plane;
  2156. var Viewport = (function () {
  2157. function Viewport(x, y, width, height) {
  2158. this.x = x;
  2159. this.y = y;
  2160. this.width = width;
  2161. this.height = height;
  2162. }
  2163. Viewport.prototype.toGlobal = function (engine) {
  2164. var width = engine.getRenderWidth();
  2165. var height = engine.getRenderHeight();
  2166. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2167. };
  2168. return Viewport;
  2169. })();
  2170. BABYLON.Viewport = Viewport;
  2171. var Frustum = (function () {
  2172. function Frustum() {
  2173. }
  2174. Frustum.GetPlanes = function (transform) {
  2175. var frustumPlanes = [];
  2176. for (var index = 0; index < 6; index++) {
  2177. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2178. }
  2179. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2180. return frustumPlanes;
  2181. };
  2182. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2183. // Near
  2184. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2185. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2186. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2187. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2188. frustumPlanes[0].normalize();
  2189. // Far
  2190. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2191. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2192. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2193. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2194. frustumPlanes[1].normalize();
  2195. // Left
  2196. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2197. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2198. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2199. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2200. frustumPlanes[2].normalize();
  2201. // Right
  2202. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2203. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2204. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2205. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2206. frustumPlanes[3].normalize();
  2207. // Top
  2208. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2209. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2210. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2211. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2212. frustumPlanes[4].normalize();
  2213. // Bottom
  2214. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2215. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2216. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2217. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2218. frustumPlanes[5].normalize();
  2219. };
  2220. return Frustum;
  2221. })();
  2222. BABYLON.Frustum = Frustum;
  2223. var Ray = (function () {
  2224. function Ray(origin, direction, length) {
  2225. if (length === void 0) { length = Number.MAX_VALUE; }
  2226. this.origin = origin;
  2227. this.direction = direction;
  2228. this.length = length;
  2229. }
  2230. // Methods
  2231. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2232. var d = 0.0;
  2233. var maxValue = Number.MAX_VALUE;
  2234. if (Math.abs(this.direction.x) < 0.0000001) {
  2235. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2236. return false;
  2237. }
  2238. }
  2239. else {
  2240. var inv = 1.0 / this.direction.x;
  2241. var min = (minimum.x - this.origin.x) * inv;
  2242. var max = (maximum.x - this.origin.x) * inv;
  2243. if (max === -Infinity) {
  2244. max = Infinity;
  2245. }
  2246. if (min > max) {
  2247. var temp = min;
  2248. min = max;
  2249. max = temp;
  2250. }
  2251. d = Math.max(min, d);
  2252. maxValue = Math.min(max, maxValue);
  2253. if (d > maxValue) {
  2254. return false;
  2255. }
  2256. }
  2257. if (Math.abs(this.direction.y) < 0.0000001) {
  2258. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2259. return false;
  2260. }
  2261. }
  2262. else {
  2263. inv = 1.0 / this.direction.y;
  2264. min = (minimum.y - this.origin.y) * inv;
  2265. max = (maximum.y - this.origin.y) * inv;
  2266. if (max === -Infinity) {
  2267. max = Infinity;
  2268. }
  2269. if (min > max) {
  2270. temp = min;
  2271. min = max;
  2272. max = temp;
  2273. }
  2274. d = Math.max(min, d);
  2275. maxValue = Math.min(max, maxValue);
  2276. if (d > maxValue) {
  2277. return false;
  2278. }
  2279. }
  2280. if (Math.abs(this.direction.z) < 0.0000001) {
  2281. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2282. return false;
  2283. }
  2284. }
  2285. else {
  2286. inv = 1.0 / this.direction.z;
  2287. min = (minimum.z - this.origin.z) * inv;
  2288. max = (maximum.z - this.origin.z) * inv;
  2289. if (max === -Infinity) {
  2290. max = Infinity;
  2291. }
  2292. if (min > max) {
  2293. temp = min;
  2294. min = max;
  2295. max = temp;
  2296. }
  2297. d = Math.max(min, d);
  2298. maxValue = Math.min(max, maxValue);
  2299. if (d > maxValue) {
  2300. return false;
  2301. }
  2302. }
  2303. return true;
  2304. };
  2305. Ray.prototype.intersectsBox = function (box) {
  2306. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2307. };
  2308. Ray.prototype.intersectsSphere = function (sphere) {
  2309. var x = sphere.center.x - this.origin.x;
  2310. var y = sphere.center.y - this.origin.y;
  2311. var z = sphere.center.z - this.origin.z;
  2312. var pyth = (x * x) + (y * y) + (z * z);
  2313. var rr = sphere.radius * sphere.radius;
  2314. if (pyth <= rr) {
  2315. return true;
  2316. }
  2317. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2318. if (dot < 0.0) {
  2319. return false;
  2320. }
  2321. var temp = pyth - (dot * dot);
  2322. return temp <= rr;
  2323. };
  2324. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2325. if (!this._edge1) {
  2326. this._edge1 = Vector3.Zero();
  2327. this._edge2 = Vector3.Zero();
  2328. this._pvec = Vector3.Zero();
  2329. this._tvec = Vector3.Zero();
  2330. this._qvec = Vector3.Zero();
  2331. }
  2332. vertex1.subtractToRef(vertex0, this._edge1);
  2333. vertex2.subtractToRef(vertex0, this._edge2);
  2334. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2335. var det = Vector3.Dot(this._edge1, this._pvec);
  2336. if (det === 0) {
  2337. return null;
  2338. }
  2339. var invdet = 1 / det;
  2340. this.origin.subtractToRef(vertex0, this._tvec);
  2341. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2342. if (bu < 0 || bu > 1.0) {
  2343. return null;
  2344. }
  2345. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2346. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2347. if (bv < 0 || bu + bv > 1.0) {
  2348. return null;
  2349. }
  2350. //check if the distance is longer than the predefined length.
  2351. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2352. if (distance > this.length) {
  2353. return null;
  2354. }
  2355. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2356. };
  2357. // Statics
  2358. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2359. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2360. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2361. var direction = end.subtract(start);
  2362. direction.normalize();
  2363. return new Ray(start, direction);
  2364. };
  2365. /**
  2366. * 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
  2367. * transformed to the given world matrix.
  2368. * @param origin The origin point
  2369. * @param end The end point
  2370. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2371. */
  2372. Ray.CreateNewFromTo = function (origin, end, world) {
  2373. if (world === void 0) { world = Matrix.Identity(); }
  2374. var direction = end.subtract(origin);
  2375. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2376. direction.normalize();
  2377. return Ray.Transform(new Ray(origin, direction, length), world);
  2378. };
  2379. Ray.Transform = function (ray, matrix) {
  2380. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2381. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2382. return new Ray(newOrigin, newDirection, ray.length);
  2383. };
  2384. return Ray;
  2385. })();
  2386. BABYLON.Ray = Ray;
  2387. (function (Space) {
  2388. Space[Space["LOCAL"] = 0] = "LOCAL";
  2389. Space[Space["WORLD"] = 1] = "WORLD";
  2390. })(BABYLON.Space || (BABYLON.Space = {}));
  2391. var Space = BABYLON.Space;
  2392. var Axis = (function () {
  2393. function Axis() {
  2394. }
  2395. Axis.X = new Vector3(1, 0, 0);
  2396. Axis.Y = new Vector3(0, 1, 0);
  2397. Axis.Z = new Vector3(0, 0, 1);
  2398. return Axis;
  2399. })();
  2400. BABYLON.Axis = Axis;
  2401. ;
  2402. var BezierCurve = (function () {
  2403. function BezierCurve() {
  2404. }
  2405. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2406. // Extract X (which is equal to time here)
  2407. var f0 = 1 - 3 * x2 + 3 * x1;
  2408. var f1 = 3 * x2 - 6 * x1;
  2409. var f2 = 3 * x1;
  2410. var refinedT = t;
  2411. for (var i = 0; i < 5; i++) {
  2412. var refinedT2 = refinedT * refinedT;
  2413. var refinedT3 = refinedT2 * refinedT;
  2414. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2415. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2416. refinedT -= (x - t) * slope;
  2417. refinedT = Math.min(1, Math.max(0, refinedT));
  2418. }
  2419. // Resolve cubic bezier for the given x
  2420. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2421. };
  2422. return BezierCurve;
  2423. })();
  2424. BABYLON.BezierCurve = BezierCurve;
  2425. (function (Orientation) {
  2426. Orientation[Orientation["CW"] = 0] = "CW";
  2427. Orientation[Orientation["CCW"] = 1] = "CCW";
  2428. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2429. var Orientation = BABYLON.Orientation;
  2430. var Angle = (function () {
  2431. function Angle(radians) {
  2432. var _this = this;
  2433. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2434. this.radians = function () { return _this._radians; };
  2435. this._radians = radians;
  2436. if (this._radians < 0)
  2437. this._radians += (2 * Math.PI);
  2438. }
  2439. Angle.BetweenTwoPoints = function (a, b) {
  2440. var delta = b.subtract(a);
  2441. var theta = Math.atan2(delta.y, delta.x);
  2442. return new Angle(theta);
  2443. };
  2444. Angle.FromRadians = function (radians) {
  2445. return new Angle(radians);
  2446. };
  2447. Angle.FromDegrees = function (degrees) {
  2448. return new Angle(degrees * Math.PI / 180);
  2449. };
  2450. return Angle;
  2451. })();
  2452. BABYLON.Angle = Angle;
  2453. var Arc2 = (function () {
  2454. function Arc2(startPoint, midPoint, endPoint) {
  2455. this.startPoint = startPoint;
  2456. this.midPoint = midPoint;
  2457. this.endPoint = endPoint;
  2458. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2459. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2460. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2461. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2462. 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);
  2463. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2464. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2465. var a1 = this.startAngle.degrees();
  2466. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2467. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2468. // angles correction
  2469. if (a2 - a1 > +180.0)
  2470. a2 -= 360.0;
  2471. if (a2 - a1 < -180.0)
  2472. a2 += 360.0;
  2473. if (a3 - a2 > +180.0)
  2474. a3 -= 360.0;
  2475. if (a3 - a2 < -180.0)
  2476. a3 += 360.0;
  2477. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2478. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2479. }
  2480. return Arc2;
  2481. })();
  2482. BABYLON.Arc2 = Arc2;
  2483. var PathCursor = (function () {
  2484. function PathCursor(path) {
  2485. this.path = path;
  2486. this._onchange = new Array();
  2487. this.value = 0;
  2488. this.animations = new Array();
  2489. }
  2490. PathCursor.prototype.getPoint = function () {
  2491. var point = this.path.getPointAtLengthPosition(this.value);
  2492. return new Vector3(point.x, 0, point.y);
  2493. };
  2494. PathCursor.prototype.moveAhead = function (step) {
  2495. if (step === void 0) { step = 0.002; }
  2496. this.move(step);
  2497. return this;
  2498. };
  2499. PathCursor.prototype.moveBack = function (step) {
  2500. if (step === void 0) { step = 0.002; }
  2501. this.move(-step);
  2502. return this;
  2503. };
  2504. PathCursor.prototype.move = function (step) {
  2505. if (Math.abs(step) > 1) {
  2506. throw "step size should be less than 1.";
  2507. }
  2508. this.value += step;
  2509. this.ensureLimits();
  2510. this.raiseOnChange();
  2511. return this;
  2512. };
  2513. PathCursor.prototype.ensureLimits = function () {
  2514. while (this.value > 1) {
  2515. this.value -= 1;
  2516. }
  2517. while (this.value < 0) {
  2518. this.value += 1;
  2519. }
  2520. return this;
  2521. };
  2522. // used by animation engine
  2523. PathCursor.prototype.markAsDirty = function (propertyName) {
  2524. this.ensureLimits();
  2525. this.raiseOnChange();
  2526. return this;
  2527. };
  2528. PathCursor.prototype.raiseOnChange = function () {
  2529. var _this = this;
  2530. this._onchange.forEach(function (f) { return f(_this); });
  2531. return this;
  2532. };
  2533. PathCursor.prototype.onchange = function (f) {
  2534. this._onchange.push(f);
  2535. return this;
  2536. };
  2537. return PathCursor;
  2538. })();
  2539. BABYLON.PathCursor = PathCursor;
  2540. var Path2 = (function () {
  2541. function Path2(x, y) {
  2542. this._points = new Array();
  2543. this._length = 0;
  2544. this.closed = false;
  2545. this._points.push(new Vector2(x, y));
  2546. }
  2547. Path2.prototype.addLineTo = function (x, y) {
  2548. if (closed) {
  2549. BABYLON.Tools.Error("cannot add lines to closed paths");
  2550. return this;
  2551. }
  2552. var newPoint = new Vector2(x, y);
  2553. var previousPoint = this._points[this._points.length - 1];
  2554. this._points.push(newPoint);
  2555. this._length += newPoint.subtract(previousPoint).length();
  2556. return this;
  2557. };
  2558. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2559. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2560. if (closed) {
  2561. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2562. return this;
  2563. }
  2564. var startPoint = this._points[this._points.length - 1];
  2565. var midPoint = new Vector2(midX, midY);
  2566. var endPoint = new Vector2(endX, endY);
  2567. var arc = new Arc2(startPoint, midPoint, endPoint);
  2568. var increment = arc.angle.radians() / numberOfSegments;
  2569. if (arc.orientation === 0 /* CW */)
  2570. increment *= -1;
  2571. var currentAngle = arc.startAngle.radians() + increment;
  2572. for (var i = 0; i < numberOfSegments; i++) {
  2573. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2574. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2575. this.addLineTo(x, y);
  2576. currentAngle += increment;
  2577. }
  2578. return this;
  2579. };
  2580. Path2.prototype.close = function () {
  2581. this.closed = true;
  2582. return this;
  2583. };
  2584. Path2.prototype.length = function () {
  2585. var result = this._length;
  2586. if (!this.closed) {
  2587. var lastPoint = this._points[this._points.length - 1];
  2588. var firstPoint = this._points[0];
  2589. result += (firstPoint.subtract(lastPoint).length());
  2590. }
  2591. return result;
  2592. };
  2593. Path2.prototype.getPoints = function () {
  2594. return this._points;
  2595. };
  2596. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2597. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2598. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2599. return Vector2.Zero();
  2600. }
  2601. var lengthPosition = normalizedLengthPosition * this.length();
  2602. var previousOffset = 0;
  2603. for (var i = 0; i < this._points.length; i++) {
  2604. var j = (i + 1) % this._points.length;
  2605. var a = this._points[i];
  2606. var b = this._points[j];
  2607. var bToA = b.subtract(a);
  2608. var nextOffset = (bToA.length() + previousOffset);
  2609. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2610. var dir = bToA.normalize();
  2611. var localOffset = lengthPosition - previousOffset;
  2612. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2613. }
  2614. previousOffset = nextOffset;
  2615. }
  2616. BABYLON.Tools.Error("internal error");
  2617. return Vector2.Zero();
  2618. };
  2619. Path2.StartingAt = function (x, y) {
  2620. return new Path2(x, y);
  2621. };
  2622. return Path2;
  2623. })();
  2624. BABYLON.Path2 = Path2;
  2625. var Path3D = (function () {
  2626. function Path3D(path) {
  2627. this.path = path;
  2628. this._curve = new Array();
  2629. this._distances = new Array();
  2630. this._tangents = new Array();
  2631. this._normals = new Array();
  2632. this._binormals = new Array();
  2633. this._curve = path.slice(); // copy array
  2634. this._compute();
  2635. }
  2636. Path3D.prototype.getCurve = function () {
  2637. return this._curve;
  2638. };
  2639. Path3D.prototype.getTangents = function () {
  2640. return this._tangents;
  2641. };
  2642. Path3D.prototype.getNormals = function () {
  2643. return this._normals;
  2644. };
  2645. Path3D.prototype.getBinormals = function () {
  2646. return this._binormals;
  2647. };
  2648. Path3D.prototype.getDistances = function () {
  2649. return this._distances;
  2650. };
  2651. Path3D.prototype.update = function (path) {
  2652. for (var i = 0; i < path.length; i++) {
  2653. this._curve[i] = path[i];
  2654. }
  2655. this._compute();
  2656. return this;
  2657. };
  2658. // private function compute() : computes tangents, normals and binormals
  2659. Path3D.prototype._compute = function () {
  2660. var l = this._curve.length;
  2661. // first and last tangents
  2662. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2663. this._tangents[0].normalize();
  2664. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2665. this._tangents[l - 1].normalize();
  2666. // normals and binormals at first point : arbitrary vector with _normalVector()
  2667. var tg0 = this._tangents[0];
  2668. var pp0 = this._normalVector(this._curve[0], tg0);
  2669. this._normals[0] = pp0;
  2670. this._normals[0].normalize();
  2671. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2672. this._normals[0].normalize();
  2673. this._distances[0] = 0;
  2674. // normals and binormals : next points
  2675. var prev; // previous vector (segment)
  2676. var cur; // current vector (segment)
  2677. var curTang; // current tangent
  2678. var prevNorm; // previous normal
  2679. var prevBinor; // previous binormal
  2680. for (var i = 1; i < l; i++) {
  2681. // tangents
  2682. prev = this._curve[i].subtract(this._curve[i - 1]);
  2683. if (i < l - 1) {
  2684. cur = this._curve[i + 1].subtract(this._curve[i]);
  2685. this._tangents[i] = prev.add(cur);
  2686. this._tangents[i].normalize();
  2687. }
  2688. this._distances[i] = this._distances[i - 1] + prev.length();
  2689. // normals and binormals
  2690. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2691. curTang = this._tangents[i];
  2692. prevNorm = this._normals[i - 1];
  2693. prevBinor = this._binormals[i - 1];
  2694. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2695. this._normals[i].normalize();
  2696. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2697. this._binormals[i].normalize();
  2698. }
  2699. };
  2700. // private function normalVector(v0, vt) :
  2701. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2702. Path3D.prototype._normalVector = function (v0, vt) {
  2703. var point;
  2704. if (vt.x !== 1) {
  2705. point = new Vector3(1, 0, 0);
  2706. }
  2707. else if (vt.y !== 1) {
  2708. point = new Vector3(0, 1, 0);
  2709. }
  2710. else if (vt.z !== 1) {
  2711. point = new Vector3(0, 0, 1);
  2712. }
  2713. var normal0 = Vector3.Cross(vt, point);
  2714. normal0.normalize();
  2715. return normal0;
  2716. };
  2717. return Path3D;
  2718. })();
  2719. BABYLON.Path3D = Path3D;
  2720. var Curve3 = (function () {
  2721. function Curve3(points) {
  2722. this._points = points;
  2723. }
  2724. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2725. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2726. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2727. var bez = new Array();
  2728. var step = 1 / nbPoints;
  2729. var equation = function (t, val0, val1, val2) {
  2730. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2731. return res;
  2732. };
  2733. for (var i = 0; i <= 1; i += step) {
  2734. 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)));
  2735. }
  2736. return new Curve3(bez);
  2737. };
  2738. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2739. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2740. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2741. var bez = new Array();
  2742. var step = 1 / nbPoints;
  2743. var equation = function (t, val0, val1, val2, val3) {
  2744. 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;
  2745. return res;
  2746. };
  2747. for (var i = 0; i <= 1; i += step) {
  2748. 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)));
  2749. }
  2750. return new Curve3(bez);
  2751. };
  2752. Curve3.prototype.getPoints = function () {
  2753. return this._points;
  2754. };
  2755. Curve3.prototype.continue = function (curve) {
  2756. var lastPoint = this._points[this._points.length - 1];
  2757. var continuedPoints = this._points.slice();
  2758. var curvePoints = curve.getPoints();
  2759. for (var i = 1; i < curvePoints.length; i++) {
  2760. continuedPoints.push(curvePoints[i].add(lastPoint));
  2761. }
  2762. return new Curve3(continuedPoints);
  2763. };
  2764. return Curve3;
  2765. })();
  2766. BABYLON.Curve3 = Curve3;
  2767. // Vertex formats
  2768. var PositionNormalVertex = (function () {
  2769. function PositionNormalVertex(position, normal) {
  2770. if (position === void 0) { position = Vector3.Zero(); }
  2771. if (normal === void 0) { normal = Vector3.Up(); }
  2772. this.position = position;
  2773. this.normal = normal;
  2774. }
  2775. PositionNormalVertex.prototype.clone = function () {
  2776. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2777. };
  2778. return PositionNormalVertex;
  2779. })();
  2780. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2781. var PositionNormalTextureVertex = (function () {
  2782. function PositionNormalTextureVertex(position, normal, uv) {
  2783. if (position === void 0) { position = Vector3.Zero(); }
  2784. if (normal === void 0) { normal = Vector3.Up(); }
  2785. if (uv === void 0) { uv = Vector2.Zero(); }
  2786. this.position = position;
  2787. this.normal = normal;
  2788. this.uv = uv;
  2789. }
  2790. PositionNormalTextureVertex.prototype.clone = function () {
  2791. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2792. };
  2793. return PositionNormalTextureVertex;
  2794. })();
  2795. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2796. // SIMD
  2797. if (window.SIMD !== undefined) {
  2798. // Replace functions
  2799. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2800. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2801. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2802. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2803. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2804. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2805. get: function () {
  2806. return this._data[0];
  2807. },
  2808. set: function (value) {
  2809. if (!this._data) {
  2810. this._data = new Float32Array(3);
  2811. }
  2812. this._data[0] = value;
  2813. }
  2814. });
  2815. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2816. get: function () {
  2817. return this._data[1];
  2818. },
  2819. set: function (value) {
  2820. this._data[1] = value;
  2821. }
  2822. });
  2823. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2824. get: function () {
  2825. return this._data[2];
  2826. },
  2827. set: function (value) {
  2828. this._data[2] = value;
  2829. }
  2830. });
  2831. }
  2832. })(BABYLON || (BABYLON = {}));
  2833. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2834. (function (BABYLON) {
  2835. // Screenshots
  2836. var screenshotCanvas;
  2837. var cloneValue = function (source, destinationObject) {
  2838. if (!source)
  2839. return null;
  2840. if (source instanceof BABYLON.Mesh) {
  2841. return null;
  2842. }
  2843. if (source instanceof BABYLON.SubMesh) {
  2844. return source.clone(destinationObject);
  2845. }
  2846. else if (source.clone) {
  2847. return source.clone();
  2848. }
  2849. return null;
  2850. };
  2851. var Tools = (function () {
  2852. function Tools() {
  2853. }
  2854. Tools.GetFilename = function (path) {
  2855. var index = path.lastIndexOf("/");
  2856. if (index < 0)
  2857. return path;
  2858. return path.substring(index + 1);
  2859. };
  2860. Tools.GetDOMTextContent = function (element) {
  2861. var result = "";
  2862. var child = element.firstChild;
  2863. while (child) {
  2864. if (child.nodeType === 3) {
  2865. result += child.textContent;
  2866. }
  2867. child = child.nextSibling;
  2868. }
  2869. return result;
  2870. };
  2871. Tools.ToDegrees = function (angle) {
  2872. return angle * 180 / Math.PI;
  2873. };
  2874. Tools.ToRadians = function (angle) {
  2875. return angle * Math.PI / 180;
  2876. };
  2877. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2878. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2879. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2880. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2881. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2882. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2883. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2884. }
  2885. return {
  2886. minimum: minimum,
  2887. maximum: maximum
  2888. };
  2889. };
  2890. Tools.ExtractMinAndMax = function (positions, start, count) {
  2891. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2892. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2893. for (var index = start; index < start + count; index++) {
  2894. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2895. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2896. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2897. }
  2898. return {
  2899. minimum: minimum,
  2900. maximum: maximum
  2901. };
  2902. };
  2903. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2904. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2905. return undefined;
  2906. return Array.isArray(obj) ? obj : [obj];
  2907. };
  2908. // Misc.
  2909. Tools.GetPointerPrefix = function () {
  2910. var eventPrefix = "pointer";
  2911. // Check if hand.js is referenced or if the browser natively supports pointer events
  2912. if (!navigator.pointerEnabled) {
  2913. eventPrefix = "mouse";
  2914. }
  2915. return eventPrefix;
  2916. };
  2917. Tools.QueueNewFrame = function (func) {
  2918. if (window.requestAnimationFrame)
  2919. window.requestAnimationFrame(func);
  2920. else if (window.msRequestAnimationFrame)
  2921. window.msRequestAnimationFrame(func);
  2922. else if (window.webkitRequestAnimationFrame)
  2923. window.webkitRequestAnimationFrame(func);
  2924. else if (window.mozRequestAnimationFrame)
  2925. window.mozRequestAnimationFrame(func);
  2926. else if (window.oRequestAnimationFrame)
  2927. window.oRequestAnimationFrame(func);
  2928. else {
  2929. window.setTimeout(func, 16);
  2930. }
  2931. };
  2932. Tools.RequestFullscreen = function (element) {
  2933. if (element.requestFullscreen)
  2934. element.requestFullscreen();
  2935. else if (element.msRequestFullscreen)
  2936. element.msRequestFullscreen();
  2937. else if (element.webkitRequestFullscreen)
  2938. element.webkitRequestFullscreen();
  2939. else if (element.mozRequestFullScreen)
  2940. element.mozRequestFullScreen();
  2941. };
  2942. Tools.ExitFullscreen = function () {
  2943. if (document.exitFullscreen) {
  2944. document.exitFullscreen();
  2945. }
  2946. else if (document.mozCancelFullScreen) {
  2947. document.mozCancelFullScreen();
  2948. }
  2949. else if (document.webkitCancelFullScreen) {
  2950. document.webkitCancelFullScreen();
  2951. }
  2952. else if (document.msCancelFullScreen) {
  2953. document.msCancelFullScreen();
  2954. }
  2955. };
  2956. // External files
  2957. Tools.CleanUrl = function (url) {
  2958. url = url.replace(/#/mg, "%23");
  2959. return url;
  2960. };
  2961. Tools.LoadImage = function (url, onload, onerror, database) {
  2962. url = Tools.CleanUrl(url);
  2963. var img = new Image();
  2964. if (url.substr(0, 5) !== "data:")
  2965. img.crossOrigin = 'anonymous';
  2966. img.onload = function () {
  2967. onload(img);
  2968. };
  2969. img.onerror = function (err) {
  2970. onerror(img, err);
  2971. };
  2972. var noIndexedDB = function () {
  2973. img.src = url;
  2974. };
  2975. var loadFromIndexedDB = function () {
  2976. database.loadImageFromDB(url, img);
  2977. };
  2978. //ANY database to do!
  2979. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2980. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2981. }
  2982. else {
  2983. if (url.indexOf("file:") === -1) {
  2984. noIndexedDB();
  2985. }
  2986. else {
  2987. try {
  2988. var textureName = url.substring(5);
  2989. var blobURL;
  2990. try {
  2991. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2992. }
  2993. catch (ex) {
  2994. // Chrome doesn't support oneTimeOnly parameter
  2995. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2996. }
  2997. img.src = blobURL;
  2998. }
  2999. catch (e) {
  3000. Tools.Log("Error while trying to load texture: " + textureName);
  3001. img.src = null;
  3002. }
  3003. }
  3004. }
  3005. return img;
  3006. };
  3007. //ANY
  3008. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  3009. url = Tools.CleanUrl(url);
  3010. var noIndexedDB = function () {
  3011. var request = new XMLHttpRequest();
  3012. var loadUrl = Tools.BaseUrl + url;
  3013. request.open('GET', loadUrl, true);
  3014. if (useArrayBuffer) {
  3015. request.responseType = "arraybuffer";
  3016. }
  3017. request.onprogress = progressCallBack;
  3018. request.onreadystatechange = function () {
  3019. if (request.readyState === 4) {
  3020. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  3021. callback(!useArrayBuffer ? request.responseText : request.response);
  3022. }
  3023. else {
  3024. if (onError) {
  3025. onError();
  3026. }
  3027. else {
  3028. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  3029. }
  3030. }
  3031. }
  3032. };
  3033. request.send(null);
  3034. };
  3035. var loadFromIndexedDB = function () {
  3036. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  3037. };
  3038. if (url.indexOf("file:") !== -1) {
  3039. var fileName = url.substring(5);
  3040. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  3041. }
  3042. else {
  3043. // Caching all files
  3044. if (database && database.enableSceneOffline) {
  3045. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3046. }
  3047. else {
  3048. noIndexedDB();
  3049. }
  3050. }
  3051. };
  3052. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3053. var reader = new FileReader();
  3054. reader.onload = function (e) {
  3055. //target doesn't have result from ts 1.3
  3056. callback(e.target['result']);
  3057. };
  3058. reader.onprogress = progressCallback;
  3059. reader.readAsDataURL(fileToLoad);
  3060. };
  3061. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3062. var reader = new FileReader();
  3063. reader.onerror = function (e) {
  3064. Tools.Log("Error while reading file: " + fileToLoad.name);
  3065. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3066. };
  3067. reader.onload = function (e) {
  3068. //target doesn't have result from ts 1.3
  3069. callback(e.target['result']);
  3070. };
  3071. reader.onprogress = progressCallBack;
  3072. if (!useArrayBuffer) {
  3073. // Asynchronous read
  3074. reader.readAsText(fileToLoad);
  3075. }
  3076. else {
  3077. reader.readAsArrayBuffer(fileToLoad);
  3078. }
  3079. };
  3080. // Misc.
  3081. Tools.Clamp = function (value, min, max) {
  3082. if (min === void 0) { min = 0; }
  3083. if (max === void 0) { max = 1; }
  3084. return Math.min(max, Math.max(min, value));
  3085. };
  3086. // Returns -1 when value is a negative number and
  3087. // +1 when value is a positive number.
  3088. Tools.Sign = function (value) {
  3089. value = +value; // convert to a number
  3090. if (value === 0 || isNaN(value))
  3091. return value;
  3092. return value > 0 ? 1 : -1;
  3093. };
  3094. Tools.Format = function (value, decimals) {
  3095. if (decimals === void 0) { decimals = 2; }
  3096. return value.toFixed(decimals);
  3097. };
  3098. Tools.CheckExtends = function (v, min, max) {
  3099. if (v.x < min.x)
  3100. min.x = v.x;
  3101. if (v.y < min.y)
  3102. min.y = v.y;
  3103. if (v.z < min.z)
  3104. min.z = v.z;
  3105. if (v.x > max.x)
  3106. max.x = v.x;
  3107. if (v.y > max.y)
  3108. max.y = v.y;
  3109. if (v.z > max.z)
  3110. max.z = v.z;
  3111. };
  3112. Tools.WithinEpsilon = function (a, b, epsilon) {
  3113. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3114. var num = a - b;
  3115. return -epsilon <= num && num <= epsilon;
  3116. };
  3117. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3118. for (var prop in source) {
  3119. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3120. continue;
  3121. }
  3122. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3123. continue;
  3124. }
  3125. var sourceValue = source[prop];
  3126. var typeOfSourceValue = typeof sourceValue;
  3127. if (typeOfSourceValue === "function") {
  3128. continue;
  3129. }
  3130. if (typeOfSourceValue === "object") {
  3131. if (sourceValue instanceof Array) {
  3132. destination[prop] = [];
  3133. if (sourceValue.length > 0) {
  3134. if (typeof sourceValue[0] == "object") {
  3135. for (var index = 0; index < sourceValue.length; index++) {
  3136. var clonedValue = cloneValue(sourceValue[index], destination);
  3137. if (destination[prop].indexOf(clonedValue) === -1) {
  3138. destination[prop].push(clonedValue);
  3139. }
  3140. }
  3141. }
  3142. else {
  3143. destination[prop] = sourceValue.slice(0);
  3144. }
  3145. }
  3146. }
  3147. else {
  3148. destination[prop] = cloneValue(sourceValue, destination);
  3149. }
  3150. }
  3151. else {
  3152. destination[prop] = sourceValue;
  3153. }
  3154. }
  3155. };
  3156. Tools.IsEmpty = function (obj) {
  3157. for (var i in obj) {
  3158. return false;
  3159. }
  3160. return true;
  3161. };
  3162. Tools.RegisterTopRootEvents = function (events) {
  3163. for (var index = 0; index < events.length; index++) {
  3164. var event = events[index];
  3165. window.addEventListener(event.name, event.handler, false);
  3166. try {
  3167. if (window.parent) {
  3168. window.parent.addEventListener(event.name, event.handler, false);
  3169. }
  3170. }
  3171. catch (e) {
  3172. }
  3173. }
  3174. };
  3175. Tools.UnregisterTopRootEvents = function (events) {
  3176. for (var index = 0; index < events.length; index++) {
  3177. var event = events[index];
  3178. window.removeEventListener(event.name, event.handler);
  3179. try {
  3180. if (window.parent) {
  3181. window.parent.removeEventListener(event.name, event.handler);
  3182. }
  3183. }
  3184. catch (e) {
  3185. }
  3186. }
  3187. };
  3188. Tools.DumpFramebuffer = function (width, height, engine) {
  3189. // Read the contents of the framebuffer
  3190. var numberOfChannelsByLine = width * 4;
  3191. var halfHeight = height / 2;
  3192. //Reading datas from WebGL
  3193. var data = engine.readPixels(0, 0, width, height);
  3194. for (var i = 0; i < halfHeight; i++) {
  3195. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3196. var currentCell = j + i * numberOfChannelsByLine;
  3197. var targetLine = height - i - 1;
  3198. var targetCell = j + targetLine * numberOfChannelsByLine;
  3199. var temp = data[currentCell];
  3200. data[currentCell] = data[targetCell];
  3201. data[targetCell] = temp;
  3202. }
  3203. }
  3204. // Create a 2D canvas to store the result
  3205. if (!screenshotCanvas) {
  3206. screenshotCanvas = document.createElement('canvas');
  3207. }
  3208. screenshotCanvas.width = width;
  3209. screenshotCanvas.height = height;
  3210. var context = screenshotCanvas.getContext('2d');
  3211. // Copy the pixels to a 2D canvas
  3212. var imageData = context.createImageData(width, height);
  3213. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3214. var castData = imageData.data;
  3215. castData.set(data);
  3216. context.putImageData(imageData, 0, 0);
  3217. var base64Image = screenshotCanvas.toDataURL();
  3218. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3219. if (("download" in document.createElement("a"))) {
  3220. var a = window.document.createElement("a");
  3221. a.href = base64Image;
  3222. var date = new Date();
  3223. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3224. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3225. window.document.body.appendChild(a);
  3226. a.addEventListener("click", function () {
  3227. a.parentElement.removeChild(a);
  3228. });
  3229. a.click();
  3230. }
  3231. else {
  3232. var newWindow = window.open("");
  3233. var img = newWindow.document.createElement("img");
  3234. img.src = base64Image;
  3235. newWindow.document.body.appendChild(img);
  3236. }
  3237. };
  3238. Tools.CreateScreenshot = function (engine, camera, size) {
  3239. var width;
  3240. var height;
  3241. var scene = camera.getScene();
  3242. var previousCamera = null;
  3243. if (scene.activeCamera !== camera) {
  3244. previousCamera = scene.activeCamera;
  3245. scene.activeCamera = camera;
  3246. }
  3247. //If a precision value is specified
  3248. if (size.precision) {
  3249. width = Math.round(engine.getRenderWidth() * size.precision);
  3250. height = Math.round(width / engine.getAspectRatio(camera));
  3251. size = { width: width, height: height };
  3252. }
  3253. else if (size.width && size.height) {
  3254. width = size.width;
  3255. height = size.height;
  3256. }
  3257. else if (size.width && !size.height) {
  3258. width = size.width;
  3259. height = Math.round(width / engine.getAspectRatio(camera));
  3260. size = { width: width, height: height };
  3261. }
  3262. else if (size.height && !size.width) {
  3263. height = size.height;
  3264. width = Math.round(height * engine.getAspectRatio(camera));
  3265. size = { width: width, height: height };
  3266. }
  3267. else if (!isNaN(size)) {
  3268. height = size;
  3269. width = size;
  3270. }
  3271. else {
  3272. Tools.Error("Invalid 'size' parameter !");
  3273. return;
  3274. }
  3275. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3276. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3277. texture.renderList = scene.meshes;
  3278. texture.onAfterRender = function () {
  3279. Tools.DumpFramebuffer(width, height, engine);
  3280. };
  3281. scene.incrementRenderId();
  3282. texture.render(true);
  3283. texture.dispose();
  3284. if (previousCamera) {
  3285. scene.activeCamera = previousCamera;
  3286. }
  3287. };
  3288. // XHR response validator for local file scenario
  3289. Tools.ValidateXHRData = function (xhr, dataType) {
  3290. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3291. if (dataType === void 0) { dataType = 7; }
  3292. try {
  3293. if (dataType & 1) {
  3294. if (xhr.responseText && xhr.responseText.length > 0) {
  3295. return true;
  3296. }
  3297. else if (dataType === 1) {
  3298. return false;
  3299. }
  3300. }
  3301. if (dataType & 2) {
  3302. // Check header width and height since there is no "TGA" magic number
  3303. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3304. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3305. return true;
  3306. }
  3307. else if (dataType === 2) {
  3308. return false;
  3309. }
  3310. }
  3311. if (dataType & 4) {
  3312. // Check for the "DDS" magic number
  3313. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3314. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3315. return true;
  3316. }
  3317. else {
  3318. return false;
  3319. }
  3320. }
  3321. }
  3322. catch (e) {
  3323. }
  3324. return false;
  3325. };
  3326. Object.defineProperty(Tools, "NoneLogLevel", {
  3327. get: function () {
  3328. return Tools._NoneLogLevel;
  3329. },
  3330. enumerable: true,
  3331. configurable: true
  3332. });
  3333. Object.defineProperty(Tools, "MessageLogLevel", {
  3334. get: function () {
  3335. return Tools._MessageLogLevel;
  3336. },
  3337. enumerable: true,
  3338. configurable: true
  3339. });
  3340. Object.defineProperty(Tools, "WarningLogLevel", {
  3341. get: function () {
  3342. return Tools._WarningLogLevel;
  3343. },
  3344. enumerable: true,
  3345. configurable: true
  3346. });
  3347. Object.defineProperty(Tools, "ErrorLogLevel", {
  3348. get: function () {
  3349. return Tools._ErrorLogLevel;
  3350. },
  3351. enumerable: true,
  3352. configurable: true
  3353. });
  3354. Object.defineProperty(Tools, "AllLogLevel", {
  3355. get: function () {
  3356. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3357. },
  3358. enumerable: true,
  3359. configurable: true
  3360. });
  3361. Tools._AddLogEntry = function (entry) {
  3362. Tools._LogCache = entry + Tools._LogCache;
  3363. if (Tools.OnNewCacheEntry) {
  3364. Tools.OnNewCacheEntry(entry);
  3365. }
  3366. };
  3367. Tools._FormatMessage = function (message) {
  3368. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3369. var date = new Date();
  3370. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3371. };
  3372. Tools._LogDisabled = function (message) {
  3373. // nothing to do
  3374. };
  3375. Tools._LogEnabled = function (message) {
  3376. var formattedMessage = Tools._FormatMessage(message);
  3377. console.log("BJS - " + formattedMessage);
  3378. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3379. Tools._AddLogEntry(entry);
  3380. };
  3381. Tools._WarnDisabled = function (message) {
  3382. // nothing to do
  3383. };
  3384. Tools._WarnEnabled = function (message) {
  3385. var formattedMessage = Tools._FormatMessage(message);
  3386. console.warn("BJS - " + formattedMessage);
  3387. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3388. Tools._AddLogEntry(entry);
  3389. };
  3390. Tools._ErrorDisabled = function (message) {
  3391. // nothing to do
  3392. };
  3393. Tools._ErrorEnabled = function (message) {
  3394. var formattedMessage = Tools._FormatMessage(message);
  3395. console.error("BJS - " + formattedMessage);
  3396. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3397. Tools._AddLogEntry(entry);
  3398. };
  3399. Object.defineProperty(Tools, "LogCache", {
  3400. get: function () {
  3401. return Tools._LogCache;
  3402. },
  3403. enumerable: true,
  3404. configurable: true
  3405. });
  3406. Object.defineProperty(Tools, "LogLevels", {
  3407. set: function (level) {
  3408. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3409. Tools.Log = Tools._LogEnabled;
  3410. }
  3411. else {
  3412. Tools.Log = Tools._LogDisabled;
  3413. }
  3414. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3415. Tools.Warn = Tools._WarnEnabled;
  3416. }
  3417. else {
  3418. Tools.Warn = Tools._WarnDisabled;
  3419. }
  3420. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3421. Tools.Error = Tools._ErrorEnabled;
  3422. }
  3423. else {
  3424. Tools.Error = Tools._ErrorDisabled;
  3425. }
  3426. },
  3427. enumerable: true,
  3428. configurable: true
  3429. });
  3430. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3431. get: function () {
  3432. return Tools._PerformanceNoneLogLevel;
  3433. },
  3434. enumerable: true,
  3435. configurable: true
  3436. });
  3437. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3438. get: function () {
  3439. return Tools._PerformanceUserMarkLogLevel;
  3440. },
  3441. enumerable: true,
  3442. configurable: true
  3443. });
  3444. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3445. get: function () {
  3446. return Tools._PerformanceConsoleLogLevel;
  3447. },
  3448. enumerable: true,
  3449. configurable: true
  3450. });
  3451. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3452. set: function (level) {
  3453. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3454. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3455. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3456. return;
  3457. }
  3458. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3459. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3460. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3461. return;
  3462. }
  3463. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3464. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3465. },
  3466. enumerable: true,
  3467. configurable: true
  3468. });
  3469. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3470. };
  3471. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3472. };
  3473. Tools._StartUserMark = function (counterName, condition) {
  3474. if (condition === void 0) { condition = true; }
  3475. if (!condition || !Tools._performance.mark) {
  3476. return;
  3477. }
  3478. Tools._performance.mark(counterName + "-Begin");
  3479. };
  3480. Tools._EndUserMark = function (counterName, condition) {
  3481. if (condition === void 0) { condition = true; }
  3482. if (!condition || !Tools._performance.mark) {
  3483. return;
  3484. }
  3485. Tools._performance.mark(counterName + "-End");
  3486. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3487. };
  3488. Tools._StartPerformanceConsole = function (counterName, condition) {
  3489. if (condition === void 0) { condition = true; }
  3490. if (!condition) {
  3491. return;
  3492. }
  3493. Tools._StartUserMark(counterName, condition);
  3494. if (console.time) {
  3495. console.time(counterName);
  3496. }
  3497. };
  3498. Tools._EndPerformanceConsole = function (counterName, condition) {
  3499. if (condition === void 0) { condition = true; }
  3500. if (!condition) {
  3501. return;
  3502. }
  3503. Tools._EndUserMark(counterName, condition);
  3504. if (console.time) {
  3505. console.timeEnd(counterName);
  3506. }
  3507. };
  3508. Object.defineProperty(Tools, "Now", {
  3509. get: function () {
  3510. if (window.performance && window.performance.now) {
  3511. return window.performance.now();
  3512. }
  3513. return new Date().getTime();
  3514. },
  3515. enumerable: true,
  3516. configurable: true
  3517. });
  3518. // Deprecated
  3519. Tools.GetFps = function () {
  3520. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3521. return 0;
  3522. };
  3523. Tools.BaseUrl = "";
  3524. Tools.GetExponantOfTwo = function (value, max) {
  3525. var count = 1;
  3526. do {
  3527. count *= 2;
  3528. } while (count < value);
  3529. if (count > max)
  3530. count = max;
  3531. return count;
  3532. };
  3533. // Logs
  3534. Tools._NoneLogLevel = 0;
  3535. Tools._MessageLogLevel = 1;
  3536. Tools._WarningLogLevel = 2;
  3537. Tools._ErrorLogLevel = 4;
  3538. Tools._LogCache = "";
  3539. Tools.Log = Tools._LogEnabled;
  3540. Tools.Warn = Tools._WarnEnabled;
  3541. Tools.Error = Tools._ErrorEnabled;
  3542. // Performances
  3543. Tools._PerformanceNoneLogLevel = 0;
  3544. Tools._PerformanceUserMarkLogLevel = 1;
  3545. Tools._PerformanceConsoleLogLevel = 2;
  3546. Tools._performance = window.performance;
  3547. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3548. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3549. return Tools;
  3550. })();
  3551. BABYLON.Tools = Tools;
  3552. /**
  3553. * An implementation of a loop for asynchronous functions.
  3554. */
  3555. var AsyncLoop = (function () {
  3556. /**
  3557. * Constroctor.
  3558. * @param iterations the number of iterations.
  3559. * @param _fn the function to run each iteration
  3560. * @param _successCallback the callback that will be called upon succesful execution
  3561. * @param offset starting offset.
  3562. */
  3563. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3564. if (offset === void 0) { offset = 0; }
  3565. this.iterations = iterations;
  3566. this._fn = _fn;
  3567. this._successCallback = _successCallback;
  3568. this.index = offset - 1;
  3569. this._done = false;
  3570. }
  3571. /**
  3572. * Execute the next iteration. Must be called after the last iteration was finished.
  3573. */
  3574. AsyncLoop.prototype.executeNext = function () {
  3575. if (!this._done) {
  3576. if (this.index + 1 < this.iterations) {
  3577. ++this.index;
  3578. this._fn(this);
  3579. }
  3580. else {
  3581. this.breakLoop();
  3582. }
  3583. }
  3584. };
  3585. /**
  3586. * Break the loop and run the success callback.
  3587. */
  3588. AsyncLoop.prototype.breakLoop = function () {
  3589. this._done = true;
  3590. this._successCallback();
  3591. };
  3592. /**
  3593. * Helper function
  3594. */
  3595. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3596. if (offset === void 0) { offset = 0; }
  3597. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3598. loop.executeNext();
  3599. return loop;
  3600. };
  3601. /**
  3602. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3603. * @param iterations total number of iterations
  3604. * @param syncedIterations number of synchronous iterations in each async iteration.
  3605. * @param fn the function to call each iteration.
  3606. * @param callback a success call back that will be called when iterating stops.
  3607. * @param breakFunction a break condition (optional)
  3608. * @param timeout timeout settings for the setTimeout function. default - 0.
  3609. * @constructor
  3610. */
  3611. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3612. if (timeout === void 0) { timeout = 0; }
  3613. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3614. if (breakFunction && breakFunction())
  3615. loop.breakLoop();
  3616. else {
  3617. setTimeout(function () {
  3618. for (var i = 0; i < syncedIterations; ++i) {
  3619. var iteration = (loop.index * syncedIterations) + i;
  3620. if (iteration >= iterations)
  3621. break;
  3622. fn(iteration);
  3623. if (breakFunction && breakFunction()) {
  3624. loop.breakLoop();
  3625. break;
  3626. }
  3627. }
  3628. loop.executeNext();
  3629. }, timeout);
  3630. }
  3631. }, callback);
  3632. };
  3633. return AsyncLoop;
  3634. })();
  3635. BABYLON.AsyncLoop = AsyncLoop;
  3636. })(BABYLON || (BABYLON = {}));
  3637. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3638. (function (BABYLON) {
  3639. var _DepthCullingState = (function () {
  3640. function _DepthCullingState() {
  3641. this._isDepthTestDirty = false;
  3642. this._isDepthMaskDirty = false;
  3643. this._isDepthFuncDirty = false;
  3644. this._isCullFaceDirty = false;
  3645. this._isCullDirty = false;
  3646. this._isZOffsetDirty = false;
  3647. }
  3648. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3649. get: function () {
  3650. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  3651. },
  3652. enumerable: true,
  3653. configurable: true
  3654. });
  3655. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  3656. get: function () {
  3657. return this._zOffset;
  3658. },
  3659. set: function (value) {
  3660. if (this._zOffset === value) {
  3661. return;
  3662. }
  3663. this._zOffset = value;
  3664. this._isZOffsetDirty = true;
  3665. },
  3666. enumerable: true,
  3667. configurable: true
  3668. });
  3669. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3670. get: function () {
  3671. return this._cullFace;
  3672. },
  3673. set: function (value) {
  3674. if (this._cullFace === value) {
  3675. return;
  3676. }
  3677. this._cullFace = value;
  3678. this._isCullFaceDirty = true;
  3679. },
  3680. enumerable: true,
  3681. configurable: true
  3682. });
  3683. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3684. get: function () {
  3685. return this._cull;
  3686. },
  3687. set: function (value) {
  3688. if (this._cull === value) {
  3689. return;
  3690. }
  3691. this._cull = value;
  3692. this._isCullDirty = true;
  3693. },
  3694. enumerable: true,
  3695. configurable: true
  3696. });
  3697. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3698. get: function () {
  3699. return this._depthFunc;
  3700. },
  3701. set: function (value) {
  3702. if (this._depthFunc === value) {
  3703. return;
  3704. }
  3705. this._depthFunc = value;
  3706. this._isDepthFuncDirty = true;
  3707. },
  3708. enumerable: true,
  3709. configurable: true
  3710. });
  3711. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3712. get: function () {
  3713. return this._depthMask;
  3714. },
  3715. set: function (value) {
  3716. if (this._depthMask === value) {
  3717. return;
  3718. }
  3719. this._depthMask = value;
  3720. this._isDepthMaskDirty = true;
  3721. },
  3722. enumerable: true,
  3723. configurable: true
  3724. });
  3725. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3726. get: function () {
  3727. return this._depthTest;
  3728. },
  3729. set: function (value) {
  3730. if (this._depthTest === value) {
  3731. return;
  3732. }
  3733. this._depthTest = value;
  3734. this._isDepthTestDirty = true;
  3735. },
  3736. enumerable: true,
  3737. configurable: true
  3738. });
  3739. _DepthCullingState.prototype.reset = function () {
  3740. this._depthMask = true;
  3741. this._depthTest = true;
  3742. this._depthFunc = null;
  3743. this._cull = null;
  3744. this._cullFace = null;
  3745. this._zOffset = 0;
  3746. this._isDepthTestDirty = true;
  3747. this._isDepthMaskDirty = true;
  3748. this._isDepthFuncDirty = false;
  3749. this._isCullFaceDirty = false;
  3750. this._isCullDirty = false;
  3751. this._isZOffsetDirty = false;
  3752. };
  3753. _DepthCullingState.prototype.apply = function (gl) {
  3754. if (!this.isDirty) {
  3755. return;
  3756. }
  3757. // Cull
  3758. if (this._isCullDirty) {
  3759. if (this.cull) {
  3760. gl.enable(gl.CULL_FACE);
  3761. }
  3762. else {
  3763. gl.disable(gl.CULL_FACE);
  3764. }
  3765. this._isCullDirty = false;
  3766. }
  3767. // Cull face
  3768. if (this._isCullFaceDirty) {
  3769. gl.cullFace(this.cullFace);
  3770. this._isCullFaceDirty = false;
  3771. }
  3772. // Depth mask
  3773. if (this._isDepthMaskDirty) {
  3774. gl.depthMask(this.depthMask);
  3775. this._isDepthMaskDirty = false;
  3776. }
  3777. // Depth test
  3778. if (this._isDepthTestDirty) {
  3779. if (this.depthTest) {
  3780. gl.enable(gl.DEPTH_TEST);
  3781. }
  3782. else {
  3783. gl.disable(gl.DEPTH_TEST);
  3784. }
  3785. this._isDepthTestDirty = false;
  3786. }
  3787. // Depth func
  3788. if (this._isDepthFuncDirty) {
  3789. gl.depthFunc(this.depthFunc);
  3790. this._isDepthFuncDirty = false;
  3791. }
  3792. // zOffset
  3793. if (this._isZOffsetDirty) {
  3794. if (this.zOffset) {
  3795. gl.enable(gl.POLYGON_OFFSET_FILL);
  3796. gl.polygonOffset(this.zOffset, 0);
  3797. }
  3798. else {
  3799. gl.disable(gl.POLYGON_OFFSET_FILL);
  3800. }
  3801. this._isZOffsetDirty = false;
  3802. }
  3803. };
  3804. return _DepthCullingState;
  3805. })();
  3806. BABYLON._DepthCullingState = _DepthCullingState;
  3807. var _AlphaState = (function () {
  3808. function _AlphaState() {
  3809. this._isAlphaBlendDirty = false;
  3810. this._isBlendFunctionParametersDirty = false;
  3811. this._alphaBlend = false;
  3812. this._blendFunctionParameters = new Array(4);
  3813. }
  3814. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3815. get: function () {
  3816. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3817. },
  3818. enumerable: true,
  3819. configurable: true
  3820. });
  3821. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3822. get: function () {
  3823. return this._alphaBlend;
  3824. },
  3825. set: function (value) {
  3826. if (this._alphaBlend === value) {
  3827. return;
  3828. }
  3829. this._alphaBlend = value;
  3830. this._isAlphaBlendDirty = true;
  3831. },
  3832. enumerable: true,
  3833. configurable: true
  3834. });
  3835. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3836. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3837. return;
  3838. }
  3839. this._blendFunctionParameters[0] = value0;
  3840. this._blendFunctionParameters[1] = value1;
  3841. this._blendFunctionParameters[2] = value2;
  3842. this._blendFunctionParameters[3] = value3;
  3843. this._isBlendFunctionParametersDirty = true;
  3844. };
  3845. _AlphaState.prototype.reset = function () {
  3846. this._alphaBlend = false;
  3847. this._blendFunctionParameters[0] = null;
  3848. this._blendFunctionParameters[1] = null;
  3849. this._blendFunctionParameters[2] = null;
  3850. this._blendFunctionParameters[3] = null;
  3851. this._isAlphaBlendDirty = true;
  3852. this._isBlendFunctionParametersDirty = false;
  3853. };
  3854. _AlphaState.prototype.apply = function (gl) {
  3855. if (!this.isDirty) {
  3856. return;
  3857. }
  3858. // Alpha blend
  3859. if (this._isAlphaBlendDirty) {
  3860. if (this._alphaBlend) {
  3861. gl.enable(gl.BLEND);
  3862. }
  3863. else {
  3864. gl.disable(gl.BLEND);
  3865. }
  3866. this._isAlphaBlendDirty = false;
  3867. }
  3868. // Alpha function
  3869. if (this._isBlendFunctionParametersDirty) {
  3870. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3871. this._isBlendFunctionParametersDirty = false;
  3872. }
  3873. };
  3874. return _AlphaState;
  3875. })();
  3876. BABYLON._AlphaState = _AlphaState;
  3877. var compileShader = function (gl, source, type, defines) {
  3878. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3879. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3880. gl.compileShader(shader);
  3881. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3882. throw new Error(gl.getShaderInfoLog(shader));
  3883. }
  3884. return shader;
  3885. };
  3886. var getWebGLTextureType = function (gl, type) {
  3887. var textureType = gl.UNSIGNED_BYTE;
  3888. if (type === Engine.TEXTURETYPE_FLOAT)
  3889. textureType = gl.FLOAT;
  3890. return textureType;
  3891. };
  3892. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3893. var magFilter = gl.NEAREST;
  3894. var minFilter = gl.NEAREST;
  3895. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3896. magFilter = gl.LINEAR;
  3897. if (generateMipMaps) {
  3898. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3899. }
  3900. else {
  3901. minFilter = gl.LINEAR;
  3902. }
  3903. }
  3904. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3905. magFilter = gl.LINEAR;
  3906. if (generateMipMaps) {
  3907. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3908. }
  3909. else {
  3910. minFilter = gl.LINEAR;
  3911. }
  3912. }
  3913. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3914. magFilter = gl.NEAREST;
  3915. if (generateMipMaps) {
  3916. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3917. }
  3918. else {
  3919. minFilter = gl.NEAREST;
  3920. }
  3921. }
  3922. return {
  3923. min: minFilter,
  3924. mag: magFilter
  3925. };
  3926. };
  3927. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3928. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3929. var engine = scene.getEngine();
  3930. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3931. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3932. gl.bindTexture(gl.TEXTURE_2D, texture);
  3933. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3934. processFunction(potWidth, potHeight);
  3935. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3938. if (!noMipmap && !isCompressed) {
  3939. gl.generateMipmap(gl.TEXTURE_2D);
  3940. }
  3941. gl.bindTexture(gl.TEXTURE_2D, null);
  3942. engine._activeTexturesCache = [];
  3943. texture._baseWidth = width;
  3944. texture._baseHeight = height;
  3945. texture._width = potWidth;
  3946. texture._height = potHeight;
  3947. texture.isReady = true;
  3948. texture.samplingMode = samplingMode;
  3949. scene._removePendingData(texture);
  3950. };
  3951. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3952. var onload = function () {
  3953. loadedImages[index] = img;
  3954. loadedImages._internalCount++;
  3955. scene._removePendingData(img);
  3956. if (loadedImages._internalCount === 6) {
  3957. onfinish(loadedImages);
  3958. }
  3959. };
  3960. var onerror = function () {
  3961. scene._removePendingData(img);
  3962. };
  3963. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3964. scene._addPendingData(img);
  3965. };
  3966. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3967. var loadedImages = [];
  3968. loadedImages._internalCount = 0;
  3969. for (var index = 0; index < 6; index++) {
  3970. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3971. }
  3972. };
  3973. var EngineCapabilities = (function () {
  3974. function EngineCapabilities() {
  3975. }
  3976. return EngineCapabilities;
  3977. })();
  3978. BABYLON.EngineCapabilities = EngineCapabilities;
  3979. /**
  3980. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3981. */
  3982. var Engine = (function () {
  3983. /**
  3984. * @constructor
  3985. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3986. * @param {boolean} [antialias] - enable antialias
  3987. * @param options - further options to be sent to the getContext function
  3988. */
  3989. function Engine(canvas, antialias, options) {
  3990. var _this = this;
  3991. // Public members
  3992. this.isFullscreen = false;
  3993. this.isPointerLock = false;
  3994. this.cullBackFaces = true;
  3995. this.renderEvenInBackground = true;
  3996. this.scenes = new Array();
  3997. this._windowIsBackground = false;
  3998. this._loadingDivBackgroundColor = "black";
  3999. this._drawCalls = 0;
  4000. this._renderingQueueLaunched = false;
  4001. this._activeRenderLoops = [];
  4002. // FPS
  4003. this.fpsRange = 60;
  4004. this.previousFramesDuration = [];
  4005. this.fps = 60;
  4006. this.deltaTime = 0;
  4007. // States
  4008. this._depthCullingState = new _DepthCullingState();
  4009. this._alphaState = new _AlphaState();
  4010. this._alphaMode = Engine.ALPHA_DISABLE;
  4011. // Cache
  4012. this._loadedTexturesCache = new Array();
  4013. this._activeTexturesCache = new Array();
  4014. this._compiledEffects = {};
  4015. this._uintIndicesCurrentlySet = false;
  4016. this._renderingCanvas = canvas;
  4017. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4018. options = options || {};
  4019. options.antialias = antialias;
  4020. try {
  4021. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  4022. }
  4023. catch (e) {
  4024. throw new Error("WebGL not supported");
  4025. }
  4026. if (!this._gl) {
  4027. throw new Error("WebGL not supported");
  4028. }
  4029. this._onBlur = function () {
  4030. _this._windowIsBackground = true;
  4031. };
  4032. this._onFocus = function () {
  4033. _this._windowIsBackground = false;
  4034. };
  4035. window.addEventListener("blur", this._onBlur);
  4036. window.addEventListener("focus", this._onFocus);
  4037. // Viewport
  4038. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  4039. this.resize();
  4040. // Caps
  4041. this._caps = new EngineCapabilities();
  4042. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  4043. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  4044. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  4045. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  4046. // Infos
  4047. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  4048. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  4049. if (rendererInfo != null) {
  4050. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  4051. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  4052. }
  4053. if (!this._glVendor) {
  4054. this._glVendor = "Unknown vendor";
  4055. }
  4056. if (!this._glRenderer) {
  4057. this._glRenderer = "Unknown renderer";
  4058. }
  4059. // Extensions
  4060. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  4061. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  4062. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  4063. 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');
  4064. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  4065. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  4066. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  4067. // Depth buffer
  4068. this.setDepthBuffer(true);
  4069. this.setDepthFunctionToLessOrEqual();
  4070. this.setDepthWrite(true);
  4071. // Fullscreen
  4072. this._onFullscreenChange = function () {
  4073. if (document.fullscreen !== undefined) {
  4074. _this.isFullscreen = document.fullscreen;
  4075. }
  4076. else if (document.mozFullScreen !== undefined) {
  4077. _this.isFullscreen = document.mozFullScreen;
  4078. }
  4079. else if (document.webkitIsFullScreen !== undefined) {
  4080. _this.isFullscreen = document.webkitIsFullScreen;
  4081. }
  4082. else if (document.msIsFullScreen !== undefined) {
  4083. _this.isFullscreen = document.msIsFullScreen;
  4084. }
  4085. // Pointer lock
  4086. if (_this.isFullscreen && _this._pointerLockRequested) {
  4087. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4088. if (canvas.requestPointerLock) {
  4089. canvas.requestPointerLock();
  4090. }
  4091. }
  4092. };
  4093. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4094. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4095. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4096. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4097. // Pointer lock
  4098. this._onPointerLockChange = function () {
  4099. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4100. };
  4101. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4102. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4103. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4104. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4105. if (!Engine.audioEngine) {
  4106. Engine.audioEngine = new BABYLON.AudioEngine();
  4107. }
  4108. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4109. }
  4110. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4111. get: function () {
  4112. return Engine._ALPHA_DISABLE;
  4113. },
  4114. enumerable: true,
  4115. configurable: true
  4116. });
  4117. Object.defineProperty(Engine, "ALPHA_ADD", {
  4118. get: function () {
  4119. return Engine._ALPHA_ADD;
  4120. },
  4121. enumerable: true,
  4122. configurable: true
  4123. });
  4124. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4125. get: function () {
  4126. return Engine._ALPHA_COMBINE;
  4127. },
  4128. enumerable: true,
  4129. configurable: true
  4130. });
  4131. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4132. get: function () {
  4133. return Engine._DELAYLOADSTATE_NONE;
  4134. },
  4135. enumerable: true,
  4136. configurable: true
  4137. });
  4138. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4139. get: function () {
  4140. return Engine._DELAYLOADSTATE_LOADED;
  4141. },
  4142. enumerable: true,
  4143. configurable: true
  4144. });
  4145. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4146. get: function () {
  4147. return Engine._DELAYLOADSTATE_LOADING;
  4148. },
  4149. enumerable: true,
  4150. configurable: true
  4151. });
  4152. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4153. get: function () {
  4154. return Engine._DELAYLOADSTATE_NOTLOADED;
  4155. },
  4156. enumerable: true,
  4157. configurable: true
  4158. });
  4159. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4160. get: function () {
  4161. return Engine._TEXTUREFORMAT_ALPHA;
  4162. },
  4163. enumerable: true,
  4164. configurable: true
  4165. });
  4166. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4167. get: function () {
  4168. return Engine._TEXTUREFORMAT_LUMINANCE;
  4169. },
  4170. enumerable: true,
  4171. configurable: true
  4172. });
  4173. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4174. get: function () {
  4175. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4176. },
  4177. enumerable: true,
  4178. configurable: true
  4179. });
  4180. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4181. get: function () {
  4182. return Engine._TEXTUREFORMAT_RGB;
  4183. },
  4184. enumerable: true,
  4185. configurable: true
  4186. });
  4187. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4188. get: function () {
  4189. return Engine._TEXTUREFORMAT_RGBA;
  4190. },
  4191. enumerable: true,
  4192. configurable: true
  4193. });
  4194. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4195. get: function () {
  4196. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4197. },
  4198. enumerable: true,
  4199. configurable: true
  4200. });
  4201. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4202. get: function () {
  4203. return Engine._TEXTURETYPE_FLOAT;
  4204. },
  4205. enumerable: true,
  4206. configurable: true
  4207. });
  4208. Object.defineProperty(Engine, "Version", {
  4209. get: function () {
  4210. return "2.1.0 alpha";
  4211. },
  4212. enumerable: true,
  4213. configurable: true
  4214. });
  4215. Engine.prototype._prepareWorkingCanvas = function () {
  4216. if (this._workingCanvas) {
  4217. return;
  4218. }
  4219. this._workingCanvas = document.createElement("canvas");
  4220. this._workingContext = this._workingCanvas.getContext("2d");
  4221. };
  4222. Engine.prototype.getGlInfo = function () {
  4223. return {
  4224. vendor: this._glVendor,
  4225. renderer: this._glRenderer,
  4226. version: this._glVersion
  4227. };
  4228. };
  4229. Engine.prototype.getAspectRatio = function (camera) {
  4230. var viewport = camera.viewport;
  4231. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4232. };
  4233. Engine.prototype.getRenderWidth = function () {
  4234. if (this._currentRenderTarget) {
  4235. return this._currentRenderTarget._width;
  4236. }
  4237. return this._renderingCanvas.width;
  4238. };
  4239. Engine.prototype.getRenderHeight = function () {
  4240. if (this._currentRenderTarget) {
  4241. return this._currentRenderTarget._height;
  4242. }
  4243. return this._renderingCanvas.height;
  4244. };
  4245. Engine.prototype.getRenderingCanvas = function () {
  4246. return this._renderingCanvas;
  4247. };
  4248. Engine.prototype.getRenderingCanvasClientRect = function () {
  4249. return this._renderingCanvas.getBoundingClientRect();
  4250. };
  4251. Engine.prototype.setHardwareScalingLevel = function (level) {
  4252. this._hardwareScalingLevel = level;
  4253. this.resize();
  4254. };
  4255. Engine.prototype.getHardwareScalingLevel = function () {
  4256. return this._hardwareScalingLevel;
  4257. };
  4258. Engine.prototype.getLoadedTexturesCache = function () {
  4259. return this._loadedTexturesCache;
  4260. };
  4261. Engine.prototype.getCaps = function () {
  4262. return this._caps;
  4263. };
  4264. Object.defineProperty(Engine.prototype, "drawCalls", {
  4265. get: function () {
  4266. return this._drawCalls;
  4267. },
  4268. enumerable: true,
  4269. configurable: true
  4270. });
  4271. // Methods
  4272. Engine.prototype.resetDrawCalls = function () {
  4273. this._drawCalls = 0;
  4274. };
  4275. Engine.prototype.setDepthFunctionToGreater = function () {
  4276. this._depthCullingState.depthFunc = this._gl.GREATER;
  4277. };
  4278. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4279. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4280. };
  4281. Engine.prototype.setDepthFunctionToLess = function () {
  4282. this._depthCullingState.depthFunc = this._gl.LESS;
  4283. };
  4284. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4285. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4286. };
  4287. /**
  4288. * stop executing a render loop function and remove it from the execution array
  4289. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4290. */
  4291. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4292. if (!renderFunction) {
  4293. this._activeRenderLoops = [];
  4294. return;
  4295. }
  4296. var index = this._activeRenderLoops.indexOf(renderFunction);
  4297. if (index >= 0) {
  4298. this._activeRenderLoops.splice(index, 1);
  4299. }
  4300. };
  4301. Engine.prototype._renderLoop = function () {
  4302. var _this = this;
  4303. var shouldRender = true;
  4304. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4305. shouldRender = false;
  4306. }
  4307. if (shouldRender) {
  4308. // Start new frame
  4309. this.beginFrame();
  4310. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4311. var renderFunction = this._activeRenderLoops[index];
  4312. renderFunction();
  4313. }
  4314. // Present
  4315. this.endFrame();
  4316. }
  4317. if (this._activeRenderLoops.length > 0) {
  4318. // Register new frame
  4319. BABYLON.Tools.QueueNewFrame(function () {
  4320. _this._renderLoop();
  4321. });
  4322. }
  4323. else {
  4324. this._renderingQueueLaunched = false;
  4325. }
  4326. };
  4327. /**
  4328. * Register and execute a render loop. The engine can have more than one render function.
  4329. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4330. * @example
  4331. * engine.runRenderLoop(function () {
  4332. * scene.render()
  4333. * })
  4334. */
  4335. Engine.prototype.runRenderLoop = function (renderFunction) {
  4336. var _this = this;
  4337. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4338. return;
  4339. }
  4340. this._activeRenderLoops.push(renderFunction);
  4341. if (!this._renderingQueueLaunched) {
  4342. this._renderingQueueLaunched = true;
  4343. BABYLON.Tools.QueueNewFrame(function () {
  4344. _this._renderLoop();
  4345. });
  4346. }
  4347. };
  4348. /**
  4349. * Toggle full screen mode.
  4350. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4351. */
  4352. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4353. if (this.isFullscreen) {
  4354. BABYLON.Tools.ExitFullscreen();
  4355. }
  4356. else {
  4357. this._pointerLockRequested = requestPointerLock;
  4358. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4359. }
  4360. };
  4361. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4362. this.applyStates();
  4363. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4364. if (this._depthCullingState.depthMask) {
  4365. this._gl.clearDepth(1.0);
  4366. }
  4367. var mode = 0;
  4368. if (backBuffer)
  4369. mode |= this._gl.COLOR_BUFFER_BIT;
  4370. if (depthStencil && this._depthCullingState.depthMask)
  4371. mode |= this._gl.DEPTH_BUFFER_BIT;
  4372. this._gl.clear(mode);
  4373. };
  4374. /**
  4375. * Set the WebGL's viewport
  4376. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4377. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4378. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4379. */
  4380. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4381. var width = requiredWidth || this._renderingCanvas.width;
  4382. var height = requiredHeight || this._renderingCanvas.height;
  4383. var x = viewport.x || 0;
  4384. var y = viewport.y || 0;
  4385. this._cachedViewport = viewport;
  4386. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4387. };
  4388. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4389. this._cachedViewport = null;
  4390. this._gl.viewport(x, y, width, height);
  4391. };
  4392. Engine.prototype.beginFrame = function () {
  4393. this._measureFps();
  4394. };
  4395. Engine.prototype.endFrame = function () {
  4396. //this.flushFramebuffer();
  4397. };
  4398. /**
  4399. * resize the view according to the canvas' size.
  4400. * @example
  4401. * window.addEventListener("resize", function () {
  4402. * engine.resize();
  4403. * });
  4404. */
  4405. Engine.prototype.resize = function () {
  4406. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4407. };
  4408. /**
  4409. * force a specific size of the canvas
  4410. * @param {number} width - the new canvas' width
  4411. * @param {number} height - the new canvas' height
  4412. */
  4413. Engine.prototype.setSize = function (width, height) {
  4414. this._renderingCanvas.width = width;
  4415. this._renderingCanvas.height = height;
  4416. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4417. };
  4418. Engine.prototype.bindFramebuffer = function (texture) {
  4419. this._currentRenderTarget = texture;
  4420. var gl = this._gl;
  4421. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4422. this._gl.viewport(0, 0, texture._width, texture._height);
  4423. this.wipeCaches();
  4424. };
  4425. Engine.prototype.unBindFramebuffer = function (texture) {
  4426. this._currentRenderTarget = null;
  4427. if (texture.generateMipMaps) {
  4428. var gl = this._gl;
  4429. gl.bindTexture(gl.TEXTURE_2D, texture);
  4430. gl.generateMipmap(gl.TEXTURE_2D);
  4431. gl.bindTexture(gl.TEXTURE_2D, null);
  4432. }
  4433. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4434. };
  4435. Engine.prototype.flushFramebuffer = function () {
  4436. this._gl.flush();
  4437. };
  4438. Engine.prototype.restoreDefaultFramebuffer = function () {
  4439. this._currentRenderTarget = null;
  4440. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4441. this.setViewport(this._cachedViewport);
  4442. this.wipeCaches();
  4443. };
  4444. // VBOs
  4445. Engine.prototype._resetVertexBufferBinding = function () {
  4446. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4447. this._cachedVertexBuffers = null;
  4448. };
  4449. Engine.prototype.createVertexBuffer = function (vertices) {
  4450. var vbo = this._gl.createBuffer();
  4451. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4452. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4453. this._resetVertexBufferBinding();
  4454. vbo.references = 1;
  4455. return vbo;
  4456. };
  4457. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4458. var vbo = this._gl.createBuffer();
  4459. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4460. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4461. this._resetVertexBufferBinding();
  4462. vbo.references = 1;
  4463. return vbo;
  4464. };
  4465. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4466. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4467. if (offset === undefined) {
  4468. offset = 0;
  4469. }
  4470. if (vertices instanceof Float32Array) {
  4471. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4472. }
  4473. else {
  4474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4475. }
  4476. this._resetVertexBufferBinding();
  4477. };
  4478. Engine.prototype._resetIndexBufferBinding = function () {
  4479. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4480. this._cachedIndexBuffer = null;
  4481. };
  4482. Engine.prototype.createIndexBuffer = function (indices) {
  4483. var vbo = this._gl.createBuffer();
  4484. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4485. // Check for 32 bits indices
  4486. var arrayBuffer;
  4487. var need32Bits = false;
  4488. if (this._caps.uintIndices) {
  4489. for (var index = 0; index < indices.length; index++) {
  4490. if (indices[index] > 65535) {
  4491. need32Bits = true;
  4492. break;
  4493. }
  4494. }
  4495. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4496. }
  4497. else {
  4498. arrayBuffer = new Uint16Array(indices);
  4499. }
  4500. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4501. this._resetIndexBufferBinding();
  4502. vbo.references = 1;
  4503. vbo.is32Bits = need32Bits;
  4504. return vbo;
  4505. };
  4506. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4507. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4508. this._cachedVertexBuffers = vertexBuffer;
  4509. this._cachedEffectForVertexBuffers = effect;
  4510. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4511. var offset = 0;
  4512. for (var index = 0; index < vertexDeclaration.length; index++) {
  4513. var order = effect.getAttributeLocation(index);
  4514. if (order >= 0) {
  4515. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4516. }
  4517. offset += vertexDeclaration[index] * 4;
  4518. }
  4519. }
  4520. if (this._cachedIndexBuffer !== indexBuffer) {
  4521. this._cachedIndexBuffer = indexBuffer;
  4522. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4523. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4524. }
  4525. };
  4526. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4527. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4528. this._cachedVertexBuffers = vertexBuffers;
  4529. this._cachedEffectForVertexBuffers = effect;
  4530. var attributes = effect.getAttributesNames();
  4531. for (var index = 0; index < attributes.length; index++) {
  4532. var order = effect.getAttributeLocation(index);
  4533. if (order >= 0) {
  4534. var vertexBuffer = vertexBuffers[attributes[index]];
  4535. if (!vertexBuffer) {
  4536. continue;
  4537. }
  4538. var stride = vertexBuffer.getStrideSize();
  4539. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4540. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4541. }
  4542. }
  4543. }
  4544. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4545. this._cachedIndexBuffer = indexBuffer;
  4546. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4547. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4548. }
  4549. };
  4550. Engine.prototype._releaseBuffer = function (buffer) {
  4551. buffer.references--;
  4552. if (buffer.references === 0) {
  4553. this._gl.deleteBuffer(buffer);
  4554. return true;
  4555. }
  4556. return false;
  4557. };
  4558. Engine.prototype.createInstancesBuffer = function (capacity) {
  4559. var buffer = this._gl.createBuffer();
  4560. buffer.capacity = capacity;
  4561. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4562. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4563. return buffer;
  4564. };
  4565. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4566. this._gl.deleteBuffer(buffer);
  4567. };
  4568. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4569. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4570. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4571. for (var index = 0; index < 4; index++) {
  4572. var offsetLocation = offsetLocations[index];
  4573. this._gl.enableVertexAttribArray(offsetLocation);
  4574. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4575. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4576. }
  4577. };
  4578. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4579. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4580. for (var index = 0; index < 4; index++) {
  4581. var offsetLocation = offsetLocations[index];
  4582. this._gl.disableVertexAttribArray(offsetLocation);
  4583. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4584. }
  4585. };
  4586. Engine.prototype.applyStates = function () {
  4587. this._depthCullingState.apply(this._gl);
  4588. this._alphaState.apply(this._gl);
  4589. };
  4590. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4591. // Apply states
  4592. this.applyStates();
  4593. this._drawCalls++;
  4594. // Render
  4595. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4596. if (instancesCount) {
  4597. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4598. return;
  4599. }
  4600. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4601. };
  4602. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4603. // Apply states
  4604. this.applyStates();
  4605. this._drawCalls++;
  4606. if (instancesCount) {
  4607. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4608. return;
  4609. }
  4610. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4611. };
  4612. // Shaders
  4613. Engine.prototype._releaseEffect = function (effect) {
  4614. if (this._compiledEffects[effect._key]) {
  4615. delete this._compiledEffects[effect._key];
  4616. if (effect.getProgram()) {
  4617. this._gl.deleteProgram(effect.getProgram());
  4618. }
  4619. }
  4620. };
  4621. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4622. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4623. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4624. var name = vertex + "+" + fragment + "@" + defines;
  4625. if (this._compiledEffects[name]) {
  4626. return this._compiledEffects[name];
  4627. }
  4628. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4629. effect._key = name;
  4630. this._compiledEffects[name] = effect;
  4631. return effect;
  4632. };
  4633. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4634. if (uniformsNames === void 0) { uniformsNames = []; }
  4635. if (samplers === void 0) { samplers = []; }
  4636. if (defines === void 0) { defines = ""; }
  4637. return this.createEffect({
  4638. vertex: "particles",
  4639. fragmentElement: fragmentName
  4640. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4641. };
  4642. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4643. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4644. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4645. var shaderProgram = this._gl.createProgram();
  4646. this._gl.attachShader(shaderProgram, vertexShader);
  4647. this._gl.attachShader(shaderProgram, fragmentShader);
  4648. this._gl.linkProgram(shaderProgram);
  4649. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4650. if (!linked) {
  4651. var error = this._gl.getProgramInfoLog(shaderProgram);
  4652. if (error) {
  4653. throw new Error(error);
  4654. }
  4655. }
  4656. this._gl.deleteShader(vertexShader);
  4657. this._gl.deleteShader(fragmentShader);
  4658. return shaderProgram;
  4659. };
  4660. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4661. var results = [];
  4662. for (var index = 0; index < uniformsNames.length; index++) {
  4663. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4664. }
  4665. return results;
  4666. };
  4667. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4668. var results = [];
  4669. for (var index = 0; index < attributesNames.length; index++) {
  4670. try {
  4671. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4672. }
  4673. catch (e) {
  4674. results.push(-1);
  4675. }
  4676. }
  4677. return results;
  4678. };
  4679. Engine.prototype.enableEffect = function (effect) {
  4680. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4681. if (effect && effect.onBind) {
  4682. effect.onBind(effect);
  4683. }
  4684. return;
  4685. }
  4686. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4687. // Use program
  4688. this._gl.useProgram(effect.getProgram());
  4689. for (var i in this._vertexAttribArrays) {
  4690. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4691. continue;
  4692. }
  4693. this._vertexAttribArrays[i] = false;
  4694. this._gl.disableVertexAttribArray(i);
  4695. }
  4696. var attributesCount = effect.getAttributesCount();
  4697. for (var index = 0; index < attributesCount; index++) {
  4698. // Attributes
  4699. var order = effect.getAttributeLocation(index);
  4700. if (order >= 0) {
  4701. this._vertexAttribArrays[order] = true;
  4702. this._gl.enableVertexAttribArray(order);
  4703. }
  4704. }
  4705. this._currentEffect = effect;
  4706. if (effect.onBind) {
  4707. effect.onBind(effect);
  4708. }
  4709. };
  4710. Engine.prototype.setArray = function (uniform, array) {
  4711. if (!uniform)
  4712. return;
  4713. this._gl.uniform1fv(uniform, array);
  4714. };
  4715. Engine.prototype.setArray2 = function (uniform, array) {
  4716. if (!uniform || array.length % 2 !== 0)
  4717. return;
  4718. this._gl.uniform2fv(uniform, array);
  4719. };
  4720. Engine.prototype.setArray3 = function (uniform, array) {
  4721. if (!uniform || array.length % 3 !== 0)
  4722. return;
  4723. this._gl.uniform3fv(uniform, array);
  4724. };
  4725. Engine.prototype.setArray4 = function (uniform, array) {
  4726. if (!uniform || array.length % 4 !== 0)
  4727. return;
  4728. this._gl.uniform4fv(uniform, array);
  4729. };
  4730. Engine.prototype.setMatrices = function (uniform, matrices) {
  4731. if (!uniform)
  4732. return;
  4733. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4734. };
  4735. Engine.prototype.setMatrix = function (uniform, matrix) {
  4736. if (!uniform)
  4737. return;
  4738. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4739. };
  4740. Engine.prototype.setFloat = function (uniform, value) {
  4741. if (!uniform)
  4742. return;
  4743. this._gl.uniform1f(uniform, value);
  4744. };
  4745. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4746. if (!uniform)
  4747. return;
  4748. this._gl.uniform2f(uniform, x, y);
  4749. };
  4750. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4751. if (!uniform)
  4752. return;
  4753. this._gl.uniform3f(uniform, x, y, z);
  4754. };
  4755. Engine.prototype.setBool = function (uniform, bool) {
  4756. if (!uniform)
  4757. return;
  4758. this._gl.uniform1i(uniform, bool);
  4759. };
  4760. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4761. if (!uniform)
  4762. return;
  4763. this._gl.uniform4f(uniform, x, y, z, w);
  4764. };
  4765. Engine.prototype.setColor3 = function (uniform, color3) {
  4766. if (!uniform)
  4767. return;
  4768. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4769. };
  4770. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4771. if (!uniform)
  4772. return;
  4773. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4774. };
  4775. // States
  4776. Engine.prototype.setState = function (culling, zOffset, force) {
  4777. if (zOffset === void 0) { zOffset = 0; }
  4778. // Culling
  4779. if (this._depthCullingState.cull !== culling || force) {
  4780. if (culling) {
  4781. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4782. this._depthCullingState.cull = true;
  4783. }
  4784. else {
  4785. this._depthCullingState.cull = false;
  4786. }
  4787. }
  4788. // Z offset
  4789. this._depthCullingState.zOffset = zOffset;
  4790. };
  4791. Engine.prototype.setDepthBuffer = function (enable) {
  4792. this._depthCullingState.depthTest = enable;
  4793. };
  4794. Engine.prototype.getDepthWrite = function () {
  4795. return this._depthCullingState.depthMask;
  4796. };
  4797. Engine.prototype.setDepthWrite = function (enable) {
  4798. this._depthCullingState.depthMask = enable;
  4799. };
  4800. Engine.prototype.setColorWrite = function (enable) {
  4801. this._gl.colorMask(enable, enable, enable, enable);
  4802. };
  4803. Engine.prototype.setAlphaMode = function (mode) {
  4804. switch (mode) {
  4805. case Engine.ALPHA_DISABLE:
  4806. this.setDepthWrite(true);
  4807. this._alphaState.alphaBlend = false;
  4808. break;
  4809. case Engine.ALPHA_COMBINE:
  4810. this.setDepthWrite(false);
  4811. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4812. this._alphaState.alphaBlend = true;
  4813. break;
  4814. case Engine.ALPHA_ADD:
  4815. this.setDepthWrite(false);
  4816. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4817. this._alphaState.alphaBlend = true;
  4818. break;
  4819. }
  4820. this._alphaMode = mode;
  4821. };
  4822. Engine.prototype.getAlphaMode = function () {
  4823. return this._alphaMode;
  4824. };
  4825. Engine.prototype.setAlphaTesting = function (enable) {
  4826. this._alphaTest = enable;
  4827. };
  4828. Engine.prototype.getAlphaTesting = function () {
  4829. return this._alphaTest;
  4830. };
  4831. // Textures
  4832. Engine.prototype.wipeCaches = function () {
  4833. this._activeTexturesCache = [];
  4834. this._currentEffect = null;
  4835. this._depthCullingState.reset();
  4836. this._alphaState.reset();
  4837. this._cachedVertexBuffers = null;
  4838. this._cachedIndexBuffer = null;
  4839. this._cachedEffectForVertexBuffers = null;
  4840. };
  4841. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4842. var gl = this._gl;
  4843. gl.bindTexture(gl.TEXTURE_2D, texture);
  4844. var magFilter = gl.NEAREST;
  4845. var minFilter = gl.NEAREST;
  4846. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4847. magFilter = gl.LINEAR;
  4848. minFilter = gl.LINEAR;
  4849. }
  4850. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4851. magFilter = gl.LINEAR;
  4852. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4853. }
  4854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4856. gl.bindTexture(gl.TEXTURE_2D, null);
  4857. texture.samplingMode = samplingMode;
  4858. };
  4859. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4860. var _this = this;
  4861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4862. if (onLoad === void 0) { onLoad = null; }
  4863. if (onError === void 0) { onError = null; }
  4864. if (buffer === void 0) { buffer = null; }
  4865. var texture = this._gl.createTexture();
  4866. var extension;
  4867. var fromData = false;
  4868. if (url.substr(0, 5) === "data:") {
  4869. fromData = true;
  4870. }
  4871. if (!fromData)
  4872. extension = url.substr(url.length - 4, 4).toLowerCase();
  4873. else {
  4874. var oldUrl = url;
  4875. fromData = oldUrl.split(':');
  4876. url = oldUrl;
  4877. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4878. }
  4879. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4880. var isTGA = (extension === ".tga");
  4881. scene._addPendingData(texture);
  4882. texture.url = url;
  4883. texture.noMipmap = noMipmap;
  4884. texture.references = 1;
  4885. this._loadedTexturesCache.push(texture);
  4886. var onerror = function () {
  4887. scene._removePendingData(texture);
  4888. if (onError) {
  4889. onError();
  4890. }
  4891. };
  4892. if (isTGA) {
  4893. var callback = function (arrayBuffer) {
  4894. var data = new Uint8Array(arrayBuffer);
  4895. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4896. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4897. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4898. if (onLoad) {
  4899. onLoad();
  4900. }
  4901. }, samplingMode);
  4902. };
  4903. if (!(fromData instanceof Array))
  4904. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4905. callback(arrayBuffer);
  4906. }, onerror, scene.database, true);
  4907. else
  4908. callback(buffer);
  4909. }
  4910. else if (isDDS) {
  4911. callback = function (data) {
  4912. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4913. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4914. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4915. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4916. if (onLoad) {
  4917. onLoad();
  4918. }
  4919. }, samplingMode);
  4920. };
  4921. if (!(fromData instanceof Array))
  4922. BABYLON.Tools.LoadFile(url, function (data) {
  4923. callback(data);
  4924. }, onerror, scene.database, true);
  4925. else
  4926. callback(buffer);
  4927. }
  4928. else {
  4929. var onload = function (img) {
  4930. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4931. var isPot = (img.width === potWidth && img.height === potHeight);
  4932. if (!isPot) {
  4933. _this._prepareWorkingCanvas();
  4934. _this._workingCanvas.width = potWidth;
  4935. _this._workingCanvas.height = potHeight;
  4936. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4937. _this._workingContext.imageSmoothingEnabled = false;
  4938. _this._workingContext.mozImageSmoothingEnabled = false;
  4939. _this._workingContext.oImageSmoothingEnabled = false;
  4940. _this._workingContext.webkitImageSmoothingEnabled = false;
  4941. _this._workingContext.msImageSmoothingEnabled = false;
  4942. }
  4943. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4944. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4945. _this._workingContext.imageSmoothingEnabled = true;
  4946. _this._workingContext.mozImageSmoothingEnabled = true;
  4947. _this._workingContext.oImageSmoothingEnabled = true;
  4948. _this._workingContext.webkitImageSmoothingEnabled = true;
  4949. _this._workingContext.msImageSmoothingEnabled = true;
  4950. }
  4951. }
  4952. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4953. if (onLoad) {
  4954. onLoad();
  4955. }
  4956. }, samplingMode);
  4957. };
  4958. if (!(fromData instanceof Array))
  4959. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4960. else
  4961. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4962. }
  4963. return texture;
  4964. };
  4965. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4966. var texture = this._gl.createTexture();
  4967. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4968. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4969. // Format
  4970. var internalFormat = this._gl.RGBA;
  4971. switch (format) {
  4972. case Engine.TEXTUREFORMAT_ALPHA:
  4973. internalFormat = this._gl.ALPHA;
  4974. break;
  4975. case Engine.TEXTUREFORMAT_LUMINANCE:
  4976. internalFormat = this._gl.LUMINANCE;
  4977. break;
  4978. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4979. internalFormat = this._gl.LUMINANCE_ALPHA;
  4980. break;
  4981. case Engine.TEXTUREFORMAT_RGB:
  4982. internalFormat = this._gl.RGB;
  4983. break;
  4984. case Engine.TEXTUREFORMAT_RGBA:
  4985. internalFormat = this._gl.RGBA;
  4986. break;
  4987. }
  4988. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4989. if (generateMipMaps) {
  4990. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4991. }
  4992. // Filters
  4993. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4994. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4995. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4996. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4997. this._activeTexturesCache = [];
  4998. texture._baseWidth = width;
  4999. texture._baseHeight = height;
  5000. texture._width = width;
  5001. texture._height = height;
  5002. texture.isReady = true;
  5003. texture.references = 1;
  5004. texture.samplingMode = samplingMode;
  5005. this._loadedTexturesCache.push(texture);
  5006. return texture;
  5007. };
  5008. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  5009. var texture = this._gl.createTexture();
  5010. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  5011. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  5012. this._activeTexturesCache = [];
  5013. texture._baseWidth = width;
  5014. texture._baseHeight = height;
  5015. texture._width = width;
  5016. texture._height = height;
  5017. texture.isReady = false;
  5018. texture.generateMipMaps = generateMipMaps;
  5019. texture.references = 1;
  5020. texture.samplingMode = samplingMode;
  5021. this.updateTextureSamplingMode(samplingMode, texture);
  5022. this._loadedTexturesCache.push(texture);
  5023. return texture;
  5024. };
  5025. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  5026. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  5027. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5029. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5030. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5031. };
  5032. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  5033. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5034. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  5035. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  5036. if (texture.generateMipMaps) {
  5037. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5038. }
  5039. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5040. this._activeTexturesCache = [];
  5041. texture.isReady = true;
  5042. };
  5043. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  5044. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5045. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  5046. // Scale the video if it is a NPOT using the current working canvas
  5047. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  5048. if (!texture._workingCanvas) {
  5049. texture._workingCanvas = document.createElement("canvas");
  5050. texture._workingContext = texture._workingCanvas.getContext("2d");
  5051. texture._workingCanvas.width = texture._width;
  5052. texture._workingCanvas.height = texture._height;
  5053. }
  5054. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  5055. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  5056. }
  5057. else {
  5058. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  5059. }
  5060. if (texture.generateMipMaps) {
  5061. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5062. }
  5063. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5064. this._activeTexturesCache = [];
  5065. texture.isReady = true;
  5066. };
  5067. Engine.prototype.createRenderTargetTexture = function (size, options) {
  5068. // old version had a "generateMipMaps" arg instead of options.
  5069. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  5070. // in the same way, generateDepthBuffer is defaulted to true
  5071. var generateMipMaps = false;
  5072. var generateDepthBuffer = true;
  5073. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5074. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  5075. if (options !== undefined) {
  5076. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  5077. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  5078. type = options.type === undefined ? type : options.type;
  5079. if (options.samplingMode !== undefined) {
  5080. samplingMode = options.samplingMode;
  5081. }
  5082. if (type === Engine.TEXTURETYPE_FLOAT) {
  5083. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5084. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5085. }
  5086. }
  5087. var gl = this._gl;
  5088. var texture = gl.createTexture();
  5089. gl.bindTexture(gl.TEXTURE_2D, texture);
  5090. var width = size.width || size;
  5091. var height = size.height || size;
  5092. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5093. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5094. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5095. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5096. }
  5097. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5100. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5101. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5102. var depthBuffer;
  5103. // Create the depth buffer
  5104. if (generateDepthBuffer) {
  5105. depthBuffer = gl.createRenderbuffer();
  5106. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5107. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5108. }
  5109. // Create the framebuffer
  5110. var framebuffer = gl.createFramebuffer();
  5111. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5113. if (generateDepthBuffer) {
  5114. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5115. }
  5116. // Unbind
  5117. gl.bindTexture(gl.TEXTURE_2D, null);
  5118. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5119. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5120. texture._framebuffer = framebuffer;
  5121. if (generateDepthBuffer) {
  5122. texture._depthBuffer = depthBuffer;
  5123. }
  5124. texture._width = width;
  5125. texture._height = height;
  5126. texture.isReady = true;
  5127. texture.generateMipMaps = generateMipMaps;
  5128. texture.references = 1;
  5129. texture.samplingMode = samplingMode;
  5130. this._activeTexturesCache = [];
  5131. this._loadedTexturesCache.push(texture);
  5132. return texture;
  5133. };
  5134. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5135. var _this = this;
  5136. var gl = this._gl;
  5137. var texture = gl.createTexture();
  5138. texture.isCube = true;
  5139. texture.url = rootUrl;
  5140. texture.references = 1;
  5141. this._loadedTexturesCache.push(texture);
  5142. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5143. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5144. if (isDDS) {
  5145. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5146. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5147. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5148. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5149. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5150. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5151. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5152. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5153. }
  5154. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5155. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5157. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5158. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5159. _this._activeTexturesCache = [];
  5160. texture._width = info.width;
  5161. texture._height = info.height;
  5162. texture.isReady = true;
  5163. }, null, null, true);
  5164. }
  5165. else {
  5166. cascadeLoad(rootUrl, scene, function (imgs) {
  5167. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5168. var height = width;
  5169. _this._prepareWorkingCanvas();
  5170. _this._workingCanvas.width = width;
  5171. _this._workingCanvas.height = height;
  5172. var faces = [
  5173. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5174. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5175. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5176. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5177. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5178. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5179. ];
  5180. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5181. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5182. for (var index = 0; index < faces.length; index++) {
  5183. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5184. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5185. }
  5186. if (!noMipmap) {
  5187. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5188. }
  5189. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5190. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5193. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5194. _this._activeTexturesCache = [];
  5195. texture._width = width;
  5196. texture._height = height;
  5197. texture.isReady = true;
  5198. }, extensions);
  5199. }
  5200. return texture;
  5201. };
  5202. Engine.prototype._releaseTexture = function (texture) {
  5203. var gl = this._gl;
  5204. if (texture._framebuffer) {
  5205. gl.deleteFramebuffer(texture._framebuffer);
  5206. }
  5207. if (texture._depthBuffer) {
  5208. gl.deleteRenderbuffer(texture._depthBuffer);
  5209. }
  5210. gl.deleteTexture(texture);
  5211. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5212. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5213. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5214. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5215. this._activeTexturesCache[channel] = null;
  5216. }
  5217. var index = this._loadedTexturesCache.indexOf(texture);
  5218. if (index !== -1) {
  5219. this._loadedTexturesCache.splice(index, 1);
  5220. }
  5221. };
  5222. Engine.prototype.bindSamplers = function (effect) {
  5223. this._gl.useProgram(effect.getProgram());
  5224. var samplers = effect.getSamplers();
  5225. for (var index = 0; index < samplers.length; index++) {
  5226. var uniform = effect.getUniform(samplers[index]);
  5227. this._gl.uniform1i(uniform, index);
  5228. }
  5229. this._currentEffect = null;
  5230. };
  5231. Engine.prototype._bindTexture = function (channel, texture) {
  5232. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5233. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5234. this._activeTexturesCache[channel] = null;
  5235. };
  5236. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5237. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5238. };
  5239. Engine.prototype.setTexture = function (channel, texture) {
  5240. if (channel < 0) {
  5241. return;
  5242. }
  5243. // Not ready?
  5244. if (!texture || !texture.isReady()) {
  5245. if (this._activeTexturesCache[channel] != null) {
  5246. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5247. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5248. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5249. this._activeTexturesCache[channel] = null;
  5250. }
  5251. return;
  5252. }
  5253. // Video
  5254. if (texture instanceof BABYLON.VideoTexture) {
  5255. if (texture.update()) {
  5256. this._activeTexturesCache[channel] = null;
  5257. }
  5258. }
  5259. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5260. texture.delayLoad();
  5261. return;
  5262. }
  5263. if (this._activeTexturesCache[channel] === texture) {
  5264. return;
  5265. }
  5266. this._activeTexturesCache[channel] = texture;
  5267. var internalTexture = texture.getInternalTexture();
  5268. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5269. if (internalTexture.isCube) {
  5270. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5271. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5272. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5273. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5274. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5275. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5276. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5277. }
  5278. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5279. }
  5280. else {
  5281. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5282. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5283. internalTexture._cachedWrapU = texture.wrapU;
  5284. switch (texture.wrapU) {
  5285. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5286. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5287. break;
  5288. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5289. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5290. break;
  5291. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5292. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5293. break;
  5294. }
  5295. }
  5296. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5297. internalTexture._cachedWrapV = texture.wrapV;
  5298. switch (texture.wrapV) {
  5299. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5300. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5301. break;
  5302. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5303. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5304. break;
  5305. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5306. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5307. break;
  5308. }
  5309. }
  5310. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5311. }
  5312. };
  5313. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5314. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5315. var value = texture.anisotropicFilteringLevel;
  5316. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5317. value = 1;
  5318. }
  5319. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5320. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5321. texture._cachedAnisotropicFilteringLevel = value;
  5322. }
  5323. };
  5324. Engine.prototype.readPixels = function (x, y, width, height) {
  5325. var data = new Uint8Array(height * width * 4);
  5326. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5327. return data;
  5328. };
  5329. // Dispose
  5330. Engine.prototype.dispose = function () {
  5331. this.hideLoadingUI();
  5332. this.stopRenderLoop();
  5333. while (this.scenes.length) {
  5334. this.scenes[0].dispose();
  5335. }
  5336. // Release audio engine
  5337. Engine.audioEngine.dispose();
  5338. for (var name in this._compiledEffects) {
  5339. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5340. }
  5341. for (var i in this._vertexAttribArrays) {
  5342. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5343. continue;
  5344. }
  5345. this._gl.disableVertexAttribArray(i);
  5346. }
  5347. // Events
  5348. window.removeEventListener("blur", this._onBlur);
  5349. window.removeEventListener("focus", this._onFocus);
  5350. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5351. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5352. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5353. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5354. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5355. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5356. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5357. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5358. };
  5359. // Loading screen
  5360. Engine.prototype.displayLoadingUI = function () {
  5361. var _this = this;
  5362. this._loadingDiv = document.createElement("div");
  5363. this._loadingDiv.style.opacity = "0";
  5364. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5365. // Loading text
  5366. this._loadingTextDiv = document.createElement("div");
  5367. this._loadingTextDiv.style.position = "absolute";
  5368. this._loadingTextDiv.style.left = "0";
  5369. this._loadingTextDiv.style.top = "50%";
  5370. this._loadingTextDiv.style.marginTop = "80px";
  5371. this._loadingTextDiv.style.width = "100%";
  5372. this._loadingTextDiv.style.height = "20px";
  5373. this._loadingTextDiv.style.fontFamily = "Arial";
  5374. this._loadingTextDiv.style.fontSize = "14px";
  5375. this._loadingTextDiv.style.color = "white";
  5376. this._loadingTextDiv.style.textAlign = "center";
  5377. this._loadingTextDiv.innerHTML = "Loading";
  5378. this._loadingDiv.appendChild(this._loadingTextDiv);
  5379. // Loading img
  5380. var imgBack = new Image();
  5381. 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==";
  5382. imgBack.style.position = "absolute";
  5383. imgBack.style.left = "50%";
  5384. imgBack.style.top = "50%";
  5385. imgBack.style.marginLeft = "-50px";
  5386. imgBack.style.marginTop = "-50px";
  5387. imgBack.style.transition = "transform 1.0s ease";
  5388. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5389. var deg = 360;
  5390. var onTransitionEnd = function () {
  5391. deg += 360;
  5392. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5393. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5394. };
  5395. imgBack.addEventListener("transitionend", onTransitionEnd);
  5396. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5397. this._loadingDiv.appendChild(imgBack);
  5398. // front image
  5399. var imgFront = new Image();
  5400. 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=";
  5401. imgFront.style.position = "absolute";
  5402. imgFront.style.left = "50%";
  5403. imgFront.style.top = "50%";
  5404. imgFront.style.marginLeft = "-50px";
  5405. imgFront.style.marginTop = "-50px";
  5406. this._loadingDiv.appendChild(imgFront);
  5407. // Resize
  5408. this._resizeLoadingUI = function () {
  5409. var canvasRect = _this.getRenderingCanvasClientRect();
  5410. _this._loadingDiv.style.position = "absolute";
  5411. _this._loadingDiv.style.left = canvasRect.left + "px";
  5412. _this._loadingDiv.style.top = canvasRect.top + "px";
  5413. _this._loadingDiv.style.width = canvasRect.width + "px";
  5414. _this._loadingDiv.style.height = canvasRect.height + "px";
  5415. };
  5416. this._resizeLoadingUI();
  5417. window.addEventListener("resize", this._resizeLoadingUI);
  5418. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5419. document.body.appendChild(this._loadingDiv);
  5420. setTimeout(function () {
  5421. _this._loadingDiv.style.opacity = "1";
  5422. imgBack.style.transform = "rotateZ(360deg)";
  5423. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5424. }, 0);
  5425. };
  5426. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5427. set: function (text) {
  5428. if (!this._loadingDiv) {
  5429. return;
  5430. }
  5431. this._loadingTextDiv.innerHTML = text;
  5432. },
  5433. enumerable: true,
  5434. configurable: true
  5435. });
  5436. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5437. get: function () {
  5438. return this._loadingDivBackgroundColor;
  5439. },
  5440. set: function (color) {
  5441. this._loadingDivBackgroundColor = color;
  5442. if (!this._loadingDiv) {
  5443. return;
  5444. }
  5445. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5446. },
  5447. enumerable: true,
  5448. configurable: true
  5449. });
  5450. Engine.prototype.hideLoadingUI = function () {
  5451. var _this = this;
  5452. if (!this._loadingDiv) {
  5453. return;
  5454. }
  5455. var onTransitionEnd = function () {
  5456. if (!_this._loadingDiv) {
  5457. return;
  5458. }
  5459. document.body.removeChild(_this._loadingDiv);
  5460. window.removeEventListener("resize", _this._resizeLoadingUI);
  5461. _this._loadingDiv = null;
  5462. };
  5463. this._loadingDiv.style.opacity = "0";
  5464. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5465. };
  5466. // FPS
  5467. Engine.prototype.getFps = function () {
  5468. return this.fps;
  5469. };
  5470. Engine.prototype.getDeltaTime = function () {
  5471. return this.deltaTime;
  5472. };
  5473. Engine.prototype._measureFps = function () {
  5474. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5475. var length = this.previousFramesDuration.length;
  5476. if (length >= 2) {
  5477. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5478. }
  5479. if (length >= this.fpsRange) {
  5480. if (length > this.fpsRange) {
  5481. this.previousFramesDuration.splice(0, 1);
  5482. length = this.previousFramesDuration.length;
  5483. }
  5484. var sum = 0;
  5485. for (var id = 0; id < length - 1; id++) {
  5486. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5487. }
  5488. this.fps = 1000.0 / (sum / (length - 1));
  5489. }
  5490. };
  5491. // Statics
  5492. Engine.isSupported = function () {
  5493. try {
  5494. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5495. if (navigator.isCocoonJS) {
  5496. return true;
  5497. }
  5498. var tempcanvas = document.createElement("canvas");
  5499. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5500. return gl != null && !!window.WebGLRenderingContext;
  5501. }
  5502. catch (e) {
  5503. return false;
  5504. }
  5505. };
  5506. // Const statics
  5507. Engine._ALPHA_DISABLE = 0;
  5508. Engine._ALPHA_ADD = 1;
  5509. Engine._ALPHA_COMBINE = 2;
  5510. Engine._DELAYLOADSTATE_NONE = 0;
  5511. Engine._DELAYLOADSTATE_LOADED = 1;
  5512. Engine._DELAYLOADSTATE_LOADING = 2;
  5513. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5514. Engine._TEXTUREFORMAT_ALPHA = 0;
  5515. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5516. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5517. Engine._TEXTUREFORMAT_RGB = 4;
  5518. Engine._TEXTUREFORMAT_RGBA = 4;
  5519. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5520. Engine._TEXTURETYPE_FLOAT = 1;
  5521. // Updatable statics so stick with vars here
  5522. Engine.Epsilon = 0.001;
  5523. Engine.CollisionsEpsilon = 0.001;
  5524. Engine.ShadersRepository = "Babylon/Shaders/";
  5525. return Engine;
  5526. })();
  5527. BABYLON.Engine = Engine;
  5528. })(BABYLON || (BABYLON = {}));
  5529. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5530. (function (BABYLON) {
  5531. /**
  5532. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5533. */
  5534. var Node = (function () {
  5535. /**
  5536. * @constructor
  5537. * @param {string} name - the name and id to be given to this node
  5538. * @param {BABYLON.Scene} the scene this node will be added to
  5539. */
  5540. function Node(name, scene) {
  5541. this.state = "";
  5542. this.animations = new Array();
  5543. this._childrenFlag = -1;
  5544. this._isEnabled = true;
  5545. this._isReady = true;
  5546. this._currentRenderId = -1;
  5547. this._parentRenderId = -1;
  5548. this.name = name;
  5549. this.id = name;
  5550. this._scene = scene;
  5551. this._initCache();
  5552. }
  5553. Node.prototype.getScene = function () {
  5554. return this._scene;
  5555. };
  5556. Node.prototype.getEngine = function () {
  5557. return this._scene.getEngine();
  5558. };
  5559. // override it in derived class
  5560. Node.prototype.getWorldMatrix = function () {
  5561. return BABYLON.Matrix.Identity();
  5562. };
  5563. // override it in derived class if you add new variables to the cache
  5564. // and call the parent class method
  5565. Node.prototype._initCache = function () {
  5566. this._cache = {};
  5567. this._cache.parent = undefined;
  5568. };
  5569. Node.prototype.updateCache = function (force) {
  5570. if (!force && this.isSynchronized())
  5571. return;
  5572. this._cache.parent = this.parent;
  5573. this._updateCache();
  5574. };
  5575. // override it in derived class if you add new variables to the cache
  5576. // and call the parent class method if !ignoreParentClass
  5577. Node.prototype._updateCache = function (ignoreParentClass) {
  5578. };
  5579. // override it in derived class if you add new variables to the cache
  5580. Node.prototype._isSynchronized = function () {
  5581. return true;
  5582. };
  5583. Node.prototype.isSynchronizedWithParent = function () {
  5584. if (!this.parent) {
  5585. return true;
  5586. }
  5587. if (this._parentRenderId !== this.parent._currentRenderId) {
  5588. return false;
  5589. }
  5590. this._parentRenderId = this.parent._currentRenderId;
  5591. return this.parent._currentRenderId <= this._currentRenderId && this.parent.isSynchronized();
  5592. };
  5593. Node.prototype.isSynchronized = function (updateCache) {
  5594. var check = this.hasNewParent();
  5595. check = check || !this.isSynchronizedWithParent();
  5596. check = check || !this._isSynchronized();
  5597. if (updateCache)
  5598. this.updateCache(true);
  5599. return !check;
  5600. };
  5601. Node.prototype.hasNewParent = function (update) {
  5602. if (this._cache.parent === this.parent)
  5603. return false;
  5604. if (update)
  5605. this._cache.parent = this.parent;
  5606. return true;
  5607. };
  5608. /**
  5609. * Is this node ready to be used/rendered
  5610. * @return {boolean} is it ready
  5611. */
  5612. Node.prototype.isReady = function () {
  5613. return this._isReady;
  5614. };
  5615. /**
  5616. * Is this node enabled.
  5617. * If the node has a parent and is enabled, the parent will be inspected as well.
  5618. * @return {boolean} whether this node (and its parent) is enabled.
  5619. * @see setEnabled
  5620. */
  5621. Node.prototype.isEnabled = function () {
  5622. if (!this._isEnabled) {
  5623. return false;
  5624. }
  5625. if (this.parent) {
  5626. return this.parent.isEnabled();
  5627. }
  5628. return true;
  5629. };
  5630. /**
  5631. * Set the enabled state of this node.
  5632. * @param {boolean} value - the new enabled state
  5633. * @see isEnabled
  5634. */
  5635. Node.prototype.setEnabled = function (value) {
  5636. this._isEnabled = value;
  5637. };
  5638. /**
  5639. * Is this node a descendant of the given node.
  5640. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5641. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5642. * @see parent
  5643. */
  5644. Node.prototype.isDescendantOf = function (ancestor) {
  5645. if (this.parent) {
  5646. if (this.parent === ancestor) {
  5647. return true;
  5648. }
  5649. return this.parent.isDescendantOf(ancestor);
  5650. }
  5651. return false;
  5652. };
  5653. Node.prototype._getDescendants = function (list, results) {
  5654. for (var index = 0; index < list.length; index++) {
  5655. var item = list[index];
  5656. if (item.isDescendantOf(this)) {
  5657. results.push(item);
  5658. }
  5659. }
  5660. };
  5661. /**
  5662. * Will return all nodes that have this node as parent.
  5663. * @return {BABYLON.Node[]} all children nodes of all types.
  5664. */
  5665. Node.prototype.getDescendants = function () {
  5666. var results = [];
  5667. this._getDescendants(this._scene.meshes, results);
  5668. this._getDescendants(this._scene.lights, results);
  5669. this._getDescendants(this._scene.cameras, results);
  5670. return results;
  5671. };
  5672. Node.prototype._setReady = function (state) {
  5673. if (state == this._isReady) {
  5674. return;
  5675. }
  5676. if (!state) {
  5677. this._isReady = false;
  5678. return;
  5679. }
  5680. this._isReady = true;
  5681. if (this.onReady) {
  5682. this.onReady(this);
  5683. }
  5684. };
  5685. return Node;
  5686. })();
  5687. BABYLON.Node = Node;
  5688. })(BABYLON || (BABYLON = {}));
  5689. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5690. (function (BABYLON) {
  5691. var BoundingSphere = (function () {
  5692. function BoundingSphere(minimum, maximum) {
  5693. this.minimum = minimum;
  5694. this.maximum = maximum;
  5695. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5696. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5697. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5698. this.radius = distance * 0.5;
  5699. this.centerWorld = BABYLON.Vector3.Zero();
  5700. this._update(BABYLON.Matrix.Identity());
  5701. }
  5702. // Methods
  5703. BoundingSphere.prototype._update = function (world) {
  5704. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5705. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5706. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5707. };
  5708. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5709. for (var i = 0; i < 6; i++) {
  5710. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5711. return false;
  5712. }
  5713. return true;
  5714. };
  5715. BoundingSphere.prototype.intersectsPoint = function (point) {
  5716. var x = this.centerWorld.x - point.x;
  5717. var y = this.centerWorld.y - point.y;
  5718. var z = this.centerWorld.z - point.z;
  5719. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5720. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5721. return false;
  5722. return true;
  5723. };
  5724. // Statics
  5725. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5726. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5727. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5728. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5729. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5730. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5731. return false;
  5732. return true;
  5733. };
  5734. return BoundingSphere;
  5735. })();
  5736. BABYLON.BoundingSphere = BoundingSphere;
  5737. })(BABYLON || (BABYLON = {}));
  5738. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5739. (function (BABYLON) {
  5740. var BoundingBox = (function () {
  5741. function BoundingBox(minimum, maximum) {
  5742. this.minimum = minimum;
  5743. this.maximum = maximum;
  5744. this.vectors = new Array();
  5745. this.vectorsWorld = new Array();
  5746. // Bounding vectors
  5747. this.vectors.push(this.minimum.clone());
  5748. this.vectors.push(this.maximum.clone());
  5749. this.vectors.push(this.minimum.clone());
  5750. this.vectors[2].x = this.maximum.x;
  5751. this.vectors.push(this.minimum.clone());
  5752. this.vectors[3].y = this.maximum.y;
  5753. this.vectors.push(this.minimum.clone());
  5754. this.vectors[4].z = this.maximum.z;
  5755. this.vectors.push(this.maximum.clone());
  5756. this.vectors[5].z = this.minimum.z;
  5757. this.vectors.push(this.maximum.clone());
  5758. this.vectors[6].x = this.minimum.x;
  5759. this.vectors.push(this.maximum.clone());
  5760. this.vectors[7].y = this.minimum.y;
  5761. // OBB
  5762. this.center = this.maximum.add(this.minimum).scale(0.5);
  5763. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5764. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5765. for (var index = 0; index < this.vectors.length; index++) {
  5766. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5767. }
  5768. this.minimumWorld = BABYLON.Vector3.Zero();
  5769. this.maximumWorld = BABYLON.Vector3.Zero();
  5770. this._update(BABYLON.Matrix.Identity());
  5771. }
  5772. // Methods
  5773. BoundingBox.prototype.getWorldMatrix = function () {
  5774. return this._worldMatrix;
  5775. };
  5776. BoundingBox.prototype._update = function (world) {
  5777. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5778. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5779. for (var index = 0; index < this.vectors.length; index++) {
  5780. var v = this.vectorsWorld[index];
  5781. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5782. if (v.x < this.minimumWorld.x)
  5783. this.minimumWorld.x = v.x;
  5784. if (v.y < this.minimumWorld.y)
  5785. this.minimumWorld.y = v.y;
  5786. if (v.z < this.minimumWorld.z)
  5787. this.minimumWorld.z = v.z;
  5788. if (v.x > this.maximumWorld.x)
  5789. this.maximumWorld.x = v.x;
  5790. if (v.y > this.maximumWorld.y)
  5791. this.maximumWorld.y = v.y;
  5792. if (v.z > this.maximumWorld.z)
  5793. this.maximumWorld.z = v.z;
  5794. }
  5795. // OBB
  5796. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5797. this.center.scaleInPlace(0.5);
  5798. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5799. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5800. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5801. this._worldMatrix = world;
  5802. };
  5803. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5804. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5805. };
  5806. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5807. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5808. };
  5809. BoundingBox.prototype.intersectsPoint = function (point) {
  5810. var delta = BABYLON.Engine.Epsilon;
  5811. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5812. return false;
  5813. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5814. return false;
  5815. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5816. return false;
  5817. return true;
  5818. };
  5819. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5820. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5821. };
  5822. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5823. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5824. return false;
  5825. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5826. return false;
  5827. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5828. return false;
  5829. return true;
  5830. };
  5831. // Statics
  5832. BoundingBox.Intersects = function (box0, box1) {
  5833. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5834. return false;
  5835. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5836. return false;
  5837. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5838. return false;
  5839. return true;
  5840. };
  5841. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5842. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5843. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5844. return (num <= (sphereRadius * sphereRadius));
  5845. };
  5846. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5847. for (var p = 0; p < 6; p++) {
  5848. for (var i = 0; i < 8; i++) {
  5849. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5850. return false;
  5851. }
  5852. }
  5853. }
  5854. return true;
  5855. };
  5856. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5857. for (var p = 0; p < 6; p++) {
  5858. var inCount = 8;
  5859. for (var i = 0; i < 8; i++) {
  5860. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5861. --inCount;
  5862. }
  5863. else {
  5864. break;
  5865. }
  5866. }
  5867. if (inCount === 0)
  5868. return false;
  5869. }
  5870. return true;
  5871. };
  5872. return BoundingBox;
  5873. })();
  5874. BABYLON.BoundingBox = BoundingBox;
  5875. })(BABYLON || (BABYLON = {}));
  5876. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5877. (function (BABYLON) {
  5878. var computeBoxExtents = function (axis, box) {
  5879. var p = BABYLON.Vector3.Dot(box.center, axis);
  5880. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5881. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5882. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5883. var r = r0 + r1 + r2;
  5884. return {
  5885. min: p - r,
  5886. max: p + r
  5887. };
  5888. };
  5889. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5890. var axisOverlap = function (axis, box0, box1) {
  5891. var result0 = computeBoxExtents(axis, box0);
  5892. var result1 = computeBoxExtents(axis, box1);
  5893. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5894. };
  5895. var BoundingInfo = (function () {
  5896. function BoundingInfo(minimum, maximum) {
  5897. this.minimum = minimum;
  5898. this.maximum = maximum;
  5899. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5900. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5901. }
  5902. // Methods
  5903. BoundingInfo.prototype._update = function (world) {
  5904. this.boundingBox._update(world);
  5905. this.boundingSphere._update(world);
  5906. };
  5907. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5908. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5909. return false;
  5910. return this.boundingBox.isInFrustum(frustumPlanes);
  5911. };
  5912. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5913. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5914. };
  5915. BoundingInfo.prototype._checkCollision = function (collider) {
  5916. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5917. };
  5918. BoundingInfo.prototype.intersectsPoint = function (point) {
  5919. if (!this.boundingSphere.centerWorld) {
  5920. return false;
  5921. }
  5922. if (!this.boundingSphere.intersectsPoint(point)) {
  5923. return false;
  5924. }
  5925. if (!this.boundingBox.intersectsPoint(point)) {
  5926. return false;
  5927. }
  5928. return true;
  5929. };
  5930. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5931. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5932. return false;
  5933. }
  5934. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5935. return false;
  5936. }
  5937. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5938. return false;
  5939. }
  5940. if (!precise) {
  5941. return true;
  5942. }
  5943. var box0 = this.boundingBox;
  5944. var box1 = boundingInfo.boundingBox;
  5945. if (!axisOverlap(box0.directions[0], box0, box1))
  5946. return false;
  5947. if (!axisOverlap(box0.directions[1], box0, box1))
  5948. return false;
  5949. if (!axisOverlap(box0.directions[2], box0, box1))
  5950. return false;
  5951. if (!axisOverlap(box1.directions[0], box0, box1))
  5952. return false;
  5953. if (!axisOverlap(box1.directions[1], box0, box1))
  5954. return false;
  5955. if (!axisOverlap(box1.directions[2], box0, box1))
  5956. return false;
  5957. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5958. return false;
  5959. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5960. return false;
  5961. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5962. return false;
  5963. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5964. return false;
  5965. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5966. return false;
  5967. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5968. return false;
  5969. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5970. return false;
  5971. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5972. return false;
  5973. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5974. return false;
  5975. return true;
  5976. };
  5977. return BoundingInfo;
  5978. })();
  5979. BABYLON.BoundingInfo = BoundingInfo;
  5980. })(BABYLON || (BABYLON = {}));
  5981. //# sourceMappingURL=babylon.boundingInfo.js.map
  5982. var BABYLON;
  5983. (function (BABYLON) {
  5984. var Light = (function (_super) {
  5985. __extends(Light, _super);
  5986. function Light(name, scene) {
  5987. _super.call(this, name, scene);
  5988. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5989. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5990. this.intensity = 1.0;
  5991. this.range = Number.MAX_VALUE;
  5992. this.includeOnlyWithLayerMask = 0;
  5993. this.includedOnlyMeshes = new Array();
  5994. this.excludedMeshes = new Array();
  5995. this._excludedMeshesIds = new Array();
  5996. this._includedOnlyMeshesIds = new Array();
  5997. scene.addLight(this);
  5998. }
  5999. Light.prototype.getShadowGenerator = function () {
  6000. return this._shadowGenerator;
  6001. };
  6002. Light.prototype.getAbsolutePosition = function () {
  6003. return BABYLON.Vector3.Zero();
  6004. };
  6005. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  6006. };
  6007. Light.prototype._getWorldMatrix = function () {
  6008. return BABYLON.Matrix.Identity();
  6009. };
  6010. Light.prototype.canAffectMesh = function (mesh) {
  6011. if (!mesh) {
  6012. return true;
  6013. }
  6014. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  6015. return false;
  6016. }
  6017. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  6018. return false;
  6019. }
  6020. if (this.includeOnlyWithLayerMask !== 0 && this.includeOnlyWithLayerMask !== mesh.layerMask) {
  6021. return false;
  6022. }
  6023. return true;
  6024. };
  6025. Light.prototype.getWorldMatrix = function () {
  6026. this._currentRenderId = this.getScene().getRenderId();
  6027. var worldMatrix = this._getWorldMatrix();
  6028. if (this.parent && this.parent.getWorldMatrix) {
  6029. if (!this._parentedWorldMatrix) {
  6030. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  6031. }
  6032. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  6033. return this._parentedWorldMatrix;
  6034. }
  6035. return worldMatrix;
  6036. };
  6037. Light.prototype.dispose = function () {
  6038. if (this._shadowGenerator) {
  6039. this._shadowGenerator.dispose();
  6040. this._shadowGenerator = null;
  6041. }
  6042. // Remove from scene
  6043. this.getScene().removeLight(this);
  6044. };
  6045. return Light;
  6046. })(BABYLON.Node);
  6047. BABYLON.Light = Light;
  6048. })(BABYLON || (BABYLON = {}));
  6049. //# sourceMappingURL=babylon.light.js.map
  6050. var BABYLON;
  6051. (function (BABYLON) {
  6052. var PointLight = (function (_super) {
  6053. __extends(PointLight, _super);
  6054. function PointLight(name, position, scene) {
  6055. _super.call(this, name, scene);
  6056. this.position = position;
  6057. }
  6058. PointLight.prototype.getAbsolutePosition = function () {
  6059. return this._transformedPosition ? this._transformedPosition : this.position;
  6060. };
  6061. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  6062. if (this.parent && this.parent.getWorldMatrix) {
  6063. if (!this._transformedPosition) {
  6064. this._transformedPosition = BABYLON.Vector3.Zero();
  6065. }
  6066. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6067. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  6068. return;
  6069. }
  6070. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  6071. };
  6072. PointLight.prototype.getShadowGenerator = function () {
  6073. return null;
  6074. };
  6075. PointLight.prototype._getWorldMatrix = function () {
  6076. if (!this._worldMatrix) {
  6077. this._worldMatrix = BABYLON.Matrix.Identity();
  6078. }
  6079. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6080. return this._worldMatrix;
  6081. };
  6082. return PointLight;
  6083. })(BABYLON.Light);
  6084. BABYLON.PointLight = PointLight;
  6085. })(BABYLON || (BABYLON = {}));
  6086. //# sourceMappingURL=babylon.pointLight.js.map
  6087. var BABYLON;
  6088. (function (BABYLON) {
  6089. var SpotLight = (function (_super) {
  6090. __extends(SpotLight, _super);
  6091. function SpotLight(name, position, direction, angle, exponent, scene) {
  6092. _super.call(this, name, scene);
  6093. this.position = position;
  6094. this.direction = direction;
  6095. this.angle = angle;
  6096. this.exponent = exponent;
  6097. }
  6098. SpotLight.prototype.getAbsolutePosition = function () {
  6099. return this.transformedPosition ? this.transformedPosition : this.position;
  6100. };
  6101. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6102. var activeCamera = this.getScene().activeCamera;
  6103. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6104. };
  6105. SpotLight.prototype.supportsVSM = function () {
  6106. return true;
  6107. };
  6108. SpotLight.prototype.needRefreshPerFrame = function () {
  6109. return false;
  6110. };
  6111. SpotLight.prototype.setDirectionToTarget = function (target) {
  6112. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6113. return this.direction;
  6114. };
  6115. SpotLight.prototype.computeTransformedPosition = function () {
  6116. if (this.parent && this.parent.getWorldMatrix) {
  6117. if (!this.transformedPosition) {
  6118. this.transformedPosition = BABYLON.Vector3.Zero();
  6119. }
  6120. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6121. return true;
  6122. }
  6123. return false;
  6124. };
  6125. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6126. var normalizeDirection;
  6127. if (this.parent && this.parent.getWorldMatrix) {
  6128. if (!this._transformedDirection) {
  6129. this._transformedDirection = BABYLON.Vector3.Zero();
  6130. }
  6131. this.computeTransformedPosition();
  6132. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6133. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6134. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6135. }
  6136. else {
  6137. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6138. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6139. }
  6140. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6141. };
  6142. SpotLight.prototype._getWorldMatrix = function () {
  6143. if (!this._worldMatrix) {
  6144. this._worldMatrix = BABYLON.Matrix.Identity();
  6145. }
  6146. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6147. return this._worldMatrix;
  6148. };
  6149. return SpotLight;
  6150. })(BABYLON.Light);
  6151. BABYLON.SpotLight = SpotLight;
  6152. })(BABYLON || (BABYLON = {}));
  6153. //# sourceMappingURL=babylon.spotLight.js.map
  6154. var BABYLON;
  6155. (function (BABYLON) {
  6156. var DirectionalLight = (function (_super) {
  6157. __extends(DirectionalLight, _super);
  6158. function DirectionalLight(name, direction, scene) {
  6159. _super.call(this, name, scene);
  6160. this.direction = direction;
  6161. this.shadowOrthoScale = 0.5;
  6162. this.position = direction.scale(-1);
  6163. }
  6164. DirectionalLight.prototype.getAbsolutePosition = function () {
  6165. return this.transformedPosition ? this.transformedPosition : this.position;
  6166. };
  6167. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6168. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6169. return this.direction;
  6170. };
  6171. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6172. var orthoLeft = Number.MAX_VALUE;
  6173. var orthoRight = Number.MIN_VALUE;
  6174. var orthoTop = Number.MIN_VALUE;
  6175. var orthoBottom = Number.MAX_VALUE;
  6176. var tempVector3 = BABYLON.Vector3.Zero();
  6177. var activeCamera = this.getScene().activeCamera;
  6178. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6179. var mesh = renderList[meshIndex];
  6180. if (!mesh) {
  6181. continue;
  6182. }
  6183. var boundingInfo = mesh.getBoundingInfo();
  6184. if (!boundingInfo) {
  6185. continue;
  6186. }
  6187. var boundingBox = boundingInfo.boundingBox;
  6188. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6189. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6190. if (tempVector3.x < orthoLeft)
  6191. orthoLeft = tempVector3.x;
  6192. if (tempVector3.y < orthoBottom)
  6193. orthoBottom = tempVector3.y;
  6194. if (tempVector3.x > orthoRight)
  6195. orthoRight = tempVector3.x;
  6196. if (tempVector3.y > orthoTop)
  6197. orthoTop = tempVector3.y;
  6198. }
  6199. }
  6200. var xOffset = orthoRight - orthoLeft;
  6201. var yOffset = orthoTop - orthoBottom;
  6202. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6203. };
  6204. DirectionalLight.prototype.supportsVSM = function () {
  6205. return true;
  6206. };
  6207. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6208. return true;
  6209. };
  6210. DirectionalLight.prototype.computeTransformedPosition = function () {
  6211. if (this.parent && this.parent.getWorldMatrix) {
  6212. if (!this.transformedPosition) {
  6213. this.transformedPosition = BABYLON.Vector3.Zero();
  6214. }
  6215. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6216. return true;
  6217. }
  6218. return false;
  6219. };
  6220. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6221. if (this.parent && this.parent.getWorldMatrix) {
  6222. if (!this._transformedDirection) {
  6223. this._transformedDirection = BABYLON.Vector3.Zero();
  6224. }
  6225. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6226. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6227. return;
  6228. }
  6229. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6230. };
  6231. DirectionalLight.prototype._getWorldMatrix = function () {
  6232. if (!this._worldMatrix) {
  6233. this._worldMatrix = BABYLON.Matrix.Identity();
  6234. }
  6235. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6236. return this._worldMatrix;
  6237. };
  6238. return DirectionalLight;
  6239. })(BABYLON.Light);
  6240. BABYLON.DirectionalLight = DirectionalLight;
  6241. })(BABYLON || (BABYLON = {}));
  6242. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6243. (function (BABYLON) {
  6244. var ShadowGenerator = (function () {
  6245. function ShadowGenerator(mapSize, light) {
  6246. var _this = this;
  6247. // Members
  6248. this._filter = ShadowGenerator.FILTER_NONE;
  6249. this.blurScale = 2;
  6250. this._blurBoxOffset = 0;
  6251. this._bias = 0.00005;
  6252. this._darkness = 0;
  6253. this._transparencyShadow = false;
  6254. this._viewMatrix = BABYLON.Matrix.Zero();
  6255. this._projectionMatrix = BABYLON.Matrix.Zero();
  6256. this._transformMatrix = BABYLON.Matrix.Zero();
  6257. this._worldViewProjection = BABYLON.Matrix.Zero();
  6258. this._light = light;
  6259. this._scene = light.getScene();
  6260. this._mapSize = mapSize;
  6261. light._shadowGenerator = this;
  6262. // Render target
  6263. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6264. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6265. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6266. this._shadowMap.anisotropicFilteringLevel = 1;
  6267. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6268. this._shadowMap.renderParticles = false;
  6269. this._shadowMap.onAfterUnbind = function () {
  6270. if (!_this.useBlurVarianceShadowMap) {
  6271. return;
  6272. }
  6273. if (!_this._shadowMap2) {
  6274. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6275. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6276. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6277. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6278. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6279. _this._downSamplePostprocess.onApply = function (effect) {
  6280. effect.setTexture("textureSampler", _this._shadowMap);
  6281. };
  6282. _this.blurBoxOffset = 1;
  6283. }
  6284. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6285. };
  6286. // Custom render function
  6287. var renderSubMesh = function (subMesh) {
  6288. var mesh = subMesh.getRenderingMesh();
  6289. var scene = _this._scene;
  6290. var engine = scene.getEngine();
  6291. // Culling
  6292. engine.setState(subMesh.getMaterial().backFaceCulling);
  6293. // Managing instances
  6294. var batch = mesh._getInstancesRenderList(subMesh._id);
  6295. if (batch.mustReturn) {
  6296. return;
  6297. }
  6298. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6299. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6300. engine.enableEffect(_this._effect);
  6301. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6302. var material = subMesh.getMaterial();
  6303. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6304. // Alpha test
  6305. if (material && material.needAlphaTesting()) {
  6306. var alphaTexture = material.getAlphaTestTexture();
  6307. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6308. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6309. }
  6310. // Bones
  6311. if (mesh.useBones) {
  6312. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6313. }
  6314. // Draw
  6315. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6316. }
  6317. else {
  6318. // Need to reset refresh rate of the shadowMap
  6319. _this._shadowMap.resetRefreshCounter();
  6320. }
  6321. };
  6322. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6323. var index;
  6324. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6325. renderSubMesh(opaqueSubMeshes.data[index]);
  6326. }
  6327. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6328. renderSubMesh(alphaTestSubMeshes.data[index]);
  6329. }
  6330. if (_this._transparencyShadow) {
  6331. for (index = 0; index < transparentSubMeshes.length; index++) {
  6332. renderSubMesh(transparentSubMeshes.data[index]);
  6333. }
  6334. }
  6335. };
  6336. this._shadowMap.onClear = function (engine) {
  6337. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6338. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6339. }
  6340. else {
  6341. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6342. }
  6343. };
  6344. }
  6345. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6346. // Static
  6347. get: function () {
  6348. return ShadowGenerator._FILTER_NONE;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6354. get: function () {
  6355. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6356. },
  6357. enumerable: true,
  6358. configurable: true
  6359. });
  6360. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6361. get: function () {
  6362. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6363. },
  6364. enumerable: true,
  6365. configurable: true
  6366. });
  6367. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6368. get: function () {
  6369. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6370. },
  6371. enumerable: true,
  6372. configurable: true
  6373. });
  6374. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6375. get: function () {
  6376. return this._bias;
  6377. },
  6378. set: function (bias) {
  6379. this._bias = bias;
  6380. },
  6381. enumerable: true,
  6382. configurable: true
  6383. });
  6384. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6385. get: function () {
  6386. return this._blurBoxOffset;
  6387. },
  6388. set: function (value) {
  6389. var _this = this;
  6390. if (this._blurBoxOffset === value) {
  6391. return;
  6392. }
  6393. this._blurBoxOffset = value;
  6394. if (this._boxBlurPostprocess) {
  6395. this._boxBlurPostprocess.dispose();
  6396. }
  6397. 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);
  6398. this._boxBlurPostprocess.onApply = function (effect) {
  6399. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6400. };
  6401. },
  6402. enumerable: true,
  6403. configurable: true
  6404. });
  6405. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6406. get: function () {
  6407. return this._filter;
  6408. },
  6409. set: function (value) {
  6410. if (this._filter === value) {
  6411. return;
  6412. }
  6413. this._filter = value;
  6414. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6415. this._shadowMap.anisotropicFilteringLevel = 16;
  6416. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6417. }
  6418. else {
  6419. this._shadowMap.anisotropicFilteringLevel = 1;
  6420. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6421. }
  6422. },
  6423. enumerable: true,
  6424. configurable: true
  6425. });
  6426. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6427. get: function () {
  6428. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6429. },
  6430. set: function (value) {
  6431. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6432. },
  6433. enumerable: true,
  6434. configurable: true
  6435. });
  6436. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6437. get: function () {
  6438. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6439. },
  6440. set: function (value) {
  6441. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6442. },
  6443. enumerable: true,
  6444. configurable: true
  6445. });
  6446. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6447. get: function () {
  6448. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6449. },
  6450. set: function (value) {
  6451. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6452. },
  6453. enumerable: true,
  6454. configurable: true
  6455. });
  6456. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6457. var defines = [];
  6458. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6459. defines.push("#define VSM");
  6460. }
  6461. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6462. var mesh = subMesh.getMesh();
  6463. var material = subMesh.getMaterial();
  6464. // Alpha test
  6465. if (material && material.needAlphaTesting()) {
  6466. defines.push("#define ALPHATEST");
  6467. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6468. attribs.push(BABYLON.VertexBuffer.UVKind);
  6469. defines.push("#define UV1");
  6470. }
  6471. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6472. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6473. defines.push("#define UV2");
  6474. }
  6475. }
  6476. // Bones
  6477. if (mesh.useBones) {
  6478. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6479. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6480. defines.push("#define BONES");
  6481. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6482. }
  6483. // Instances
  6484. if (useInstances) {
  6485. defines.push("#define INSTANCES");
  6486. attribs.push("world0");
  6487. attribs.push("world1");
  6488. attribs.push("world2");
  6489. attribs.push("world3");
  6490. }
  6491. // Get correct effect
  6492. var join = defines.join("\n");
  6493. if (this._cachedDefines !== join) {
  6494. this._cachedDefines = join;
  6495. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6496. }
  6497. return this._effect.isReady();
  6498. };
  6499. ShadowGenerator.prototype.getShadowMap = function () {
  6500. return this._shadowMap;
  6501. };
  6502. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6503. if (this._shadowMap2) {
  6504. return this._shadowMap2;
  6505. }
  6506. return this._shadowMap;
  6507. };
  6508. ShadowGenerator.prototype.getLight = function () {
  6509. return this._light;
  6510. };
  6511. // Methods
  6512. ShadowGenerator.prototype.getTransformMatrix = function () {
  6513. var scene = this._scene;
  6514. if (this._currentRenderID === scene.getRenderId()) {
  6515. return this._transformMatrix;
  6516. }
  6517. this._currentRenderID = scene.getRenderId();
  6518. var lightPosition = this._light.position;
  6519. var lightDirection = this._light.direction;
  6520. if (this._light.computeTransformedPosition()) {
  6521. lightPosition = this._light.transformedPosition;
  6522. }
  6523. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6524. this._cachedPosition = lightPosition.clone();
  6525. this._cachedDirection = lightDirection.clone();
  6526. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6527. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6528. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6529. }
  6530. return this._transformMatrix;
  6531. };
  6532. ShadowGenerator.prototype.getDarkness = function () {
  6533. return this._darkness;
  6534. };
  6535. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6536. if (darkness >= 1.0)
  6537. this._darkness = 1.0;
  6538. else if (darkness <= 0.0)
  6539. this._darkness = 0.0;
  6540. else
  6541. this._darkness = darkness;
  6542. };
  6543. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6544. this._transparencyShadow = hasShadow;
  6545. };
  6546. ShadowGenerator.prototype._packHalf = function (depth) {
  6547. var scale = depth * 255.0;
  6548. var fract = scale - Math.floor(scale);
  6549. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6550. };
  6551. ShadowGenerator.prototype.dispose = function () {
  6552. this._shadowMap.dispose();
  6553. if (this._shadowMap2) {
  6554. this._shadowMap2.dispose();
  6555. }
  6556. if (this._downSamplePostprocess) {
  6557. this._downSamplePostprocess.dispose();
  6558. }
  6559. if (this._boxBlurPostprocess) {
  6560. this._boxBlurPostprocess.dispose();
  6561. }
  6562. };
  6563. ShadowGenerator._FILTER_NONE = 0;
  6564. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6565. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6566. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6567. return ShadowGenerator;
  6568. })();
  6569. BABYLON.ShadowGenerator = ShadowGenerator;
  6570. })(BABYLON || (BABYLON = {}));
  6571. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6572. var BABYLON;
  6573. (function (BABYLON) {
  6574. var HemisphericLight = (function (_super) {
  6575. __extends(HemisphericLight, _super);
  6576. function HemisphericLight(name, direction, scene) {
  6577. _super.call(this, name, scene);
  6578. this.direction = direction;
  6579. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6580. }
  6581. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6582. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6583. return this.direction;
  6584. };
  6585. HemisphericLight.prototype.getShadowGenerator = function () {
  6586. return null;
  6587. };
  6588. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6589. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6590. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6591. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6592. };
  6593. HemisphericLight.prototype._getWorldMatrix = function () {
  6594. if (!this._worldMatrix) {
  6595. this._worldMatrix = BABYLON.Matrix.Identity();
  6596. }
  6597. return this._worldMatrix;
  6598. };
  6599. return HemisphericLight;
  6600. })(BABYLON.Light);
  6601. BABYLON.HemisphericLight = HemisphericLight;
  6602. })(BABYLON || (BABYLON = {}));
  6603. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6604. (function (BABYLON) {
  6605. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6606. if (boxMin.x > sphereCenter.x + sphereRadius)
  6607. return false;
  6608. if (sphereCenter.x - sphereRadius > boxMax.x)
  6609. return false;
  6610. if (boxMin.y > sphereCenter.y + sphereRadius)
  6611. return false;
  6612. if (sphereCenter.y - sphereRadius > boxMax.y)
  6613. return false;
  6614. if (boxMin.z > sphereCenter.z + sphereRadius)
  6615. return false;
  6616. if (sphereCenter.z - sphereRadius > boxMax.z)
  6617. return false;
  6618. return true;
  6619. };
  6620. var getLowestRoot = function (a, b, c, maxR) {
  6621. var determinant = b * b - 4.0 * a * c;
  6622. var result = { root: 0, found: false };
  6623. if (determinant < 0)
  6624. return result;
  6625. var sqrtD = Math.sqrt(determinant);
  6626. var r1 = (-b - sqrtD) / (2.0 * a);
  6627. var r2 = (-b + sqrtD) / (2.0 * a);
  6628. if (r1 > r2) {
  6629. var temp = r2;
  6630. r2 = r1;
  6631. r1 = temp;
  6632. }
  6633. if (r1 > 0 && r1 < maxR) {
  6634. result.root = r1;
  6635. result.found = true;
  6636. return result;
  6637. }
  6638. if (r2 > 0 && r2 < maxR) {
  6639. result.root = r2;
  6640. result.found = true;
  6641. return result;
  6642. }
  6643. return result;
  6644. };
  6645. var Collider = (function () {
  6646. function Collider() {
  6647. this.radius = new BABYLON.Vector3(1, 1, 1);
  6648. this.retry = 0;
  6649. this.basePointWorld = BABYLON.Vector3.Zero();
  6650. this.velocityWorld = BABYLON.Vector3.Zero();
  6651. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6652. this._collisionPoint = BABYLON.Vector3.Zero();
  6653. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6654. this._tempVector = BABYLON.Vector3.Zero();
  6655. this._tempVector2 = BABYLON.Vector3.Zero();
  6656. this._tempVector3 = BABYLON.Vector3.Zero();
  6657. this._tempVector4 = BABYLON.Vector3.Zero();
  6658. this._edge = BABYLON.Vector3.Zero();
  6659. this._baseToVertex = BABYLON.Vector3.Zero();
  6660. this._destinationPoint = BABYLON.Vector3.Zero();
  6661. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6662. this._displacementVector = BABYLON.Vector3.Zero();
  6663. }
  6664. // Methods
  6665. Collider.prototype._initialize = function (source, dir, e) {
  6666. this.velocity = dir;
  6667. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6668. this.basePoint = source;
  6669. source.multiplyToRef(this.radius, this.basePointWorld);
  6670. dir.multiplyToRef(this.radius, this.velocityWorld);
  6671. this.velocityWorldLength = this.velocityWorld.length();
  6672. this.epsilon = e;
  6673. this.collisionFound = false;
  6674. };
  6675. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6676. pa.subtractToRef(point, this._tempVector);
  6677. pb.subtractToRef(point, this._tempVector2);
  6678. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6679. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6680. if (d < 0)
  6681. return false;
  6682. pc.subtractToRef(point, this._tempVector3);
  6683. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6684. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6685. if (d < 0)
  6686. return false;
  6687. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6688. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6689. return d >= 0;
  6690. };
  6691. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6692. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6693. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6694. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6695. return false;
  6696. }
  6697. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6698. return false;
  6699. return true;
  6700. };
  6701. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6702. var t0;
  6703. var embeddedInPlane = false;
  6704. if (!subMesh._trianglePlanes) {
  6705. subMesh._trianglePlanes = [];
  6706. }
  6707. if (!subMesh._trianglePlanes[faceIndex]) {
  6708. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6709. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6710. }
  6711. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6712. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6713. return;
  6714. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6715. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6716. if (normalDotVelocity == 0) {
  6717. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6718. return;
  6719. embeddedInPlane = true;
  6720. t0 = 0;
  6721. }
  6722. else {
  6723. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6724. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6725. if (t0 > t1) {
  6726. var temp = t1;
  6727. t1 = t0;
  6728. t0 = temp;
  6729. }
  6730. if (t0 > 1.0 || t1 < 0.0)
  6731. return;
  6732. if (t0 < 0)
  6733. t0 = 0;
  6734. if (t0 > 1.0)
  6735. t0 = 1.0;
  6736. }
  6737. this._collisionPoint.copyFromFloats(0, 0, 0);
  6738. var found = false;
  6739. var t = 1.0;
  6740. if (!embeddedInPlane) {
  6741. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6742. this.velocity.scaleToRef(t0, this._tempVector);
  6743. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6744. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6745. found = true;
  6746. t = t0;
  6747. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6748. }
  6749. }
  6750. if (!found) {
  6751. var velocitySquaredLength = this.velocity.lengthSquared();
  6752. var a = velocitySquaredLength;
  6753. this.basePoint.subtractToRef(p1, this._tempVector);
  6754. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6755. var c = this._tempVector.lengthSquared() - 1.0;
  6756. var lowestRoot = getLowestRoot(a, b, c, t);
  6757. if (lowestRoot.found) {
  6758. t = lowestRoot.root;
  6759. found = true;
  6760. this._collisionPoint.copyFrom(p1);
  6761. }
  6762. this.basePoint.subtractToRef(p2, this._tempVector);
  6763. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6764. c = this._tempVector.lengthSquared() - 1.0;
  6765. lowestRoot = getLowestRoot(a, b, c, t);
  6766. if (lowestRoot.found) {
  6767. t = lowestRoot.root;
  6768. found = true;
  6769. this._collisionPoint.copyFrom(p2);
  6770. }
  6771. this.basePoint.subtractToRef(p3, this._tempVector);
  6772. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6773. c = this._tempVector.lengthSquared() - 1.0;
  6774. lowestRoot = getLowestRoot(a, b, c, t);
  6775. if (lowestRoot.found) {
  6776. t = lowestRoot.root;
  6777. found = true;
  6778. this._collisionPoint.copyFrom(p3);
  6779. }
  6780. p2.subtractToRef(p1, this._edge);
  6781. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6782. var edgeSquaredLength = this._edge.lengthSquared();
  6783. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6784. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6785. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6786. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6787. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6788. lowestRoot = getLowestRoot(a, b, c, t);
  6789. if (lowestRoot.found) {
  6790. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6791. if (f >= 0.0 && f <= 1.0) {
  6792. t = lowestRoot.root;
  6793. found = true;
  6794. this._edge.scaleInPlace(f);
  6795. p1.addToRef(this._edge, this._collisionPoint);
  6796. }
  6797. }
  6798. p3.subtractToRef(p2, this._edge);
  6799. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6800. edgeSquaredLength = this._edge.lengthSquared();
  6801. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6802. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6803. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6804. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6805. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6806. lowestRoot = getLowestRoot(a, b, c, t);
  6807. if (lowestRoot.found) {
  6808. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6809. if (f >= 0.0 && f <= 1.0) {
  6810. t = lowestRoot.root;
  6811. found = true;
  6812. this._edge.scaleInPlace(f);
  6813. p2.addToRef(this._edge, this._collisionPoint);
  6814. }
  6815. }
  6816. p1.subtractToRef(p3, this._edge);
  6817. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6818. edgeSquaredLength = this._edge.lengthSquared();
  6819. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6820. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6821. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6822. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6823. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6824. lowestRoot = getLowestRoot(a, b, c, t);
  6825. if (lowestRoot.found) {
  6826. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6827. if (f >= 0.0 && f <= 1.0) {
  6828. t = lowestRoot.root;
  6829. found = true;
  6830. this._edge.scaleInPlace(f);
  6831. p3.addToRef(this._edge, this._collisionPoint);
  6832. }
  6833. }
  6834. }
  6835. if (found) {
  6836. var distToCollision = t * this.velocity.length();
  6837. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6838. if (!this.intersectionPoint) {
  6839. this.intersectionPoint = this._collisionPoint.clone();
  6840. }
  6841. else {
  6842. this.intersectionPoint.copyFrom(this._collisionPoint);
  6843. }
  6844. this.nearestDistance = distToCollision;
  6845. this.collisionFound = true;
  6846. this.collidedMesh = subMesh.getMesh();
  6847. }
  6848. }
  6849. };
  6850. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6851. for (var i = indexStart; i < indexEnd; i += 3) {
  6852. var p1 = pts[indices[i] - decal];
  6853. var p2 = pts[indices[i + 1] - decal];
  6854. var p3 = pts[indices[i + 2] - decal];
  6855. this._testTriangle(i, subMesh, p3, p2, p1);
  6856. }
  6857. };
  6858. Collider.prototype._getResponse = function (pos, vel) {
  6859. pos.addToRef(vel, this._destinationPoint);
  6860. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6861. this.basePoint.addToRef(vel, pos);
  6862. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6863. this._slidePlaneNormal.normalize();
  6864. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6865. pos.addInPlace(this._displacementVector);
  6866. this.intersectionPoint.addInPlace(this._displacementVector);
  6867. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6868. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6869. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6870. };
  6871. return Collider;
  6872. })();
  6873. BABYLON.Collider = Collider;
  6874. })(BABYLON || (BABYLON = {}));
  6875. //# sourceMappingURL=babylon.collider.js.map
  6876. var BABYLON;
  6877. (function (BABYLON) {
  6878. var Camera = (function (_super) {
  6879. __extends(Camera, _super);
  6880. function Camera(name, position, scene) {
  6881. _super.call(this, name, scene);
  6882. this.position = position;
  6883. // Members
  6884. this.upVector = BABYLON.Vector3.Up();
  6885. this.orthoLeft = null;
  6886. this.orthoRight = null;
  6887. this.orthoBottom = null;
  6888. this.orthoTop = null;
  6889. this.fov = 0.8;
  6890. this.minZ = 1.0;
  6891. this.maxZ = 10000.0;
  6892. this.inertia = 0.9;
  6893. this.mode = Camera.PERSPECTIVE_CAMERA;
  6894. this.isIntermediate = false;
  6895. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6896. this.subCameras = [];
  6897. this.layerMask = 0xFFFFFFFF;
  6898. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6899. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6900. this._projectionMatrix = new BABYLON.Matrix();
  6901. this._postProcesses = new Array();
  6902. this._postProcessesTakenIndices = [];
  6903. this._activeMeshes = new BABYLON.SmartArray(256);
  6904. this._globalPosition = BABYLON.Vector3.Zero();
  6905. scene.addCamera(this);
  6906. if (!scene.activeCamera) {
  6907. scene.activeCamera = this;
  6908. }
  6909. }
  6910. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6911. get: function () {
  6912. return Camera._PERSPECTIVE_CAMERA;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6918. get: function () {
  6919. return Camera._ORTHOGRAPHIC_CAMERA;
  6920. },
  6921. enumerable: true,
  6922. configurable: true
  6923. });
  6924. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6925. get: function () {
  6926. return Camera._FOVMODE_VERTICAL_FIXED;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6932. get: function () {
  6933. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6934. },
  6935. enumerable: true,
  6936. configurable: true
  6937. });
  6938. Object.defineProperty(Camera.prototype, "globalPosition", {
  6939. get: function () {
  6940. return this._globalPosition;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Camera.prototype.getActiveMeshes = function () {
  6946. return this._activeMeshes;
  6947. };
  6948. Camera.prototype.isActiveMesh = function (mesh) {
  6949. return (this._activeMeshes.indexOf(mesh) !== -1);
  6950. };
  6951. //Cache
  6952. Camera.prototype._initCache = function () {
  6953. _super.prototype._initCache.call(this);
  6954. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6955. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6956. this._cache.mode = undefined;
  6957. this._cache.minZ = undefined;
  6958. this._cache.maxZ = undefined;
  6959. this._cache.fov = undefined;
  6960. this._cache.aspectRatio = undefined;
  6961. this._cache.orthoLeft = undefined;
  6962. this._cache.orthoRight = undefined;
  6963. this._cache.orthoBottom = undefined;
  6964. this._cache.orthoTop = undefined;
  6965. this._cache.renderWidth = undefined;
  6966. this._cache.renderHeight = undefined;
  6967. };
  6968. Camera.prototype._updateCache = function (ignoreParentClass) {
  6969. if (!ignoreParentClass) {
  6970. _super.prototype._updateCache.call(this);
  6971. }
  6972. var engine = this.getEngine();
  6973. this._cache.position.copyFrom(this.position);
  6974. this._cache.upVector.copyFrom(this.upVector);
  6975. this._cache.mode = this.mode;
  6976. this._cache.minZ = this.minZ;
  6977. this._cache.maxZ = this.maxZ;
  6978. this._cache.fov = this.fov;
  6979. this._cache.aspectRatio = engine.getAspectRatio(this);
  6980. this._cache.orthoLeft = this.orthoLeft;
  6981. this._cache.orthoRight = this.orthoRight;
  6982. this._cache.orthoBottom = this.orthoBottom;
  6983. this._cache.orthoTop = this.orthoTop;
  6984. this._cache.renderWidth = engine.getRenderWidth();
  6985. this._cache.renderHeight = engine.getRenderHeight();
  6986. };
  6987. Camera.prototype._updateFromScene = function () {
  6988. this.updateCache();
  6989. this._update();
  6990. };
  6991. // Synchronized
  6992. Camera.prototype._isSynchronized = function () {
  6993. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6994. };
  6995. Camera.prototype._isSynchronizedViewMatrix = function () {
  6996. if (!_super.prototype._isSynchronized.call(this))
  6997. return false;
  6998. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6999. };
  7000. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  7001. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  7002. if (!check) {
  7003. return false;
  7004. }
  7005. var engine = this.getEngine();
  7006. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7007. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  7008. }
  7009. else {
  7010. 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();
  7011. }
  7012. return check;
  7013. };
  7014. // Controls
  7015. Camera.prototype.attachControl = function (element) {
  7016. };
  7017. Camera.prototype.detachControl = function (element) {
  7018. };
  7019. Camera.prototype._update = function () {
  7020. };
  7021. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  7022. if (insertAt === void 0) { insertAt = null; }
  7023. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  7024. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  7025. return 0;
  7026. }
  7027. if (insertAt == null || insertAt < 0) {
  7028. this._postProcesses.push(postProcess);
  7029. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  7030. return this._postProcesses.length - 1;
  7031. }
  7032. var add = 0;
  7033. if (this._postProcesses[insertAt]) {
  7034. var start = this._postProcesses.length - 1;
  7035. for (var i = start; i >= insertAt + 1; --i) {
  7036. this._postProcesses[i + 1] = this._postProcesses[i];
  7037. }
  7038. add = 1;
  7039. }
  7040. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7041. if (this._postProcessesTakenIndices[i] < insertAt) {
  7042. continue;
  7043. }
  7044. start = this._postProcessesTakenIndices.length - 1;
  7045. for (var j = start; j >= i; --j) {
  7046. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  7047. }
  7048. this._postProcessesTakenIndices[i] = insertAt;
  7049. break;
  7050. }
  7051. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  7052. this._postProcessesTakenIndices.push(insertAt);
  7053. }
  7054. var result = insertAt + add;
  7055. this._postProcesses[result] = postProcess;
  7056. return result;
  7057. };
  7058. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  7059. if (atIndices === void 0) { atIndices = null; }
  7060. var result = [];
  7061. if (!atIndices) {
  7062. var length = this._postProcesses.length;
  7063. for (var i = 0; i < length; i++) {
  7064. if (this._postProcesses[i] !== postProcess) {
  7065. continue;
  7066. }
  7067. delete this._postProcesses[i];
  7068. var index = this._postProcessesTakenIndices.indexOf(i);
  7069. this._postProcessesTakenIndices.splice(index, 1);
  7070. }
  7071. }
  7072. else {
  7073. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  7074. for (i = 0; i < atIndices.length; i++) {
  7075. var foundPostProcess = this._postProcesses[atIndices[i]];
  7076. if (foundPostProcess !== postProcess) {
  7077. result.push(i);
  7078. continue;
  7079. }
  7080. delete this._postProcesses[atIndices[i]];
  7081. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  7082. this._postProcessesTakenIndices.splice(index, 1);
  7083. }
  7084. }
  7085. return result;
  7086. };
  7087. Camera.prototype.getWorldMatrix = function () {
  7088. if (!this._worldMatrix) {
  7089. this._worldMatrix = BABYLON.Matrix.Identity();
  7090. }
  7091. var viewMatrix = this.getViewMatrix();
  7092. viewMatrix.invertToRef(this._worldMatrix);
  7093. return this._worldMatrix;
  7094. };
  7095. Camera.prototype._getViewMatrix = function () {
  7096. return BABYLON.Matrix.Identity();
  7097. };
  7098. Camera.prototype.getViewMatrix = function () {
  7099. this._computedViewMatrix = this._computeViewMatrix();
  7100. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  7101. this._globalPosition.copyFrom(this.position);
  7102. return this._computedViewMatrix;
  7103. }
  7104. if (!this._worldMatrix) {
  7105. this._worldMatrix = BABYLON.Matrix.Identity();
  7106. }
  7107. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7108. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7109. this._computedViewMatrix.invert();
  7110. this._currentRenderId = this.getScene().getRenderId();
  7111. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7112. return this._computedViewMatrix;
  7113. };
  7114. Camera.prototype._computeViewMatrix = function (force) {
  7115. if (!force && this._isSynchronizedViewMatrix()) {
  7116. return this._computedViewMatrix;
  7117. }
  7118. this._computedViewMatrix = this._getViewMatrix();
  7119. if (!this.parent || !this.parent.getWorldMatrix) {
  7120. this._currentRenderId = this.getScene().getRenderId();
  7121. }
  7122. return this._computedViewMatrix;
  7123. };
  7124. Camera.prototype.getProjectionMatrix = function (force) {
  7125. if (!force && this._isSynchronizedProjectionMatrix()) {
  7126. return this._projectionMatrix;
  7127. }
  7128. var engine = this.getEngine();
  7129. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7130. if (this.minZ <= 0) {
  7131. this.minZ = 0.1;
  7132. }
  7133. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7134. return this._projectionMatrix;
  7135. }
  7136. var halfWidth = engine.getRenderWidth() / 2.0;
  7137. var halfHeight = engine.getRenderHeight() / 2.0;
  7138. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7139. return this._projectionMatrix;
  7140. };
  7141. Camera.prototype.dispose = function () {
  7142. // Remove from scene
  7143. this.getScene().removeCamera(this);
  7144. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7145. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7146. }
  7147. };
  7148. // Statics
  7149. Camera._PERSPECTIVE_CAMERA = 0;
  7150. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7151. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7152. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7153. return Camera;
  7154. })(BABYLON.Node);
  7155. BABYLON.Camera = Camera;
  7156. })(BABYLON || (BABYLON = {}));
  7157. //# sourceMappingURL=babylon.camera.js.map
  7158. var BABYLON;
  7159. (function (BABYLON) {
  7160. var TargetCamera = (function (_super) {
  7161. __extends(TargetCamera, _super);
  7162. function TargetCamera(name, position, scene) {
  7163. _super.call(this, name, position, scene);
  7164. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7165. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7166. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7167. this.speed = 2.0;
  7168. this.noRotationConstraint = false;
  7169. this.lockedTarget = null;
  7170. this._currentTarget = BABYLON.Vector3.Zero();
  7171. this._viewMatrix = BABYLON.Matrix.Zero();
  7172. this._camMatrix = BABYLON.Matrix.Zero();
  7173. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7174. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7175. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7176. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7177. this._lookAtTemp = BABYLON.Matrix.Zero();
  7178. this._tempMatrix = BABYLON.Matrix.Zero();
  7179. }
  7180. TargetCamera.prototype._getLockedTargetPosition = function () {
  7181. if (!this.lockedTarget) {
  7182. return null;
  7183. }
  7184. return this.lockedTarget.position || this.lockedTarget;
  7185. };
  7186. // Cache
  7187. TargetCamera.prototype._initCache = function () {
  7188. _super.prototype._initCache.call(this);
  7189. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7190. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7191. };
  7192. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7193. if (!ignoreParentClass) {
  7194. _super.prototype._updateCache.call(this);
  7195. }
  7196. var lockedTargetPosition = this._getLockedTargetPosition();
  7197. if (!lockedTargetPosition) {
  7198. this._cache.lockedTarget = null;
  7199. }
  7200. else {
  7201. if (!this._cache.lockedTarget) {
  7202. this._cache.lockedTarget = lockedTargetPosition.clone();
  7203. }
  7204. else {
  7205. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7206. }
  7207. }
  7208. this._cache.rotation.copyFrom(this.rotation);
  7209. };
  7210. // Synchronized
  7211. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7212. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7213. return false;
  7214. }
  7215. var lockedTargetPosition = this._getLockedTargetPosition();
  7216. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7217. };
  7218. // Methods
  7219. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7220. var engine = this.getEngine();
  7221. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7222. };
  7223. // Target
  7224. TargetCamera.prototype.setTarget = function (target) {
  7225. this.upVector.normalize();
  7226. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7227. this._camMatrix.invert();
  7228. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7229. var vDir = target.subtract(this.position);
  7230. if (vDir.x >= 0.0) {
  7231. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7232. }
  7233. else {
  7234. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7235. }
  7236. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7237. if (isNaN(this.rotation.x)) {
  7238. this.rotation.x = 0;
  7239. }
  7240. if (isNaN(this.rotation.y)) {
  7241. this.rotation.y = 0;
  7242. }
  7243. if (isNaN(this.rotation.z)) {
  7244. this.rotation.z = 0;
  7245. }
  7246. };
  7247. TargetCamera.prototype.getTarget = function () {
  7248. return this._currentTarget;
  7249. };
  7250. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7251. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7252. };
  7253. TargetCamera.prototype._updatePosition = function () {
  7254. this.position.addInPlace(this.cameraDirection);
  7255. };
  7256. TargetCamera.prototype._update = function () {
  7257. var needToMove = this._decideIfNeedsToMove();
  7258. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7259. // Move
  7260. if (needToMove) {
  7261. this._updatePosition();
  7262. }
  7263. // Rotate
  7264. if (needToRotate) {
  7265. this.rotation.x += this.cameraRotation.x;
  7266. this.rotation.y += this.cameraRotation.y;
  7267. if (!this.noRotationConstraint) {
  7268. var limit = (Math.PI / 2) * 0.95;
  7269. if (this.rotation.x > limit)
  7270. this.rotation.x = limit;
  7271. if (this.rotation.x < -limit)
  7272. this.rotation.x = -limit;
  7273. }
  7274. }
  7275. // Inertia
  7276. if (needToMove) {
  7277. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7278. this.cameraDirection.x = 0;
  7279. }
  7280. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7281. this.cameraDirection.y = 0;
  7282. }
  7283. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7284. this.cameraDirection.z = 0;
  7285. }
  7286. this.cameraDirection.scaleInPlace(this.inertia);
  7287. }
  7288. if (needToRotate) {
  7289. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7290. this.cameraRotation.x = 0;
  7291. }
  7292. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7293. this.cameraRotation.y = 0;
  7294. }
  7295. this.cameraRotation.scaleInPlace(this.inertia);
  7296. }
  7297. };
  7298. TargetCamera.prototype._getViewMatrix = function () {
  7299. if (!this.lockedTarget) {
  7300. // Compute
  7301. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7302. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7303. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7304. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7305. this._lookAtTemp.invert();
  7306. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7307. }
  7308. else {
  7309. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7310. }
  7311. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7312. // Computing target and final matrix
  7313. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7314. }
  7315. else {
  7316. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7317. }
  7318. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7319. return this._viewMatrix;
  7320. };
  7321. return TargetCamera;
  7322. })(BABYLON.Camera);
  7323. BABYLON.TargetCamera = TargetCamera;
  7324. })(BABYLON || (BABYLON = {}));
  7325. //# sourceMappingURL=babylon.targetCamera.js.map
  7326. var BABYLON;
  7327. (function (BABYLON) {
  7328. var FollowCamera = (function (_super) {
  7329. __extends(FollowCamera, _super);
  7330. function FollowCamera(name, position, scene) {
  7331. _super.call(this, name, position, scene);
  7332. this.radius = 12;
  7333. this.rotationOffset = 0;
  7334. this.heightOffset = 4;
  7335. this.cameraAcceleration = 0.05;
  7336. this.maxCameraSpeed = 20;
  7337. }
  7338. FollowCamera.prototype.getRadians = function (degrees) {
  7339. return degrees * Math.PI / 180;
  7340. };
  7341. FollowCamera.prototype.follow = function (cameraTarget) {
  7342. if (!cameraTarget)
  7343. return;
  7344. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7345. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7346. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7347. var dx = targetX - this.position.x;
  7348. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7349. var dz = (targetZ) - this.position.z;
  7350. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7351. var vy = dy * this.cameraAcceleration;
  7352. var vz = dz * this.cameraAcceleration * 2;
  7353. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7354. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7355. }
  7356. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7357. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7358. }
  7359. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7360. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7361. }
  7362. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7363. this.setTarget(cameraTarget.position);
  7364. };
  7365. FollowCamera.prototype._update = function () {
  7366. _super.prototype._update.call(this);
  7367. this.follow(this.target);
  7368. };
  7369. return FollowCamera;
  7370. })(BABYLON.TargetCamera);
  7371. BABYLON.FollowCamera = FollowCamera;
  7372. })(BABYLON || (BABYLON = {}));
  7373. //# sourceMappingURL=babylon.followCamera.js.map
  7374. var BABYLON;
  7375. (function (BABYLON) {
  7376. var FreeCamera = (function (_super) {
  7377. __extends(FreeCamera, _super);
  7378. function FreeCamera(name, position, scene) {
  7379. _super.call(this, name, position, scene);
  7380. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7381. this.keysUp = [38];
  7382. this.keysDown = [40];
  7383. this.keysLeft = [37];
  7384. this.keysRight = [39];
  7385. this.checkCollisions = false;
  7386. this.applyGravity = false;
  7387. this.angularSensibility = 2000.0;
  7388. this._keys = [];
  7389. this._collider = new BABYLON.Collider();
  7390. this._needMoveForGravity = true;
  7391. this._oldPosition = BABYLON.Vector3.Zero();
  7392. this._diffPosition = BABYLON.Vector3.Zero();
  7393. this._newPosition = BABYLON.Vector3.Zero();
  7394. }
  7395. // Controls
  7396. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7397. var _this = this;
  7398. var previousPosition;
  7399. var engine = this.getEngine();
  7400. if (this._attachedElement) {
  7401. return;
  7402. }
  7403. this._attachedElement = element;
  7404. if (this._onMouseDown === undefined) {
  7405. this._onMouseDown = function (evt) {
  7406. previousPosition = {
  7407. x: evt.clientX,
  7408. y: evt.clientY
  7409. };
  7410. if (!noPreventDefault) {
  7411. evt.preventDefault();
  7412. }
  7413. };
  7414. this._onMouseUp = function (evt) {
  7415. previousPosition = null;
  7416. if (!noPreventDefault) {
  7417. evt.preventDefault();
  7418. }
  7419. };
  7420. this._onMouseOut = function (evt) {
  7421. previousPosition = null;
  7422. _this._keys = [];
  7423. if (!noPreventDefault) {
  7424. evt.preventDefault();
  7425. }
  7426. };
  7427. this._onMouseMove = function (evt) {
  7428. if (!previousPosition && !engine.isPointerLock) {
  7429. return;
  7430. }
  7431. var offsetX;
  7432. var offsetY;
  7433. if (!engine.isPointerLock) {
  7434. offsetX = evt.clientX - previousPosition.x;
  7435. offsetY = evt.clientY - previousPosition.y;
  7436. }
  7437. else {
  7438. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7439. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7440. }
  7441. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7442. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7443. previousPosition = {
  7444. x: evt.clientX,
  7445. y: evt.clientY
  7446. };
  7447. if (!noPreventDefault) {
  7448. evt.preventDefault();
  7449. }
  7450. };
  7451. this._onKeyDown = function (evt) {
  7452. 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) {
  7453. var index = _this._keys.indexOf(evt.keyCode);
  7454. if (index === -1) {
  7455. _this._keys.push(evt.keyCode);
  7456. }
  7457. if (!noPreventDefault) {
  7458. evt.preventDefault();
  7459. }
  7460. }
  7461. };
  7462. this._onKeyUp = function (evt) {
  7463. 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) {
  7464. var index = _this._keys.indexOf(evt.keyCode);
  7465. if (index >= 0) {
  7466. _this._keys.splice(index, 1);
  7467. }
  7468. if (!noPreventDefault) {
  7469. evt.preventDefault();
  7470. }
  7471. }
  7472. };
  7473. this._onLostFocus = function () {
  7474. _this._keys = [];
  7475. };
  7476. this._reset = function () {
  7477. _this._keys = [];
  7478. previousPosition = null;
  7479. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7480. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7481. };
  7482. }
  7483. element.addEventListener("mousedown", this._onMouseDown, false);
  7484. element.addEventListener("mouseup", this._onMouseUp, false);
  7485. element.addEventListener("mouseout", this._onMouseOut, false);
  7486. element.addEventListener("mousemove", this._onMouseMove, false);
  7487. BABYLON.Tools.RegisterTopRootEvents([
  7488. { name: "keydown", handler: this._onKeyDown },
  7489. { name: "keyup", handler: this._onKeyUp },
  7490. { name: "blur", handler: this._onLostFocus }
  7491. ]);
  7492. };
  7493. FreeCamera.prototype.detachControl = function (element) {
  7494. if (this._attachedElement != element) {
  7495. return;
  7496. }
  7497. element.removeEventListener("mousedown", this._onMouseDown);
  7498. element.removeEventListener("mouseup", this._onMouseUp);
  7499. element.removeEventListener("mouseout", this._onMouseOut);
  7500. element.removeEventListener("mousemove", this._onMouseMove);
  7501. BABYLON.Tools.UnregisterTopRootEvents([
  7502. { name: "keydown", handler: this._onKeyDown },
  7503. { name: "keyup", handler: this._onKeyUp },
  7504. { name: "blur", handler: this._onLostFocus }
  7505. ]);
  7506. this._attachedElement = null;
  7507. if (this._reset) {
  7508. this._reset();
  7509. }
  7510. };
  7511. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7512. var globalPosition;
  7513. if (this.parent) {
  7514. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7515. }
  7516. else {
  7517. globalPosition = this.position;
  7518. }
  7519. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7520. this._collider.radius = this.ellipsoid;
  7521. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7522. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7523. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7524. this.position.addInPlace(this._diffPosition);
  7525. if (this.onCollide) {
  7526. this.onCollide(this._collider.collidedMesh);
  7527. }
  7528. }
  7529. };
  7530. FreeCamera.prototype._checkInputs = function () {
  7531. if (!this._localDirection) {
  7532. this._localDirection = BABYLON.Vector3.Zero();
  7533. this._transformedDirection = BABYLON.Vector3.Zero();
  7534. }
  7535. for (var index = 0; index < this._keys.length; index++) {
  7536. var keyCode = this._keys[index];
  7537. var speed = this._computeLocalCameraSpeed();
  7538. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7539. this._localDirection.copyFromFloats(-speed, 0, 0);
  7540. }
  7541. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7542. this._localDirection.copyFromFloats(0, 0, speed);
  7543. }
  7544. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7545. this._localDirection.copyFromFloats(speed, 0, 0);
  7546. }
  7547. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7548. this._localDirection.copyFromFloats(0, 0, -speed);
  7549. }
  7550. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7551. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7552. this.cameraDirection.addInPlace(this._transformedDirection);
  7553. }
  7554. };
  7555. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7556. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7557. };
  7558. FreeCamera.prototype._updatePosition = function () {
  7559. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7560. this._collideWithWorld(this.cameraDirection);
  7561. if (this.applyGravity) {
  7562. var oldPosition = this.position;
  7563. this._collideWithWorld(this.getScene().gravity);
  7564. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7565. }
  7566. }
  7567. else {
  7568. this.position.addInPlace(this.cameraDirection);
  7569. }
  7570. };
  7571. FreeCamera.prototype._update = function () {
  7572. this._checkInputs();
  7573. _super.prototype._update.call(this);
  7574. };
  7575. return FreeCamera;
  7576. })(BABYLON.TargetCamera);
  7577. BABYLON.FreeCamera = FreeCamera;
  7578. })(BABYLON || (BABYLON = {}));
  7579. //# sourceMappingURL=babylon.freeCamera.js.map
  7580. var BABYLON;
  7581. (function (BABYLON) {
  7582. // We're mainly based on the logic defined into the FreeCamera code
  7583. var TouchCamera = (function (_super) {
  7584. __extends(TouchCamera, _super);
  7585. function TouchCamera(name, position, scene) {
  7586. _super.call(this, name, position, scene);
  7587. this._offsetX = null;
  7588. this._offsetY = null;
  7589. this._pointerCount = 0;
  7590. this._pointerPressed = [];
  7591. this.angularSensibility = 200000.0;
  7592. this.moveSensibility = 500.0;
  7593. }
  7594. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7595. var _this = this;
  7596. var previousPosition;
  7597. if (this._attachedCanvas) {
  7598. return;
  7599. }
  7600. this._attachedCanvas = canvas;
  7601. if (this._onPointerDown === undefined) {
  7602. this._onPointerDown = function (evt) {
  7603. if (!noPreventDefault) {
  7604. evt.preventDefault();
  7605. }
  7606. _this._pointerPressed.push(evt.pointerId);
  7607. if (_this._pointerPressed.length !== 1) {
  7608. return;
  7609. }
  7610. previousPosition = {
  7611. x: evt.clientX,
  7612. y: evt.clientY
  7613. };
  7614. };
  7615. this._onPointerUp = function (evt) {
  7616. if (!noPreventDefault) {
  7617. evt.preventDefault();
  7618. }
  7619. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7620. if (index === -1) {
  7621. return;
  7622. }
  7623. _this._pointerPressed.splice(index, 1);
  7624. if (index != 0) {
  7625. return;
  7626. }
  7627. previousPosition = null;
  7628. _this._offsetX = null;
  7629. _this._offsetY = null;
  7630. };
  7631. this._onPointerMove = function (evt) {
  7632. if (!noPreventDefault) {
  7633. evt.preventDefault();
  7634. }
  7635. if (!previousPosition) {
  7636. return;
  7637. }
  7638. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7639. if (index != 0) {
  7640. return;
  7641. }
  7642. _this._offsetX = evt.clientX - previousPosition.x;
  7643. _this._offsetY = -(evt.clientY - previousPosition.y);
  7644. };
  7645. this._onLostFocus = function () {
  7646. _this._offsetX = null;
  7647. _this._offsetY = null;
  7648. };
  7649. }
  7650. canvas.addEventListener("pointerdown", this._onPointerDown);
  7651. canvas.addEventListener("pointerup", this._onPointerUp);
  7652. canvas.addEventListener("pointerout", this._onPointerUp);
  7653. canvas.addEventListener("pointermove", this._onPointerMove);
  7654. BABYLON.Tools.RegisterTopRootEvents([
  7655. { name: "blur", handler: this._onLostFocus }
  7656. ]);
  7657. };
  7658. TouchCamera.prototype.detachControl = function (canvas) {
  7659. if (this._attachedCanvas != canvas) {
  7660. return;
  7661. }
  7662. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7663. canvas.removeEventListener("pointerup", this._onPointerUp);
  7664. canvas.removeEventListener("pointerout", this._onPointerUp);
  7665. canvas.removeEventListener("pointermove", this._onPointerMove);
  7666. BABYLON.Tools.UnregisterTopRootEvents([
  7667. { name: "blur", handler: this._onLostFocus }
  7668. ]);
  7669. this._attachedCanvas = null;
  7670. };
  7671. TouchCamera.prototype._checkInputs = function () {
  7672. if (!this._offsetX) {
  7673. return;
  7674. }
  7675. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7676. if (this._pointerPressed.length > 1) {
  7677. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7678. }
  7679. else {
  7680. var speed = this._computeLocalCameraSpeed();
  7681. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7682. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7683. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7684. }
  7685. };
  7686. return TouchCamera;
  7687. })(BABYLON.FreeCamera);
  7688. BABYLON.TouchCamera = TouchCamera;
  7689. })(BABYLON || (BABYLON = {}));
  7690. //# sourceMappingURL=babylon.touchCamera.js.map
  7691. var BABYLON;
  7692. (function (BABYLON) {
  7693. // We're mainly based on the logic defined into the FreeCamera code
  7694. var DeviceOrientationCamera = (function (_super) {
  7695. __extends(DeviceOrientationCamera, _super);
  7696. function DeviceOrientationCamera(name, position, scene) {
  7697. var _this = this;
  7698. _super.call(this, name, position, scene);
  7699. this._offsetX = null;
  7700. this._offsetY = null;
  7701. this._orientationGamma = 0;
  7702. this._orientationBeta = 0;
  7703. this._initialOrientationGamma = 0;
  7704. this._initialOrientationBeta = 0;
  7705. this.angularSensibility = 10000.0;
  7706. this.moveSensibility = 50.0;
  7707. window.addEventListener("resize", function () {
  7708. _this._initialOrientationGamma = null;
  7709. }, false);
  7710. }
  7711. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7712. var _this = this;
  7713. if (this._attachedCanvas) {
  7714. return;
  7715. }
  7716. this._attachedCanvas = canvas;
  7717. if (!this._orientationChanged) {
  7718. this._orientationChanged = function (evt) {
  7719. if (!_this._initialOrientationGamma) {
  7720. _this._initialOrientationGamma = evt.gamma;
  7721. _this._initialOrientationBeta = evt.beta;
  7722. }
  7723. _this._orientationGamma = evt.gamma;
  7724. _this._orientationBeta = evt.beta;
  7725. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7726. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7727. };
  7728. }
  7729. window.addEventListener("deviceorientation", this._orientationChanged);
  7730. };
  7731. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7732. if (this._attachedCanvas != canvas) {
  7733. return;
  7734. }
  7735. window.removeEventListener("deviceorientation", this._orientationChanged);
  7736. this._attachedCanvas = null;
  7737. this._orientationGamma = 0;
  7738. this._orientationBeta = 0;
  7739. this._initialOrientationGamma = 0;
  7740. this._initialOrientationBeta = 0;
  7741. };
  7742. DeviceOrientationCamera.prototype._checkInputs = function () {
  7743. if (!this._offsetX) {
  7744. return;
  7745. }
  7746. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7747. var speed = this._computeLocalCameraSpeed();
  7748. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7749. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7750. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7751. };
  7752. return DeviceOrientationCamera;
  7753. })(BABYLON.FreeCamera);
  7754. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7755. })(BABYLON || (BABYLON = {}));
  7756. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7757. var BABYLON;
  7758. (function (BABYLON) {
  7759. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7760. var ArcRotateCamera = (function (_super) {
  7761. __extends(ArcRotateCamera, _super);
  7762. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7763. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7764. this.alpha = alpha;
  7765. this.beta = beta;
  7766. this.radius = radius;
  7767. this.target = target;
  7768. this.inertialAlphaOffset = 0;
  7769. this.inertialBetaOffset = 0;
  7770. this.inertialRadiusOffset = 0;
  7771. this.lowerAlphaLimit = null;
  7772. this.upperAlphaLimit = null;
  7773. this.lowerBetaLimit = 0.01;
  7774. this.upperBetaLimit = Math.PI;
  7775. this.lowerRadiusLimit = null;
  7776. this.upperRadiusLimit = null;
  7777. this.angularSensibility = 1000.0;
  7778. this.wheelPrecision = 3.0;
  7779. this.pinchPrecision = 2.0;
  7780. this.keysUp = [38];
  7781. this.keysDown = [40];
  7782. this.keysLeft = [37];
  7783. this.keysRight = [39];
  7784. this.zoomOnFactor = 1;
  7785. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7786. this._keys = [];
  7787. this._viewMatrix = new BABYLON.Matrix();
  7788. this.checkCollisions = false;
  7789. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7790. this._collider = new BABYLON.Collider();
  7791. this._previousPosition = BABYLON.Vector3.Zero();
  7792. this._collisionVelocity = BABYLON.Vector3.Zero();
  7793. this._newPosition = BABYLON.Vector3.Zero();
  7794. if (!this.target) {
  7795. this.target = BABYLON.Vector3.Zero();
  7796. }
  7797. this.getViewMatrix();
  7798. }
  7799. ArcRotateCamera.prototype._getTargetPosition = function () {
  7800. return this.target.position || this.target;
  7801. };
  7802. // Cache
  7803. ArcRotateCamera.prototype._initCache = function () {
  7804. _super.prototype._initCache.call(this);
  7805. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7806. this._cache.alpha = undefined;
  7807. this._cache.beta = undefined;
  7808. this._cache.radius = undefined;
  7809. this._cache.targetScreenOffset = undefined;
  7810. };
  7811. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7812. if (!ignoreParentClass) {
  7813. _super.prototype._updateCache.call(this);
  7814. }
  7815. this._cache.target.copyFrom(this._getTargetPosition());
  7816. this._cache.alpha = this.alpha;
  7817. this._cache.beta = this.beta;
  7818. this._cache.radius = this.radius;
  7819. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7820. };
  7821. // Synchronized
  7822. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7823. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7824. return false;
  7825. 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);
  7826. };
  7827. // Methods
  7828. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7829. var _this = this;
  7830. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7831. var previousPinchDistance = 0;
  7832. var pointers = new BABYLON.SmartCollection();
  7833. if (this._attachedElement) {
  7834. return;
  7835. }
  7836. this._attachedElement = element;
  7837. var engine = this.getEngine();
  7838. if (this._onPointerDown === undefined) {
  7839. this._onPointerDown = function (evt) {
  7840. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7841. cacheSoloPointer = pointers.item(evt.pointerId);
  7842. if (!noPreventDefault) {
  7843. evt.preventDefault();
  7844. }
  7845. };
  7846. this._onPointerUp = function (evt) {
  7847. cacheSoloPointer = null;
  7848. previousPinchDistance = 0;
  7849. pointers.remove(evt.pointerId);
  7850. if (!noPreventDefault) {
  7851. evt.preventDefault();
  7852. }
  7853. };
  7854. this._onPointerMove = function (evt) {
  7855. if (!noPreventDefault) {
  7856. evt.preventDefault();
  7857. }
  7858. switch (pointers.count) {
  7859. case 1:
  7860. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7861. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7862. var offsetX = evt.clientX - cacheSoloPointer.x;
  7863. var offsetY = evt.clientY - cacheSoloPointer.y;
  7864. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7865. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7866. //pointers.item(evt.pointerId).x = evt.clientX;
  7867. //pointers.item(evt.pointerId).y = evt.clientY;
  7868. cacheSoloPointer.x = evt.clientX;
  7869. cacheSoloPointer.y = evt.clientY;
  7870. break;
  7871. case 2:
  7872. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7873. pointers.item(evt.pointerId).x = evt.clientX;
  7874. pointers.item(evt.pointerId).y = evt.clientY;
  7875. var direction = 1;
  7876. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7877. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7878. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7879. if (previousPinchDistance === 0) {
  7880. previousPinchDistance = pinchSquaredDistance;
  7881. return;
  7882. }
  7883. if (pinchSquaredDistance !== previousPinchDistance) {
  7884. if (pinchSquaredDistance > previousPinchDistance) {
  7885. direction = -1;
  7886. }
  7887. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7888. previousPinchDistance = pinchSquaredDistance;
  7889. }
  7890. break;
  7891. default:
  7892. if (pointers.item(evt.pointerId)) {
  7893. pointers.item(evt.pointerId).x = evt.clientX;
  7894. pointers.item(evt.pointerId).y = evt.clientY;
  7895. }
  7896. }
  7897. };
  7898. this._onMouseMove = function (evt) {
  7899. if (!engine.isPointerLock) {
  7900. return;
  7901. }
  7902. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7903. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7904. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7905. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7906. if (!noPreventDefault) {
  7907. evt.preventDefault();
  7908. }
  7909. };
  7910. this._wheel = function (event) {
  7911. var delta = 0;
  7912. if (event.wheelDelta) {
  7913. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7914. }
  7915. else if (event.detail) {
  7916. delta = -event.detail / _this.wheelPrecision;
  7917. }
  7918. if (delta)
  7919. _this.inertialRadiusOffset += delta;
  7920. if (event.preventDefault) {
  7921. if (!noPreventDefault) {
  7922. event.preventDefault();
  7923. }
  7924. }
  7925. };
  7926. this._onKeyDown = function (evt) {
  7927. 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) {
  7928. var index = _this._keys.indexOf(evt.keyCode);
  7929. if (index === -1) {
  7930. _this._keys.push(evt.keyCode);
  7931. }
  7932. if (evt.preventDefault) {
  7933. if (!noPreventDefault) {
  7934. evt.preventDefault();
  7935. }
  7936. }
  7937. }
  7938. };
  7939. this._onKeyUp = function (evt) {
  7940. 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) {
  7941. var index = _this._keys.indexOf(evt.keyCode);
  7942. if (index >= 0) {
  7943. _this._keys.splice(index, 1);
  7944. }
  7945. if (evt.preventDefault) {
  7946. if (!noPreventDefault) {
  7947. evt.preventDefault();
  7948. }
  7949. }
  7950. }
  7951. };
  7952. this._onLostFocus = function () {
  7953. _this._keys = [];
  7954. pointers.empty();
  7955. previousPinchDistance = 0;
  7956. cacheSoloPointer = null;
  7957. };
  7958. this._onGestureStart = function (e) {
  7959. if (window.MSGesture === undefined) {
  7960. return;
  7961. }
  7962. if (!_this._MSGestureHandler) {
  7963. _this._MSGestureHandler = new MSGesture();
  7964. _this._MSGestureHandler.target = element;
  7965. }
  7966. _this._MSGestureHandler.addPointer(e.pointerId);
  7967. };
  7968. this._onGesture = function (e) {
  7969. _this.radius *= e.scale;
  7970. if (e.preventDefault) {
  7971. if (!noPreventDefault) {
  7972. e.stopPropagation();
  7973. e.preventDefault();
  7974. }
  7975. }
  7976. };
  7977. this._reset = function () {
  7978. _this._keys = [];
  7979. _this.inertialAlphaOffset = 0;
  7980. _this.inertialBetaOffset = 0;
  7981. _this.inertialRadiusOffset = 0;
  7982. pointers.empty();
  7983. previousPinchDistance = 0;
  7984. cacheSoloPointer = null;
  7985. };
  7986. }
  7987. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7988. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7989. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7990. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7991. element.addEventListener("mousemove", this._onMouseMove, false);
  7992. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7993. element.addEventListener("MSGestureChange", this._onGesture, false);
  7994. element.addEventListener('mousewheel', this._wheel, false);
  7995. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7996. BABYLON.Tools.RegisterTopRootEvents([
  7997. { name: "keydown", handler: this._onKeyDown },
  7998. { name: "keyup", handler: this._onKeyUp },
  7999. { name: "blur", handler: this._onLostFocus }
  8000. ]);
  8001. };
  8002. ArcRotateCamera.prototype.detachControl = function (element) {
  8003. if (this._attachedElement !== element) {
  8004. return;
  8005. }
  8006. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  8007. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  8008. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  8009. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  8010. element.removeEventListener("mousemove", this._onMouseMove);
  8011. element.removeEventListener("MSPointerDown", this._onGestureStart);
  8012. element.removeEventListener("MSGestureChange", this._onGesture);
  8013. element.removeEventListener('mousewheel', this._wheel);
  8014. element.removeEventListener('DOMMouseScroll', this._wheel);
  8015. BABYLON.Tools.UnregisterTopRootEvents([
  8016. { name: "keydown", handler: this._onKeyDown },
  8017. { name: "keyup", handler: this._onKeyUp },
  8018. { name: "blur", handler: this._onLostFocus }
  8019. ]);
  8020. this._MSGestureHandler = null;
  8021. this._attachedElement = null;
  8022. if (this._reset) {
  8023. this._reset();
  8024. }
  8025. };
  8026. ArcRotateCamera.prototype._update = function () {
  8027. for (var index = 0; index < this._keys.length; index++) {
  8028. var keyCode = this._keys[index];
  8029. if (this.keysLeft.indexOf(keyCode) !== -1) {
  8030. this.inertialAlphaOffset -= 0.01;
  8031. }
  8032. else if (this.keysUp.indexOf(keyCode) !== -1) {
  8033. this.inertialBetaOffset -= 0.01;
  8034. }
  8035. else if (this.keysRight.indexOf(keyCode) !== -1) {
  8036. this.inertialAlphaOffset += 0.01;
  8037. }
  8038. else if (this.keysDown.indexOf(keyCode) !== -1) {
  8039. this.inertialBetaOffset += 0.01;
  8040. }
  8041. }
  8042. // Inertia
  8043. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  8044. this.alpha += this.inertialAlphaOffset;
  8045. this.beta += this.inertialBetaOffset;
  8046. this.radius -= this.inertialRadiusOffset;
  8047. this.inertialAlphaOffset *= this.inertia;
  8048. this.inertialBetaOffset *= this.inertia;
  8049. this.inertialRadiusOffset *= this.inertia;
  8050. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  8051. this.inertialAlphaOffset = 0;
  8052. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  8053. this.inertialBetaOffset = 0;
  8054. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  8055. this.inertialRadiusOffset = 0;
  8056. }
  8057. // Limits
  8058. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  8059. this.alpha = this.lowerAlphaLimit;
  8060. }
  8061. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  8062. this.alpha = this.upperAlphaLimit;
  8063. }
  8064. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  8065. this.beta = this.lowerBetaLimit;
  8066. }
  8067. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  8068. this.beta = this.upperBetaLimit;
  8069. }
  8070. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  8071. this.radius = this.lowerRadiusLimit;
  8072. }
  8073. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  8074. this.radius = this.upperRadiusLimit;
  8075. }
  8076. };
  8077. ArcRotateCamera.prototype.setPosition = function (position) {
  8078. var radiusv3 = position.subtract(this._getTargetPosition());
  8079. this.radius = radiusv3.length();
  8080. // Alpha
  8081. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  8082. if (radiusv3.z < 0) {
  8083. this.alpha = 2 * Math.PI - this.alpha;
  8084. }
  8085. // Beta
  8086. this.beta = Math.acos(radiusv3.y / this.radius);
  8087. };
  8088. ArcRotateCamera.prototype._getViewMatrix = function () {
  8089. // Compute
  8090. var cosa = Math.cos(this.alpha);
  8091. var sina = Math.sin(this.alpha);
  8092. var cosb = Math.cos(this.beta);
  8093. var sinb = Math.sin(this.beta);
  8094. var target = this._getTargetPosition();
  8095. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8096. if (this.checkCollisions) {
  8097. this._collider.radius = this.collisionRadius;
  8098. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8099. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8100. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8101. this.position.copyFrom(this._previousPosition);
  8102. this.alpha = this._previousAlpha;
  8103. this.beta = this._previousBeta;
  8104. this.radius = this._previousRadius;
  8105. if (this.onCollide) {
  8106. this.onCollide(this._collider.collidedMesh);
  8107. }
  8108. }
  8109. }
  8110. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8111. this._previousAlpha = this.alpha;
  8112. this._previousBeta = this.beta;
  8113. this._previousRadius = this.radius;
  8114. this._previousPosition.copyFrom(this.position);
  8115. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8116. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8117. return this._viewMatrix;
  8118. };
  8119. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8120. meshes = meshes || this.getScene().meshes;
  8121. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8122. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8123. this.radius = distance * this.zoomOnFactor;
  8124. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8125. };
  8126. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8127. var meshesOrMinMaxVector;
  8128. var distance;
  8129. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8130. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8131. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8132. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8133. }
  8134. else {
  8135. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8136. distance = meshesOrMinMaxVectorAndDistance.distance;
  8137. }
  8138. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8139. this.maxZ = distance * 2;
  8140. };
  8141. return ArcRotateCamera;
  8142. })(BABYLON.Camera);
  8143. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8144. })(BABYLON || (BABYLON = {}));
  8145. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8146. (function (BABYLON) {
  8147. /**
  8148. * Represents a scene to be rendered by the engine.
  8149. * @see http://doc.babylonjs.com/page.php?p=21911
  8150. */
  8151. var Scene = (function () {
  8152. /**
  8153. * @constructor
  8154. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8155. */
  8156. function Scene(engine) {
  8157. // Members
  8158. this.autoClear = true;
  8159. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8160. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8161. this.forceWireframe = false;
  8162. this.forcePointsCloud = false;
  8163. this.forceShowBoundingBoxes = false;
  8164. this.animationsEnabled = true;
  8165. 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
  8166. // Fog
  8167. /**
  8168. * is fog enabled on this scene.
  8169. * @type {boolean}
  8170. */
  8171. this.fogEnabled = true;
  8172. this.fogMode = Scene.FOGMODE_NONE;
  8173. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8174. this.fogDensity = 0.1;
  8175. this.fogStart = 0;
  8176. this.fogEnd = 1000.0;
  8177. // Lights
  8178. /**
  8179. * is shadow enabled on this scene.
  8180. * @type {boolean}
  8181. */
  8182. this.shadowsEnabled = true;
  8183. /**
  8184. * is light enabled on this scene.
  8185. * @type {boolean}
  8186. */
  8187. this.lightsEnabled = true;
  8188. /**
  8189. * All of the lights added to this scene.
  8190. * @see BABYLON.Light
  8191. * @type {BABYLON.Light[]}
  8192. */
  8193. this.lights = new Array();
  8194. // Cameras
  8195. /**
  8196. * All of the cameras added to this scene.
  8197. * @see BABYLON.Camera
  8198. * @type {BABYLON.Camera[]}
  8199. */
  8200. this.cameras = new Array();
  8201. this.activeCameras = new Array();
  8202. // Meshes
  8203. /**
  8204. * All of the (abstract) meshes added to this scene.
  8205. * @see BABYLON.AbstractMesh
  8206. * @type {BABYLON.AbstractMesh[]}
  8207. */
  8208. this.meshes = new Array();
  8209. // Geometries
  8210. this._geometries = new Array();
  8211. this.materials = new Array();
  8212. this.multiMaterials = new Array();
  8213. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8214. // Textures
  8215. this.texturesEnabled = true;
  8216. this.textures = new Array();
  8217. // Particles
  8218. this.particlesEnabled = true;
  8219. this.particleSystems = new Array();
  8220. // Sprites
  8221. this.spritesEnabled = true;
  8222. this.spriteManagers = new Array();
  8223. // Layers
  8224. this.layers = new Array();
  8225. // Skeletons
  8226. this.skeletonsEnabled = true;
  8227. this.skeletons = new Array();
  8228. // Lens flares
  8229. this.lensFlaresEnabled = true;
  8230. this.lensFlareSystems = new Array();
  8231. // Collisions
  8232. this.collisionsEnabled = true;
  8233. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8234. // Postprocesses
  8235. this.postProcessesEnabled = true;
  8236. // Customs render targets
  8237. this.renderTargetsEnabled = true;
  8238. this.dumpNextRenderTargets = false;
  8239. this.customRenderTargets = new Array();
  8240. // Imported meshes
  8241. this.importedMeshesFiles = new Array();
  8242. this._actionManagers = new Array();
  8243. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8244. // Procedural textures
  8245. this.proceduralTexturesEnabled = true;
  8246. this._proceduralTextures = new Array();
  8247. this.soundTracks = new Array();
  8248. this._audioEnabled = true;
  8249. this._headphone = false;
  8250. this._totalVertices = 0;
  8251. this._activeVertices = 0;
  8252. this._activeParticles = 0;
  8253. this._lastFrameDuration = 0;
  8254. this._evaluateActiveMeshesDuration = 0;
  8255. this._renderTargetsDuration = 0;
  8256. this._particlesDuration = 0;
  8257. this._renderDuration = 0;
  8258. this._spritesDuration = 0;
  8259. this._animationRatio = 0;
  8260. this._renderId = 0;
  8261. this._executeWhenReadyTimeoutId = -1;
  8262. this._toBeDisposed = new BABYLON.SmartArray(256);
  8263. this._onReadyCallbacks = new Array();
  8264. this._pendingData = []; //ANY
  8265. this._onBeforeRenderCallbacks = new Array();
  8266. this._onAfterRenderCallbacks = new Array();
  8267. this._activeMeshes = new BABYLON.SmartArray(256);
  8268. this._processedMaterials = new BABYLON.SmartArray(256);
  8269. this._renderTargets = new BABYLON.SmartArray(256);
  8270. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8271. this._activeSkeletons = new BABYLON.SmartArray(32);
  8272. this._activeBones = 0;
  8273. this._activeAnimatables = new Array();
  8274. this._transformMatrix = BABYLON.Matrix.Zero();
  8275. this._scaledPosition = BABYLON.Vector3.Zero();
  8276. this._scaledVelocity = BABYLON.Vector3.Zero();
  8277. this._uniqueIdCounter = 0;
  8278. this._engine = engine;
  8279. engine.scenes.push(this);
  8280. this._renderingManager = new BABYLON.RenderingManager(this);
  8281. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8282. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8283. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8284. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8285. this.attachControl();
  8286. this._debugLayer = new BABYLON.DebugLayer(this);
  8287. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8288. //simplification queue
  8289. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8290. }
  8291. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8292. get: function () {
  8293. return Scene._FOGMODE_NONE;
  8294. },
  8295. enumerable: true,
  8296. configurable: true
  8297. });
  8298. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8299. get: function () {
  8300. return Scene._FOGMODE_EXP;
  8301. },
  8302. enumerable: true,
  8303. configurable: true
  8304. });
  8305. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8306. get: function () {
  8307. return Scene._FOGMODE_EXP2;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8313. get: function () {
  8314. return Scene._FOGMODE_LINEAR;
  8315. },
  8316. enumerable: true,
  8317. configurable: true
  8318. });
  8319. Object.defineProperty(Scene.prototype, "debugLayer", {
  8320. // Properties
  8321. get: function () {
  8322. return this._debugLayer;
  8323. },
  8324. enumerable: true,
  8325. configurable: true
  8326. });
  8327. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8328. /**
  8329. * The mesh that is currently under the pointer.
  8330. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8331. */
  8332. get: function () {
  8333. return this._meshUnderPointer;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Scene.prototype, "pointerX", {
  8339. /**
  8340. * Current on-screen X position of the pointer
  8341. * @return {number} X position of the pointer
  8342. */
  8343. get: function () {
  8344. return this._pointerX;
  8345. },
  8346. enumerable: true,
  8347. configurable: true
  8348. });
  8349. Object.defineProperty(Scene.prototype, "pointerY", {
  8350. /**
  8351. * Current on-screen Y position of the pointer
  8352. * @return {number} Y position of the pointer
  8353. */
  8354. get: function () {
  8355. return this._pointerY;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Scene.prototype.getCachedMaterial = function () {
  8361. return this._cachedMaterial;
  8362. };
  8363. Scene.prototype.getBoundingBoxRenderer = function () {
  8364. return this._boundingBoxRenderer;
  8365. };
  8366. Scene.prototype.getOutlineRenderer = function () {
  8367. return this._outlineRenderer;
  8368. };
  8369. Scene.prototype.getEngine = function () {
  8370. return this._engine;
  8371. };
  8372. Scene.prototype.getTotalVertices = function () {
  8373. return this._totalVertices;
  8374. };
  8375. Scene.prototype.getActiveVertices = function () {
  8376. return this._activeVertices;
  8377. };
  8378. Scene.prototype.getActiveParticles = function () {
  8379. return this._activeParticles;
  8380. };
  8381. Scene.prototype.getActiveBones = function () {
  8382. return this._activeBones;
  8383. };
  8384. // Stats
  8385. Scene.prototype.getLastFrameDuration = function () {
  8386. return this._lastFrameDuration;
  8387. };
  8388. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8389. return this._evaluateActiveMeshesDuration;
  8390. };
  8391. Scene.prototype.getActiveMeshes = function () {
  8392. return this._activeMeshes;
  8393. };
  8394. Scene.prototype.getRenderTargetsDuration = function () {
  8395. return this._renderTargetsDuration;
  8396. };
  8397. Scene.prototype.getRenderDuration = function () {
  8398. return this._renderDuration;
  8399. };
  8400. Scene.prototype.getParticlesDuration = function () {
  8401. return this._particlesDuration;
  8402. };
  8403. Scene.prototype.getSpritesDuration = function () {
  8404. return this._spritesDuration;
  8405. };
  8406. Scene.prototype.getAnimationRatio = function () {
  8407. return this._animationRatio;
  8408. };
  8409. Scene.prototype.getRenderId = function () {
  8410. return this._renderId;
  8411. };
  8412. Scene.prototype.incrementRenderId = function () {
  8413. this._renderId++;
  8414. };
  8415. Scene.prototype._updatePointerPosition = function (evt) {
  8416. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8417. this._pointerX = evt.clientX - canvasRect.left;
  8418. this._pointerY = evt.clientY - canvasRect.top;
  8419. if (this.cameraToUseForPointers) {
  8420. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8421. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8422. }
  8423. };
  8424. // Pointers handling
  8425. Scene.prototype.attachControl = function () {
  8426. var _this = this;
  8427. this._onPointerMove = function (evt) {
  8428. var canvas = _this._engine.getRenderingCanvas();
  8429. _this._updatePointerPosition(evt);
  8430. 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);
  8431. if (pickResult.hit) {
  8432. _this._meshUnderPointer = pickResult.pickedMesh;
  8433. _this.setPointerOverMesh(pickResult.pickedMesh);
  8434. canvas.style.cursor = "pointer";
  8435. }
  8436. else {
  8437. _this.setPointerOverMesh(null);
  8438. canvas.style.cursor = "";
  8439. _this._meshUnderPointer = null;
  8440. }
  8441. };
  8442. this._onPointerDown = function (evt) {
  8443. var predicate = null;
  8444. if (!_this.onPointerDown) {
  8445. predicate = function (mesh) {
  8446. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8447. };
  8448. }
  8449. _this._updatePointerPosition(evt);
  8450. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8451. if (pickResult.hit) {
  8452. if (pickResult.pickedMesh.actionManager) {
  8453. switch (evt.button) {
  8454. case 0:
  8455. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8456. break;
  8457. case 1:
  8458. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8459. break;
  8460. case 2:
  8461. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8462. break;
  8463. }
  8464. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8465. }
  8466. }
  8467. if (_this.onPointerDown) {
  8468. _this.onPointerDown(evt, pickResult);
  8469. }
  8470. };
  8471. this._onKeyDown = function (evt) {
  8472. if (_this.actionManager) {
  8473. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8474. }
  8475. };
  8476. this._onKeyUp = function (evt) {
  8477. if (_this.actionManager) {
  8478. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8479. }
  8480. };
  8481. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8482. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8483. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8484. BABYLON.Tools.RegisterTopRootEvents([
  8485. { name: "keydown", handler: this._onKeyDown },
  8486. { name: "keyup", handler: this._onKeyUp }
  8487. ]);
  8488. };
  8489. Scene.prototype.detachControl = function () {
  8490. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8491. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8492. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8493. BABYLON.Tools.UnregisterTopRootEvents([
  8494. { name: "keydown", handler: this._onKeyDown },
  8495. { name: "keyup", handler: this._onKeyUp }
  8496. ]);
  8497. };
  8498. // Ready
  8499. Scene.prototype.isReady = function () {
  8500. if (this._pendingData.length > 0) {
  8501. return false;
  8502. }
  8503. for (var index = 0; index < this._geometries.length; index++) {
  8504. var geometry = this._geometries[index];
  8505. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8506. return false;
  8507. }
  8508. }
  8509. for (index = 0; index < this.meshes.length; index++) {
  8510. var mesh = this.meshes[index];
  8511. if (!mesh.isReady()) {
  8512. return false;
  8513. }
  8514. var mat = mesh.material;
  8515. if (mat) {
  8516. if (!mat.isReady(mesh)) {
  8517. return false;
  8518. }
  8519. }
  8520. }
  8521. return true;
  8522. };
  8523. Scene.prototype.resetCachedMaterial = function () {
  8524. this._cachedMaterial = null;
  8525. };
  8526. Scene.prototype.registerBeforeRender = function (func) {
  8527. this._onBeforeRenderCallbacks.push(func);
  8528. };
  8529. Scene.prototype.unregisterBeforeRender = function (func) {
  8530. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8531. if (index > -1) {
  8532. this._onBeforeRenderCallbacks.splice(index, 1);
  8533. }
  8534. };
  8535. Scene.prototype.registerAfterRender = function (func) {
  8536. this._onAfterRenderCallbacks.push(func);
  8537. };
  8538. Scene.prototype.unregisterAfterRender = function (func) {
  8539. var index = this._onAfterRenderCallbacks.indexOf(func);
  8540. if (index > -1) {
  8541. this._onAfterRenderCallbacks.splice(index, 1);
  8542. }
  8543. };
  8544. Scene.prototype._addPendingData = function (data) {
  8545. this._pendingData.push(data);
  8546. };
  8547. Scene.prototype._removePendingData = function (data) {
  8548. var index = this._pendingData.indexOf(data);
  8549. if (index !== -1) {
  8550. this._pendingData.splice(index, 1);
  8551. }
  8552. };
  8553. Scene.prototype.getWaitingItemsCount = function () {
  8554. return this._pendingData.length;
  8555. };
  8556. /**
  8557. * Registers a function to be executed when the scene is ready.
  8558. * @param {Function} func - the function to be executed.
  8559. */
  8560. Scene.prototype.executeWhenReady = function (func) {
  8561. var _this = this;
  8562. this._onReadyCallbacks.push(func);
  8563. if (this._executeWhenReadyTimeoutId !== -1) {
  8564. return;
  8565. }
  8566. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8567. _this._checkIsReady();
  8568. }, 150);
  8569. };
  8570. Scene.prototype._checkIsReady = function () {
  8571. var _this = this;
  8572. if (this.isReady()) {
  8573. this._onReadyCallbacks.forEach(function (func) {
  8574. func();
  8575. });
  8576. this._onReadyCallbacks = [];
  8577. this._executeWhenReadyTimeoutId = -1;
  8578. return;
  8579. }
  8580. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8581. _this._checkIsReady();
  8582. }, 150);
  8583. };
  8584. // Animations
  8585. /**
  8586. * Will start the animation sequence of a given target
  8587. * @param target - the target
  8588. * @param {number} from - from which frame should animation start
  8589. * @param {number} to - till which frame should animation run.
  8590. * @param {boolean} [loop] - should the animation loop
  8591. * @param {number} [speedRatio] - the speed in which to run the animation
  8592. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8593. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8594. * @return {BABYLON.Animatable} the animatable object created for this animation
  8595. * @see BABYLON.Animatable
  8596. * @see http://doc.babylonjs.com/page.php?p=22081
  8597. */
  8598. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8599. if (speedRatio === undefined) {
  8600. speedRatio = 1.0;
  8601. }
  8602. this.stopAnimation(target);
  8603. if (!animatable) {
  8604. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8605. }
  8606. // Local animations
  8607. if (target.animations) {
  8608. animatable.appendAnimations(target, target.animations);
  8609. }
  8610. // Children animations
  8611. if (target.getAnimatables) {
  8612. var animatables = target.getAnimatables();
  8613. for (var index = 0; index < animatables.length; index++) {
  8614. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8615. }
  8616. }
  8617. return animatable;
  8618. };
  8619. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8620. if (speedRatio === undefined) {
  8621. speedRatio = 1.0;
  8622. }
  8623. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8624. return animatable;
  8625. };
  8626. Scene.prototype.getAnimatableByTarget = function (target) {
  8627. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8628. if (this._activeAnimatables[index].target === target) {
  8629. return this._activeAnimatables[index];
  8630. }
  8631. }
  8632. return null;
  8633. };
  8634. /**
  8635. * Will stop the animation of the given target
  8636. * @param target - the target
  8637. * @see beginAnimation
  8638. */
  8639. Scene.prototype.stopAnimation = function (target) {
  8640. var animatable = this.getAnimatableByTarget(target);
  8641. if (animatable) {
  8642. animatable.stop();
  8643. }
  8644. };
  8645. Scene.prototype._animate = function () {
  8646. if (!this.animationsEnabled) {
  8647. return;
  8648. }
  8649. if (!this._animationStartDate) {
  8650. this._animationStartDate = BABYLON.Tools.Now;
  8651. }
  8652. // Getting time
  8653. var now = BABYLON.Tools.Now;
  8654. var delay = now - this._animationStartDate;
  8655. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8656. this._activeAnimatables[index]._animate(delay);
  8657. }
  8658. };
  8659. // Matrix
  8660. Scene.prototype.getViewMatrix = function () {
  8661. return this._viewMatrix;
  8662. };
  8663. Scene.prototype.getProjectionMatrix = function () {
  8664. return this._projectionMatrix;
  8665. };
  8666. Scene.prototype.getTransformMatrix = function () {
  8667. return this._transformMatrix;
  8668. };
  8669. Scene.prototype.setTransformMatrix = function (view, projection) {
  8670. this._viewMatrix = view;
  8671. this._projectionMatrix = projection;
  8672. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8673. };
  8674. // Methods
  8675. Scene.prototype.addMesh = function (newMesh) {
  8676. newMesh.uniqueId = this._uniqueIdCounter++;
  8677. var position = this.meshes.push(newMesh);
  8678. if (this.onNewMeshAdded) {
  8679. this.onNewMeshAdded(newMesh, position, this);
  8680. }
  8681. };
  8682. Scene.prototype.removeMesh = function (toRemove) {
  8683. var index = this.meshes.indexOf(toRemove);
  8684. if (index !== -1) {
  8685. // Remove from the scene if mesh found
  8686. this.meshes.splice(index, 1);
  8687. }
  8688. if (this.onMeshRemoved) {
  8689. this.onMeshRemoved(toRemove);
  8690. }
  8691. return index;
  8692. };
  8693. Scene.prototype.removeLight = function (toRemove) {
  8694. var index = this.lights.indexOf(toRemove);
  8695. if (index !== -1) {
  8696. // Remove from the scene if mesh found
  8697. this.lights.splice(index, 1);
  8698. }
  8699. if (this.onLightRemoved) {
  8700. this.onLightRemoved(toRemove);
  8701. }
  8702. return index;
  8703. };
  8704. Scene.prototype.removeCamera = function (toRemove) {
  8705. var index = this.cameras.indexOf(toRemove);
  8706. if (index !== -1) {
  8707. // Remove from the scene if mesh found
  8708. this.cameras.splice(index, 1);
  8709. }
  8710. if (this.onCameraRemoved) {
  8711. this.onCameraRemoved(toRemove);
  8712. }
  8713. return index;
  8714. };
  8715. Scene.prototype.addLight = function (newLight) {
  8716. newLight.uniqueId = this._uniqueIdCounter++;
  8717. var position = this.lights.push(newLight);
  8718. if (this.onNewLightAdded) {
  8719. this.onNewLightAdded(newLight, position, this);
  8720. }
  8721. };
  8722. Scene.prototype.addCamera = function (newCamera) {
  8723. newCamera.uniqueId = this._uniqueIdCounter++;
  8724. var position = this.cameras.push(newCamera);
  8725. if (this.onNewCameraAdded) {
  8726. this.onNewCameraAdded(newCamera, position, this);
  8727. }
  8728. };
  8729. /**
  8730. * sets the active camera of the scene using its ID
  8731. * @param {string} id - the camera's ID
  8732. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8733. * @see activeCamera
  8734. */
  8735. Scene.prototype.setActiveCameraByID = function (id) {
  8736. var camera = this.getCameraByID(id);
  8737. if (camera) {
  8738. this.activeCamera = camera;
  8739. return camera;
  8740. }
  8741. return null;
  8742. };
  8743. /**
  8744. * sets the active camera of the scene using its name
  8745. * @param {string} name - the camera's name
  8746. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8747. * @see activeCamera
  8748. */
  8749. Scene.prototype.setActiveCameraByName = function (name) {
  8750. var camera = this.getCameraByName(name);
  8751. if (camera) {
  8752. this.activeCamera = camera;
  8753. return camera;
  8754. }
  8755. return null;
  8756. };
  8757. /**
  8758. * get a material using its id
  8759. * @param {string} the material's ID
  8760. * @return {BABYLON.Material|null} the material or null if none found.
  8761. */
  8762. Scene.prototype.getMaterialByID = function (id) {
  8763. for (var index = 0; index < this.materials.length; index++) {
  8764. if (this.materials[index].id === id) {
  8765. return this.materials[index];
  8766. }
  8767. }
  8768. return null;
  8769. };
  8770. /**
  8771. * get a material using its name
  8772. * @param {string} the material's name
  8773. * @return {BABYLON.Material|null} the material or null if none found.
  8774. */
  8775. Scene.prototype.getMaterialByName = function (name) {
  8776. for (var index = 0; index < this.materials.length; index++) {
  8777. if (this.materials[index].name === name) {
  8778. return this.materials[index];
  8779. }
  8780. }
  8781. return null;
  8782. };
  8783. Scene.prototype.getCameraByID = function (id) {
  8784. for (var index = 0; index < this.cameras.length; index++) {
  8785. if (this.cameras[index].id === id) {
  8786. return this.cameras[index];
  8787. }
  8788. }
  8789. return null;
  8790. };
  8791. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  8792. for (var index = 0; index < this.cameras.length; index++) {
  8793. if (this.cameras[index].uniqueId === uniqueId) {
  8794. return this.cameras[index];
  8795. }
  8796. }
  8797. return null;
  8798. };
  8799. /**
  8800. * get a camera using its name
  8801. * @param {string} the camera's name
  8802. * @return {BABYLON.Camera|null} the camera or null if none found.
  8803. */
  8804. Scene.prototype.getCameraByName = function (name) {
  8805. for (var index = 0; index < this.cameras.length; index++) {
  8806. if (this.cameras[index].name === name) {
  8807. return this.cameras[index];
  8808. }
  8809. }
  8810. return null;
  8811. };
  8812. /**
  8813. * get a light node using its name
  8814. * @param {string} the light's name
  8815. * @return {BABYLON.Light|null} the light or null if none found.
  8816. */
  8817. Scene.prototype.getLightByName = function (name) {
  8818. for (var index = 0; index < this.lights.length; index++) {
  8819. if (this.lights[index].name === name) {
  8820. return this.lights[index];
  8821. }
  8822. }
  8823. return null;
  8824. };
  8825. /**
  8826. * get a light node using its ID
  8827. * @param {string} the light's id
  8828. * @return {BABYLON.Light|null} the light or null if none found.
  8829. */
  8830. Scene.prototype.getLightByID = function (id) {
  8831. for (var index = 0; index < this.lights.length; index++) {
  8832. if (this.lights[index].id === id) {
  8833. return this.lights[index];
  8834. }
  8835. }
  8836. return null;
  8837. };
  8838. /**
  8839. * get a light node using its scene-generated unique ID
  8840. * @param {number} the light's unique id
  8841. * @return {BABYLON.Light|null} the light or null if none found.
  8842. */
  8843. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  8844. for (var index = 0; index < this.lights.length; index++) {
  8845. if (this.lights[index].uniqueId === uniqueId) {
  8846. return this.lights[index];
  8847. }
  8848. }
  8849. return null;
  8850. };
  8851. /**
  8852. * get a geometry using its ID
  8853. * @param {string} the geometry's id
  8854. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8855. */
  8856. Scene.prototype.getGeometryByID = function (id) {
  8857. for (var index = 0; index < this._geometries.length; index++) {
  8858. if (this._geometries[index].id === id) {
  8859. return this._geometries[index];
  8860. }
  8861. }
  8862. return null;
  8863. };
  8864. /**
  8865. * add a new geometry to this scene.
  8866. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8867. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8868. * @return {boolean} was the geometry added or not
  8869. */
  8870. Scene.prototype.pushGeometry = function (geometry, force) {
  8871. if (!force && this.getGeometryByID(geometry.id)) {
  8872. return false;
  8873. }
  8874. this._geometries.push(geometry);
  8875. return true;
  8876. };
  8877. Scene.prototype.getGeometries = function () {
  8878. return this._geometries;
  8879. };
  8880. /**
  8881. * Get the first added mesh found of a given ID
  8882. * @param {string} id - the id to search for
  8883. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8884. */
  8885. Scene.prototype.getMeshByID = function (id) {
  8886. for (var index = 0; index < this.meshes.length; index++) {
  8887. if (this.meshes[index].id === id) {
  8888. return this.meshes[index];
  8889. }
  8890. }
  8891. return null;
  8892. };
  8893. /**
  8894. * Get a mesh with its auto-generated unique id
  8895. * @param {number} uniqueId - the unique id to search for
  8896. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8897. */
  8898. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  8899. for (var index = 0; index < this.meshes.length; index++) {
  8900. if (this.meshes[index].uniqueId === uniqueId) {
  8901. return this.meshes[index];
  8902. }
  8903. }
  8904. return null;
  8905. };
  8906. /**
  8907. * Get a the last added mesh found of a given ID
  8908. * @param {string} id - the id to search for
  8909. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8910. */
  8911. Scene.prototype.getLastMeshByID = function (id) {
  8912. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8913. if (this.meshes[index].id === id) {
  8914. return this.meshes[index];
  8915. }
  8916. }
  8917. return null;
  8918. };
  8919. /**
  8920. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8921. * @param {string} id - the id to search for
  8922. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8923. */
  8924. Scene.prototype.getLastEntryByID = function (id) {
  8925. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8926. if (this.meshes[index].id === id) {
  8927. return this.meshes[index];
  8928. }
  8929. }
  8930. for (index = this.cameras.length - 1; index >= 0; index--) {
  8931. if (this.cameras[index].id === id) {
  8932. return this.cameras[index];
  8933. }
  8934. }
  8935. for (index = this.lights.length - 1; index >= 0; index--) {
  8936. if (this.lights[index].id === id) {
  8937. return this.lights[index];
  8938. }
  8939. }
  8940. return null;
  8941. };
  8942. Scene.prototype.getNodeByName = function (name) {
  8943. var mesh = this.getMeshByName(name);
  8944. if (mesh) {
  8945. return mesh;
  8946. }
  8947. var light = this.getLightByName(name);
  8948. if (light) {
  8949. return light;
  8950. }
  8951. return this.getCameraByName(name);
  8952. };
  8953. Scene.prototype.getMeshByName = function (name) {
  8954. for (var index = 0; index < this.meshes.length; index++) {
  8955. if (this.meshes[index].name === name) {
  8956. return this.meshes[index];
  8957. }
  8958. }
  8959. return null;
  8960. };
  8961. Scene.prototype.getSoundByName = function (name) {
  8962. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8963. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8964. return this.mainSoundTrack.soundCollection[index];
  8965. }
  8966. }
  8967. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8968. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8969. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8970. return this.soundTracks[sdIndex].soundCollection[index];
  8971. }
  8972. }
  8973. }
  8974. return null;
  8975. };
  8976. Scene.prototype.getLastSkeletonByID = function (id) {
  8977. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8978. if (this.skeletons[index].id === id) {
  8979. return this.skeletons[index];
  8980. }
  8981. }
  8982. return null;
  8983. };
  8984. Scene.prototype.getSkeletonById = function (id) {
  8985. for (var index = 0; index < this.skeletons.length; index++) {
  8986. if (this.skeletons[index].id === id) {
  8987. return this.skeletons[index];
  8988. }
  8989. }
  8990. return null;
  8991. };
  8992. Scene.prototype.getSkeletonByName = function (name) {
  8993. for (var index = 0; index < this.skeletons.length; index++) {
  8994. if (this.skeletons[index].name === name) {
  8995. return this.skeletons[index];
  8996. }
  8997. }
  8998. return null;
  8999. };
  9000. Scene.prototype.isActiveMesh = function (mesh) {
  9001. return (this._activeMeshes.indexOf(mesh) !== -1);
  9002. };
  9003. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  9004. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  9005. var material = subMesh.getMaterial();
  9006. if (mesh.showSubMeshesBoundingBox) {
  9007. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  9008. }
  9009. if (material) {
  9010. // Render targets
  9011. if (material.getRenderTargetTextures) {
  9012. if (this._processedMaterials.indexOf(material) === -1) {
  9013. this._processedMaterials.push(material);
  9014. this._renderTargets.concat(material.getRenderTargetTextures());
  9015. }
  9016. }
  9017. // Dispatch
  9018. this._activeVertices += subMesh.indexCount;
  9019. this._renderingManager.dispatch(subMesh);
  9020. }
  9021. }
  9022. };
  9023. Scene.prototype._evaluateActiveMeshes = function () {
  9024. this.activeCamera._activeMeshes.reset();
  9025. this._activeMeshes.reset();
  9026. this._renderingManager.reset();
  9027. this._processedMaterials.reset();
  9028. this._activeParticleSystems.reset();
  9029. this._activeSkeletons.reset();
  9030. this._boundingBoxRenderer.reset();
  9031. if (!this._frustumPlanes) {
  9032. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  9033. }
  9034. else {
  9035. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  9036. }
  9037. // Meshes
  9038. var meshes;
  9039. var len;
  9040. if (this._selectionOctree) {
  9041. var selection = this._selectionOctree.select(this._frustumPlanes);
  9042. meshes = selection.data;
  9043. len = selection.length;
  9044. }
  9045. else {
  9046. len = this.meshes.length;
  9047. meshes = this.meshes;
  9048. }
  9049. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  9050. var mesh = meshes[meshIndex];
  9051. if (mesh.isBlocked) {
  9052. continue;
  9053. }
  9054. this._totalVertices += mesh.getTotalVertices();
  9055. if (!mesh.isReady()) {
  9056. continue;
  9057. }
  9058. mesh.computeWorldMatrix();
  9059. // Intersections
  9060. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  9061. this._meshesForIntersections.pushNoDuplicate(mesh);
  9062. }
  9063. // Switch to current LOD
  9064. var meshLOD = mesh.getLOD(this.activeCamera);
  9065. if (!meshLOD) {
  9066. continue;
  9067. }
  9068. mesh._preActivate();
  9069. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  9070. this._activeMeshes.push(mesh);
  9071. this.activeCamera._activeMeshes.push(mesh);
  9072. mesh._activate(this._renderId);
  9073. this._activeMesh(meshLOD);
  9074. }
  9075. }
  9076. // Particle systems
  9077. var beforeParticlesDate = BABYLON.Tools.Now;
  9078. if (this.particlesEnabled) {
  9079. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  9080. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  9081. var particleSystem = this.particleSystems[particleIndex];
  9082. if (!particleSystem.isStarted()) {
  9083. continue;
  9084. }
  9085. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  9086. this._activeParticleSystems.push(particleSystem);
  9087. particleSystem.animate();
  9088. }
  9089. }
  9090. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  9091. }
  9092. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9093. };
  9094. Scene.prototype._activeMesh = function (mesh) {
  9095. if (mesh.skeleton && this.skeletonsEnabled) {
  9096. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  9097. }
  9098. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  9099. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  9100. }
  9101. if (mesh && mesh.subMeshes) {
  9102. // Submeshes Octrees
  9103. var len;
  9104. var subMeshes;
  9105. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  9106. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  9107. len = intersections.length;
  9108. subMeshes = intersections.data;
  9109. }
  9110. else {
  9111. subMeshes = mesh.subMeshes;
  9112. len = subMeshes.length;
  9113. }
  9114. for (var subIndex = 0; subIndex < len; subIndex++) {
  9115. var subMesh = subMeshes[subIndex];
  9116. this._evaluateSubMesh(subMesh, mesh);
  9117. }
  9118. }
  9119. };
  9120. Scene.prototype.updateTransformMatrix = function (force) {
  9121. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9122. };
  9123. Scene.prototype._renderForCamera = function (camera) {
  9124. var engine = this._engine;
  9125. this.activeCamera = camera;
  9126. if (!this.activeCamera)
  9127. throw new Error("Active camera not set");
  9128. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9129. // Viewport
  9130. engine.setViewport(this.activeCamera.viewport);
  9131. // Camera
  9132. this._renderId++;
  9133. this.updateTransformMatrix();
  9134. if (this.beforeCameraRender) {
  9135. this.beforeCameraRender(this.activeCamera);
  9136. }
  9137. // Meshes
  9138. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9139. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9140. this._evaluateActiveMeshes();
  9141. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9142. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9143. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9144. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9145. skeleton.prepare();
  9146. }
  9147. // Render targets
  9148. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9149. if (this.renderTargetsEnabled) {
  9150. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9151. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9152. var renderTarget = this._renderTargets.data[renderIndex];
  9153. if (renderTarget._shouldRender()) {
  9154. this._renderId++;
  9155. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9156. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9157. }
  9158. }
  9159. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9160. this._renderId++;
  9161. }
  9162. if (this._renderTargets.length > 0) {
  9163. engine.restoreDefaultFramebuffer();
  9164. }
  9165. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9166. // Prepare Frame
  9167. this.postProcessManager._prepareFrame();
  9168. var beforeRenderDate = BABYLON.Tools.Now;
  9169. // Backgrounds
  9170. if (this.layers.length) {
  9171. engine.setDepthBuffer(false);
  9172. var layerIndex;
  9173. var layer;
  9174. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9175. layer = this.layers[layerIndex];
  9176. if (layer.isBackground) {
  9177. layer.render();
  9178. }
  9179. }
  9180. engine.setDepthBuffer(true);
  9181. }
  9182. // Render
  9183. BABYLON.Tools.StartPerformanceCounter("Main render");
  9184. this._renderingManager.render(null, null, true, true);
  9185. BABYLON.Tools.EndPerformanceCounter("Main render");
  9186. // Bounding boxes
  9187. this._boundingBoxRenderer.render();
  9188. // Lens flares
  9189. if (this.lensFlaresEnabled) {
  9190. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9191. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9192. this.lensFlareSystems[lensFlareSystemIndex].render();
  9193. }
  9194. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9195. }
  9196. // Foregrounds
  9197. if (this.layers.length) {
  9198. engine.setDepthBuffer(false);
  9199. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9200. layer = this.layers[layerIndex];
  9201. if (!layer.isBackground) {
  9202. layer.render();
  9203. }
  9204. }
  9205. engine.setDepthBuffer(true);
  9206. }
  9207. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9208. // Finalize frame
  9209. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9210. // Update camera
  9211. this.activeCamera._updateFromScene();
  9212. // Reset some special arrays
  9213. this._renderTargets.reset();
  9214. if (this.afterCameraRender) {
  9215. this.afterCameraRender(this.activeCamera);
  9216. }
  9217. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9218. };
  9219. Scene.prototype._processSubCameras = function (camera) {
  9220. if (camera.subCameras.length === 0) {
  9221. this._renderForCamera(camera);
  9222. return;
  9223. }
  9224. for (var index = 0; index < camera.subCameras.length; index++) {
  9225. this._renderForCamera(camera.subCameras[index]);
  9226. }
  9227. this.activeCamera = camera;
  9228. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9229. // Update camera
  9230. this.activeCamera._updateFromScene();
  9231. };
  9232. Scene.prototype._checkIntersections = function () {
  9233. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9234. var sourceMesh = this._meshesForIntersections.data[index];
  9235. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9236. var action = sourceMesh.actionManager.actions[actionIndex];
  9237. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9238. var parameters = action.getTriggerParameter();
  9239. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9240. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9241. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9242. if (areIntersecting && currentIntersectionInProgress === -1) {
  9243. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9244. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9245. sourceMesh._intersectionsInProgress.push(otherMesh);
  9246. }
  9247. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9248. sourceMesh._intersectionsInProgress.push(otherMesh);
  9249. }
  9250. }
  9251. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9252. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9253. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9254. if (indexOfOther > -1) {
  9255. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9256. }
  9257. }
  9258. }
  9259. }
  9260. }
  9261. };
  9262. Scene.prototype.render = function () {
  9263. var startDate = BABYLON.Tools.Now;
  9264. this._particlesDuration = 0;
  9265. this._spritesDuration = 0;
  9266. this._activeParticles = 0;
  9267. this._renderDuration = 0;
  9268. this._renderTargetsDuration = 0;
  9269. this._evaluateActiveMeshesDuration = 0;
  9270. this._totalVertices = 0;
  9271. this._activeVertices = 0;
  9272. this._activeBones = 0;
  9273. this.getEngine().resetDrawCalls();
  9274. this._meshesForIntersections.reset();
  9275. this.resetCachedMaterial();
  9276. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9277. // Actions
  9278. if (this.actionManager) {
  9279. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9280. }
  9281. //Simplification Queue
  9282. if (!this.simplificationQueue.running) {
  9283. this.simplificationQueue.executeNext();
  9284. }
  9285. // Before render
  9286. if (this.beforeRender) {
  9287. this.beforeRender();
  9288. }
  9289. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9290. this._onBeforeRenderCallbacks[callbackIndex]();
  9291. }
  9292. // Animations
  9293. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9294. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9295. this._animate();
  9296. // Physics
  9297. if (this._physicsEngine) {
  9298. BABYLON.Tools.StartPerformanceCounter("Physics");
  9299. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9300. BABYLON.Tools.EndPerformanceCounter("Physics");
  9301. }
  9302. // Customs render targets
  9303. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9304. var engine = this.getEngine();
  9305. var currentActiveCamera = this.activeCamera;
  9306. if (this.renderTargetsEnabled) {
  9307. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9308. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9309. var renderTarget = this.customRenderTargets[customIndex];
  9310. if (renderTarget._shouldRender()) {
  9311. this._renderId++;
  9312. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9313. if (!this.activeCamera)
  9314. throw new Error("Active camera not set");
  9315. // Viewport
  9316. engine.setViewport(this.activeCamera.viewport);
  9317. // Camera
  9318. this.updateTransformMatrix();
  9319. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9320. }
  9321. }
  9322. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9323. this._renderId++;
  9324. }
  9325. if (this.customRenderTargets.length > 0) {
  9326. engine.restoreDefaultFramebuffer();
  9327. }
  9328. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9329. this.activeCamera = currentActiveCamera;
  9330. // Procedural textures
  9331. if (this.proceduralTexturesEnabled) {
  9332. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9333. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9334. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9335. if (proceduralTexture._shouldRender()) {
  9336. proceduralTexture.render();
  9337. }
  9338. }
  9339. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9340. }
  9341. // Clear
  9342. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9343. // Shadows
  9344. if (this.shadowsEnabled) {
  9345. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9346. var light = this.lights[lightIndex];
  9347. var shadowGenerator = light.getShadowGenerator();
  9348. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9349. this._renderTargets.push(shadowGenerator.getShadowMap());
  9350. }
  9351. }
  9352. }
  9353. // Depth renderer
  9354. if (this._depthRenderer) {
  9355. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9356. }
  9357. // RenderPipeline
  9358. this.postProcessRenderPipelineManager.update();
  9359. // Multi-cameras?
  9360. if (this.activeCameras.length > 0) {
  9361. var currentRenderId = this._renderId;
  9362. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9363. this._renderId = currentRenderId;
  9364. this._processSubCameras(this.activeCameras[cameraIndex]);
  9365. }
  9366. }
  9367. else {
  9368. if (!this.activeCamera) {
  9369. throw new Error("No camera defined");
  9370. }
  9371. this._processSubCameras(this.activeCamera);
  9372. }
  9373. // Intersection checks
  9374. this._checkIntersections();
  9375. // Update the audio listener attached to the camera
  9376. this._updateAudioParameters();
  9377. // After render
  9378. if (this.afterRender) {
  9379. this.afterRender();
  9380. }
  9381. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9382. this._onAfterRenderCallbacks[callbackIndex]();
  9383. }
  9384. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9385. this._toBeDisposed.data[index].dispose();
  9386. this._toBeDisposed[index] = null;
  9387. }
  9388. this._toBeDisposed.reset();
  9389. if (this.dumpNextRenderTargets) {
  9390. this.dumpNextRenderTargets = false;
  9391. }
  9392. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9393. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9394. };
  9395. Scene.prototype._updateAudioParameters = function () {
  9396. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9397. return;
  9398. }
  9399. var listeningCamera;
  9400. var audioEngine = BABYLON.Engine.audioEngine;
  9401. if (this.activeCameras.length > 0) {
  9402. listeningCamera = this.activeCameras[0];
  9403. }
  9404. else {
  9405. listeningCamera = this.activeCamera;
  9406. }
  9407. if (listeningCamera && audioEngine.canUseWebAudio) {
  9408. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9409. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9410. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9411. cameraDirection.normalize();
  9412. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9413. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9414. var sound = this.mainSoundTrack.soundCollection[i];
  9415. if (sound.useCustomAttenuation) {
  9416. sound.updateDistanceFromListener();
  9417. }
  9418. }
  9419. for (i = 0; i < this.soundTracks.length; i++) {
  9420. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9421. sound = this.soundTracks[i].soundCollection[j];
  9422. if (sound.useCustomAttenuation) {
  9423. sound.updateDistanceFromListener();
  9424. }
  9425. }
  9426. }
  9427. }
  9428. };
  9429. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9430. // Audio
  9431. get: function () {
  9432. return this._audioEnabled;
  9433. },
  9434. set: function (value) {
  9435. this._audioEnabled = value;
  9436. if (this._audioEnabled) {
  9437. this._enableAudio();
  9438. }
  9439. else {
  9440. this._disableAudio();
  9441. }
  9442. },
  9443. enumerable: true,
  9444. configurable: true
  9445. });
  9446. Scene.prototype._disableAudio = function () {
  9447. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9448. this.mainSoundTrack.soundCollection[i].pause();
  9449. }
  9450. for (i = 0; i < this.soundTracks.length; i++) {
  9451. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9452. this.soundTracks[i].soundCollection[j].pause();
  9453. }
  9454. }
  9455. };
  9456. Scene.prototype._enableAudio = function () {
  9457. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9458. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9459. this.mainSoundTrack.soundCollection[i].play();
  9460. }
  9461. }
  9462. for (i = 0; i < this.soundTracks.length; i++) {
  9463. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9464. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9465. this.soundTracks[i].soundCollection[j].play();
  9466. }
  9467. }
  9468. }
  9469. };
  9470. Object.defineProperty(Scene.prototype, "headphone", {
  9471. get: function () {
  9472. return this._headphone;
  9473. },
  9474. set: function (value) {
  9475. this._headphone = value;
  9476. if (this._headphone) {
  9477. this._switchAudioModeForHeadphones();
  9478. }
  9479. else {
  9480. this._switchAudioModeForNormalSpeakers();
  9481. }
  9482. },
  9483. enumerable: true,
  9484. configurable: true
  9485. });
  9486. Scene.prototype._switchAudioModeForHeadphones = function () {
  9487. this.mainSoundTrack.switchPanningModelToHRTF();
  9488. for (var i = 0; i < this.soundTracks.length; i++) {
  9489. this.soundTracks[i].switchPanningModelToHRTF();
  9490. }
  9491. };
  9492. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9493. this.mainSoundTrack.switchPanningModelToEqualPower();
  9494. for (var i = 0; i < this.soundTracks.length; i++) {
  9495. this.soundTracks[i].switchPanningModelToEqualPower();
  9496. }
  9497. };
  9498. Scene.prototype.enableDepthRenderer = function () {
  9499. if (this._depthRenderer) {
  9500. return this._depthRenderer;
  9501. }
  9502. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9503. return this._depthRenderer;
  9504. };
  9505. Scene.prototype.disableDepthRenderer = function () {
  9506. if (!this._depthRenderer) {
  9507. return;
  9508. }
  9509. this._depthRenderer.dispose();
  9510. this._depthRenderer = null;
  9511. };
  9512. Scene.prototype.dispose = function () {
  9513. this.beforeRender = null;
  9514. this.afterRender = null;
  9515. this.skeletons = [];
  9516. this._boundingBoxRenderer.dispose();
  9517. if (this._depthRenderer) {
  9518. this._depthRenderer.dispose();
  9519. }
  9520. // Debug layer
  9521. this.debugLayer.hide();
  9522. // Events
  9523. if (this.onDispose) {
  9524. this.onDispose();
  9525. }
  9526. this._onBeforeRenderCallbacks = [];
  9527. this._onAfterRenderCallbacks = [];
  9528. this.detachControl();
  9529. // Release sounds & sounds tracks
  9530. this.disposeSounds();
  9531. // Detach cameras
  9532. var canvas = this._engine.getRenderingCanvas();
  9533. var index;
  9534. for (index = 0; index < this.cameras.length; index++) {
  9535. this.cameras[index].detachControl(canvas);
  9536. }
  9537. while (this.lights.length) {
  9538. this.lights[0].dispose();
  9539. }
  9540. while (this.meshes.length) {
  9541. this.meshes[0].dispose(true);
  9542. }
  9543. while (this.cameras.length) {
  9544. this.cameras[0].dispose();
  9545. }
  9546. while (this.materials.length) {
  9547. this.materials[0].dispose();
  9548. }
  9549. while (this.particleSystems.length) {
  9550. this.particleSystems[0].dispose();
  9551. }
  9552. while (this.spriteManagers.length) {
  9553. this.spriteManagers[0].dispose();
  9554. }
  9555. while (this.layers.length) {
  9556. this.layers[0].dispose();
  9557. }
  9558. while (this.textures.length) {
  9559. this.textures[0].dispose();
  9560. }
  9561. // Post-processes
  9562. this.postProcessManager.dispose();
  9563. // Physics
  9564. if (this._physicsEngine) {
  9565. this.disablePhysicsEngine();
  9566. }
  9567. // Remove from engine
  9568. index = this._engine.scenes.indexOf(this);
  9569. if (index > -1) {
  9570. this._engine.scenes.splice(index, 1);
  9571. }
  9572. this._engine.wipeCaches();
  9573. };
  9574. // Release sounds & sounds tracks
  9575. Scene.prototype.disposeSounds = function () {
  9576. this.mainSoundTrack.dispose();
  9577. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9578. this.soundTracks[scIndex].dispose();
  9579. }
  9580. };
  9581. // Collisions
  9582. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9583. if (excludedMesh === void 0) { excludedMesh = null; }
  9584. position.divideToRef(collider.radius, this._scaledPosition);
  9585. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9586. collider.retry = 0;
  9587. collider.initialVelocity = this._scaledVelocity;
  9588. collider.initialPosition = this._scaledPosition;
  9589. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9590. finalPosition.multiplyInPlace(collider.radius);
  9591. };
  9592. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9593. if (excludedMesh === void 0) { excludedMesh = null; }
  9594. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9595. if (collider.retry >= maximumRetry) {
  9596. finalPosition.copyFrom(position);
  9597. return;
  9598. }
  9599. collider._initialize(position, velocity, closeDistance);
  9600. for (var index = 0; index < this.meshes.length; index++) {
  9601. var mesh = this.meshes[index];
  9602. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9603. mesh._checkCollision(collider);
  9604. }
  9605. }
  9606. if (!collider.collisionFound) {
  9607. position.addToRef(velocity, finalPosition);
  9608. return;
  9609. }
  9610. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9611. collider._getResponse(position, velocity);
  9612. }
  9613. if (velocity.length() <= closeDistance) {
  9614. finalPosition.copyFrom(position);
  9615. return;
  9616. }
  9617. collider.retry++;
  9618. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9619. };
  9620. // Octrees
  9621. Scene.prototype.getWorldExtends = function () {
  9622. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9623. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9624. for (var index = 0; index < this.meshes.length; index++) {
  9625. var mesh = this.meshes[index];
  9626. mesh.computeWorldMatrix(true);
  9627. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9628. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9629. BABYLON.Tools.CheckExtends(minBox, min, max);
  9630. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9631. }
  9632. return {
  9633. min: min,
  9634. max: max
  9635. };
  9636. };
  9637. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9638. if (maxCapacity === void 0) { maxCapacity = 64; }
  9639. if (maxDepth === void 0) { maxDepth = 2; }
  9640. if (!this._selectionOctree) {
  9641. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9642. }
  9643. var worldExtends = this.getWorldExtends();
  9644. // Update octree
  9645. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9646. return this._selectionOctree;
  9647. };
  9648. // Picking
  9649. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9650. var engine = this._engine;
  9651. if (!camera) {
  9652. if (!this.activeCamera)
  9653. throw new Error("Active camera not set");
  9654. camera = this.activeCamera;
  9655. }
  9656. var cameraViewport = camera.viewport;
  9657. var viewport = cameraViewport.toGlobal(engine);
  9658. // Moving coordinates to local viewport world
  9659. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9660. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9661. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9662. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9663. };
  9664. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9665. var pickingInfo = null;
  9666. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9667. var mesh = this.meshes[meshIndex];
  9668. if (predicate) {
  9669. if (!predicate(mesh)) {
  9670. continue;
  9671. }
  9672. }
  9673. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9674. continue;
  9675. }
  9676. var world = mesh.getWorldMatrix();
  9677. var ray = rayFunction(world);
  9678. var result = mesh.intersects(ray, fastCheck);
  9679. if (!result || !result.hit)
  9680. continue;
  9681. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9682. continue;
  9683. pickingInfo = result;
  9684. if (fastCheck) {
  9685. break;
  9686. }
  9687. }
  9688. return pickingInfo || new BABYLON.PickingInfo();
  9689. };
  9690. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9691. var _this = this;
  9692. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9693. /// <param name="x">X position on screen</param>
  9694. /// <param name="y">Y position on screen</param>
  9695. /// <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>
  9696. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9697. /// <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>
  9698. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9699. };
  9700. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9701. var _this = this;
  9702. return this._internalPick(function (world) {
  9703. if (!_this._pickWithRayInverseMatrix) {
  9704. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9705. }
  9706. world.invertToRef(_this._pickWithRayInverseMatrix);
  9707. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9708. }, predicate, fastCheck);
  9709. };
  9710. Scene.prototype.setPointerOverMesh = function (mesh) {
  9711. if (this._pointerOverMesh === mesh) {
  9712. return;
  9713. }
  9714. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9715. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9716. }
  9717. this._pointerOverMesh = mesh;
  9718. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9719. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9720. }
  9721. };
  9722. Scene.prototype.getPointerOverMesh = function () {
  9723. return this._pointerOverMesh;
  9724. };
  9725. // Physics
  9726. Scene.prototype.getPhysicsEngine = function () {
  9727. return this._physicsEngine;
  9728. };
  9729. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9730. if (this._physicsEngine) {
  9731. return true;
  9732. }
  9733. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9734. if (!this._physicsEngine.isSupported()) {
  9735. this._physicsEngine = null;
  9736. return false;
  9737. }
  9738. this._physicsEngine._initialize(gravity);
  9739. return true;
  9740. };
  9741. Scene.prototype.disablePhysicsEngine = function () {
  9742. if (!this._physicsEngine) {
  9743. return;
  9744. }
  9745. this._physicsEngine.dispose();
  9746. this._physicsEngine = undefined;
  9747. };
  9748. Scene.prototype.isPhysicsEnabled = function () {
  9749. return this._physicsEngine !== undefined;
  9750. };
  9751. Scene.prototype.setGravity = function (gravity) {
  9752. if (!this._physicsEngine) {
  9753. return;
  9754. }
  9755. this._physicsEngine._setGravity(gravity);
  9756. };
  9757. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9758. if (parts.parts) {
  9759. options = parts;
  9760. parts = parts.parts;
  9761. }
  9762. if (!this._physicsEngine) {
  9763. return null;
  9764. }
  9765. for (var index = 0; index < parts.length; index++) {
  9766. var mesh = parts[index].mesh;
  9767. mesh._physicImpostor = parts[index].impostor;
  9768. mesh._physicsMass = options.mass / parts.length;
  9769. mesh._physicsFriction = options.friction;
  9770. mesh._physicRestitution = options.restitution;
  9771. }
  9772. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9773. };
  9774. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9775. for (var index = 0; index < compound.parts.length; index++) {
  9776. var mesh = compound.parts[index].mesh;
  9777. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9778. this._physicsEngine._unregisterMesh(mesh);
  9779. }
  9780. };
  9781. // Misc.
  9782. Scene.prototype.createDefaultCameraOrLight = function () {
  9783. // Light
  9784. if (this.lights.length === 0) {
  9785. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9786. }
  9787. // Camera
  9788. if (!this.activeCamera) {
  9789. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9790. // Compute position
  9791. var worldExtends = this.getWorldExtends();
  9792. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9793. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9794. camera.setTarget(worldCenter);
  9795. this.activeCamera = camera;
  9796. }
  9797. };
  9798. // Tags
  9799. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9800. if (tagsQuery === undefined) {
  9801. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9802. return list;
  9803. }
  9804. var listByTags = [];
  9805. forEach = forEach || (function (item) {
  9806. return;
  9807. });
  9808. for (var i in list) {
  9809. var item = list[i];
  9810. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9811. listByTags.push(item);
  9812. forEach(item);
  9813. }
  9814. }
  9815. return listByTags;
  9816. };
  9817. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9818. return this._getByTags(this.meshes, tagsQuery, forEach);
  9819. };
  9820. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9821. return this._getByTags(this.cameras, tagsQuery, forEach);
  9822. };
  9823. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9824. return this._getByTags(this.lights, tagsQuery, forEach);
  9825. };
  9826. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9827. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9828. };
  9829. // Statics
  9830. Scene._FOGMODE_NONE = 0;
  9831. Scene._FOGMODE_EXP = 1;
  9832. Scene._FOGMODE_EXP2 = 2;
  9833. Scene._FOGMODE_LINEAR = 3;
  9834. Scene.MinDeltaTime = 1.0;
  9835. Scene.MaxDeltaTime = 1000.0;
  9836. return Scene;
  9837. })();
  9838. BABYLON.Scene = Scene;
  9839. })(BABYLON || (BABYLON = {}));
  9840. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9841. (function (BABYLON) {
  9842. var VertexBuffer = (function () {
  9843. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9844. if (engine instanceof BABYLON.Mesh) {
  9845. this._engine = engine.getScene().getEngine();
  9846. }
  9847. else {
  9848. this._engine = engine;
  9849. }
  9850. this._updatable = updatable;
  9851. this._data = data;
  9852. if (!postponeInternalCreation) {
  9853. this.create();
  9854. }
  9855. this._kind = kind;
  9856. if (stride) {
  9857. this._strideSize = stride;
  9858. return;
  9859. }
  9860. switch (kind) {
  9861. case VertexBuffer.PositionKind:
  9862. this._strideSize = 3;
  9863. break;
  9864. case VertexBuffer.NormalKind:
  9865. this._strideSize = 3;
  9866. break;
  9867. case VertexBuffer.UVKind:
  9868. this._strideSize = 2;
  9869. break;
  9870. case VertexBuffer.UV2Kind:
  9871. this._strideSize = 2;
  9872. break;
  9873. case VertexBuffer.ColorKind:
  9874. this._strideSize = 4;
  9875. break;
  9876. case VertexBuffer.MatricesIndicesKind:
  9877. this._strideSize = 4;
  9878. break;
  9879. case VertexBuffer.MatricesWeightsKind:
  9880. this._strideSize = 4;
  9881. break;
  9882. }
  9883. }
  9884. // Properties
  9885. VertexBuffer.prototype.isUpdatable = function () {
  9886. return this._updatable;
  9887. };
  9888. VertexBuffer.prototype.getData = function () {
  9889. return this._data;
  9890. };
  9891. VertexBuffer.prototype.getBuffer = function () {
  9892. return this._buffer;
  9893. };
  9894. VertexBuffer.prototype.getStrideSize = function () {
  9895. return this._strideSize;
  9896. };
  9897. // Methods
  9898. VertexBuffer.prototype.create = function (data) {
  9899. if (!data && this._buffer) {
  9900. return; // nothing to do
  9901. }
  9902. data = data || this._data;
  9903. if (!this._buffer) {
  9904. if (this._updatable) {
  9905. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9906. }
  9907. else {
  9908. this._buffer = this._engine.createVertexBuffer(data);
  9909. }
  9910. }
  9911. if (this._updatable) {
  9912. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9913. this._data = data;
  9914. }
  9915. };
  9916. VertexBuffer.prototype.update = function (data) {
  9917. this.create(data);
  9918. };
  9919. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9920. if (!this._buffer) {
  9921. return;
  9922. }
  9923. if (this._updatable) {
  9924. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9925. this._data = null;
  9926. }
  9927. };
  9928. VertexBuffer.prototype.dispose = function () {
  9929. if (!this._buffer) {
  9930. return;
  9931. }
  9932. if (this._engine._releaseBuffer(this._buffer)) {
  9933. this._buffer = null;
  9934. }
  9935. };
  9936. Object.defineProperty(VertexBuffer, "PositionKind", {
  9937. get: function () {
  9938. return VertexBuffer._PositionKind;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(VertexBuffer, "NormalKind", {
  9944. get: function () {
  9945. return VertexBuffer._NormalKind;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(VertexBuffer, "UVKind", {
  9951. get: function () {
  9952. return VertexBuffer._UVKind;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9958. get: function () {
  9959. return VertexBuffer._UV2Kind;
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. Object.defineProperty(VertexBuffer, "ColorKind", {
  9965. get: function () {
  9966. return VertexBuffer._ColorKind;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9972. get: function () {
  9973. return VertexBuffer._MatricesIndicesKind;
  9974. },
  9975. enumerable: true,
  9976. configurable: true
  9977. });
  9978. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9979. get: function () {
  9980. return VertexBuffer._MatricesWeightsKind;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. // Enums
  9986. VertexBuffer._PositionKind = "position";
  9987. VertexBuffer._NormalKind = "normal";
  9988. VertexBuffer._UVKind = "uv";
  9989. VertexBuffer._UV2Kind = "uv2";
  9990. VertexBuffer._ColorKind = "color";
  9991. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9992. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9993. return VertexBuffer;
  9994. })();
  9995. BABYLON.VertexBuffer = VertexBuffer;
  9996. })(BABYLON || (BABYLON = {}));
  9997. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9998. var BABYLON;
  9999. (function (BABYLON) {
  10000. var AbstractMesh = (function (_super) {
  10001. __extends(AbstractMesh, _super);
  10002. function AbstractMesh(name, scene) {
  10003. _super.call(this, name, scene);
  10004. // Properties
  10005. this.definedFacingForward = true; // orientation for POV movement & rotation
  10006. this.position = new BABYLON.Vector3(0, 0, 0);
  10007. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10008. this.scaling = new BABYLON.Vector3(1, 1, 1);
  10009. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10010. this.visibility = 1.0;
  10011. this.alphaIndex = Number.MAX_VALUE;
  10012. this.infiniteDistance = false;
  10013. this.isVisible = true;
  10014. this.isPickable = true;
  10015. this.showBoundingBox = false;
  10016. this.showSubMeshesBoundingBox = false;
  10017. this.onDispose = null;
  10018. this.checkCollisions = false;
  10019. this.isBlocker = false;
  10020. this.renderingGroupId = 0;
  10021. this.receiveShadows = false;
  10022. this.renderOutline = false;
  10023. this.outlineColor = BABYLON.Color3.Red();
  10024. this.outlineWidth = 0.02;
  10025. this.renderOverlay = false;
  10026. this.overlayColor = BABYLON.Color3.Red();
  10027. this.overlayAlpha = 0.5;
  10028. this.hasVertexAlpha = false;
  10029. this.useVertexColors = true;
  10030. this.applyFog = true;
  10031. this.useOctreeForRenderingSelection = true;
  10032. this.useOctreeForPicking = true;
  10033. this.useOctreeForCollisions = true;
  10034. this.layerMask = 0x0FFFFFFF;
  10035. // Physics
  10036. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  10037. // Collisions
  10038. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10039. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10040. this._collider = new BABYLON.Collider();
  10041. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10042. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10043. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10044. // Cache
  10045. this._localScaling = BABYLON.Matrix.Zero();
  10046. this._localRotation = BABYLON.Matrix.Zero();
  10047. this._localTranslation = BABYLON.Matrix.Zero();
  10048. this._localBillboard = BABYLON.Matrix.Zero();
  10049. this._localPivotScaling = BABYLON.Matrix.Zero();
  10050. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  10051. this._localWorld = BABYLON.Matrix.Zero();
  10052. this._worldMatrix = BABYLON.Matrix.Zero();
  10053. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10054. this._absolutePosition = BABYLON.Vector3.Zero();
  10055. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10056. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10057. this._isDirty = false;
  10058. this._pivotMatrix = BABYLON.Matrix.Identity();
  10059. this._isDisposed = false;
  10060. this._renderId = 0;
  10061. this._intersectionsInProgress = new Array();
  10062. this._onAfterWorldMatrixUpdate = new Array();
  10063. scene.addMesh(this);
  10064. }
  10065. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10066. get: function () {
  10067. return AbstractMesh._BILLBOARDMODE_NONE;
  10068. },
  10069. enumerable: true,
  10070. configurable: true
  10071. });
  10072. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10073. get: function () {
  10074. return AbstractMesh._BILLBOARDMODE_X;
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10080. get: function () {
  10081. return AbstractMesh._BILLBOARDMODE_Y;
  10082. },
  10083. enumerable: true,
  10084. configurable: true
  10085. });
  10086. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10087. get: function () {
  10088. return AbstractMesh._BILLBOARDMODE_Z;
  10089. },
  10090. enumerable: true,
  10091. configurable: true
  10092. });
  10093. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10094. get: function () {
  10095. return AbstractMesh._BILLBOARDMODE_ALL;
  10096. },
  10097. enumerable: true,
  10098. configurable: true
  10099. });
  10100. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10101. // Methods
  10102. get: function () {
  10103. return false;
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. AbstractMesh.prototype.getLOD = function (camera) {
  10109. return this;
  10110. };
  10111. AbstractMesh.prototype.getTotalVertices = function () {
  10112. return 0;
  10113. };
  10114. AbstractMesh.prototype.getIndices = function () {
  10115. return null;
  10116. };
  10117. AbstractMesh.prototype.getVerticesData = function (kind) {
  10118. return null;
  10119. };
  10120. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10121. return false;
  10122. };
  10123. AbstractMesh.prototype.getBoundingInfo = function () {
  10124. if (this._masterMesh) {
  10125. return this._masterMesh.getBoundingInfo();
  10126. }
  10127. if (!this._boundingInfo) {
  10128. this._updateBoundingInfo();
  10129. }
  10130. return this._boundingInfo;
  10131. };
  10132. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10133. get: function () {
  10134. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. AbstractMesh.prototype._preActivate = function () {
  10140. };
  10141. AbstractMesh.prototype._activate = function (renderId) {
  10142. this._renderId = renderId;
  10143. };
  10144. AbstractMesh.prototype.getWorldMatrix = function () {
  10145. if (this._masterMesh) {
  10146. return this._masterMesh.getWorldMatrix();
  10147. }
  10148. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10149. this.computeWorldMatrix();
  10150. }
  10151. return this._worldMatrix;
  10152. };
  10153. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10154. get: function () {
  10155. return this._worldMatrix;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10161. get: function () {
  10162. return this._absolutePosition;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10168. if (!this.rotationQuaternion) {
  10169. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10170. this.rotation = BABYLON.Vector3.Zero();
  10171. }
  10172. if (!space || space === 0 /* LOCAL */) {
  10173. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10174. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10175. }
  10176. else {
  10177. if (this.parent) {
  10178. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10179. invertParentWorldMatrix.invert();
  10180. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10181. }
  10182. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10183. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10184. }
  10185. };
  10186. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10187. var displacementVector = axis.scale(distance);
  10188. if (!space || space === 0 /* LOCAL */) {
  10189. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10190. this.setPositionWithLocalVector(tempV3);
  10191. }
  10192. else {
  10193. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10194. }
  10195. };
  10196. AbstractMesh.prototype.getAbsolutePosition = function () {
  10197. this.computeWorldMatrix();
  10198. return this._absolutePosition;
  10199. };
  10200. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10201. if (!absolutePosition) {
  10202. return;
  10203. }
  10204. var absolutePositionX;
  10205. var absolutePositionY;
  10206. var absolutePositionZ;
  10207. if (absolutePosition.x === undefined) {
  10208. if (arguments.length < 3) {
  10209. return;
  10210. }
  10211. absolutePositionX = arguments[0];
  10212. absolutePositionY = arguments[1];
  10213. absolutePositionZ = arguments[2];
  10214. }
  10215. else {
  10216. absolutePositionX = absolutePosition.x;
  10217. absolutePositionY = absolutePosition.y;
  10218. absolutePositionZ = absolutePosition.z;
  10219. }
  10220. if (this.parent) {
  10221. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10222. invertParentWorldMatrix.invert();
  10223. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10224. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10225. }
  10226. else {
  10227. this.position.x = absolutePositionX;
  10228. this.position.y = absolutePositionY;
  10229. this.position.z = absolutePositionZ;
  10230. }
  10231. };
  10232. // ================================== Point of View Movement =================================
  10233. /**
  10234. * Perform relative position change from the point of view of behind the front of the mesh.
  10235. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10236. * Supports definition of mesh facing forward or backward.
  10237. * @param {number} amountRight
  10238. * @param {number} amountUp
  10239. * @param {number} amountForward
  10240. */
  10241. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10242. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10243. };
  10244. /**
  10245. * Calculate relative position change from the point of view of behind the front of the mesh.
  10246. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10247. * Supports definition of mesh facing forward or backward.
  10248. * @param {number} amountRight
  10249. * @param {number} amountUp
  10250. * @param {number} amountForward
  10251. */
  10252. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10253. var rotMatrix = new BABYLON.Matrix();
  10254. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10255. rotQuaternion.toRotationMatrix(rotMatrix);
  10256. var translationDelta = BABYLON.Vector3.Zero();
  10257. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10258. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10259. return translationDelta;
  10260. };
  10261. // ================================== Point of View Rotation =================================
  10262. /**
  10263. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10264. * Supports definition of mesh facing forward or backward.
  10265. * @param {number} flipBack
  10266. * @param {number} twirlClockwise
  10267. * @param {number} tiltRight
  10268. */
  10269. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10270. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10271. };
  10272. /**
  10273. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10274. * Supports definition of mesh facing forward or backward.
  10275. * @param {number} flipBack
  10276. * @param {number} twirlClockwise
  10277. * @param {number} tiltRight
  10278. */
  10279. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10280. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10281. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10282. };
  10283. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10284. this._pivotMatrix = matrix;
  10285. this._cache.pivotMatrixUpdated = true;
  10286. };
  10287. AbstractMesh.prototype.getPivotMatrix = function () {
  10288. return this._pivotMatrix;
  10289. };
  10290. AbstractMesh.prototype._isSynchronized = function () {
  10291. if (this._isDirty) {
  10292. return false;
  10293. }
  10294. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10295. return false;
  10296. if (this._cache.pivotMatrixUpdated) {
  10297. return false;
  10298. }
  10299. if (this.infiniteDistance) {
  10300. return false;
  10301. }
  10302. if (!this._cache.position.equals(this.position))
  10303. return false;
  10304. if (this.rotationQuaternion) {
  10305. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10306. return false;
  10307. }
  10308. else {
  10309. if (!this._cache.rotation.equals(this.rotation))
  10310. return false;
  10311. }
  10312. if (!this._cache.scaling.equals(this.scaling))
  10313. return false;
  10314. return true;
  10315. };
  10316. AbstractMesh.prototype._initCache = function () {
  10317. _super.prototype._initCache.call(this);
  10318. this._cache.localMatrixUpdated = false;
  10319. this._cache.position = BABYLON.Vector3.Zero();
  10320. this._cache.scaling = BABYLON.Vector3.Zero();
  10321. this._cache.rotation = BABYLON.Vector3.Zero();
  10322. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10323. };
  10324. AbstractMesh.prototype.markAsDirty = function (property) {
  10325. if (property === "rotation") {
  10326. this.rotationQuaternion = null;
  10327. }
  10328. this._currentRenderId = Number.MAX_VALUE;
  10329. this._isDirty = true;
  10330. };
  10331. AbstractMesh.prototype._updateBoundingInfo = function () {
  10332. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10333. this._boundingInfo._update(this.worldMatrixFromCache);
  10334. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10335. };
  10336. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10337. if (!this.subMeshes) {
  10338. return;
  10339. }
  10340. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10341. var subMesh = this.subMeshes[subIndex];
  10342. subMesh.updateBoundingInfo(matrix);
  10343. }
  10344. };
  10345. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10346. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10347. return this._worldMatrix;
  10348. }
  10349. this._cache.position.copyFrom(this.position);
  10350. this._cache.scaling.copyFrom(this.scaling);
  10351. this._cache.pivotMatrixUpdated = false;
  10352. this._currentRenderId = this.getScene().getRenderId();
  10353. this._isDirty = false;
  10354. // Scaling
  10355. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10356. // Rotation
  10357. if (this.rotationQuaternion) {
  10358. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10359. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10360. }
  10361. else {
  10362. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10363. this._cache.rotation.copyFrom(this.rotation);
  10364. }
  10365. // Translation
  10366. if (this.infiniteDistance && !this.parent) {
  10367. var camera = this.getScene().activeCamera;
  10368. var cameraWorldMatrix = camera.getWorldMatrix();
  10369. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10370. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10371. }
  10372. else {
  10373. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10374. }
  10375. // Composing transformations
  10376. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10377. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10378. // Billboarding
  10379. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10380. var localPosition = this.position.clone();
  10381. var zero = this.getScene().activeCamera.position.clone();
  10382. if (this.parent && this.parent.position) {
  10383. localPosition.addInPlace(this.parent.position);
  10384. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10385. }
  10386. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10387. zero = this.getScene().activeCamera.position;
  10388. }
  10389. else {
  10390. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10391. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10392. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10393. zero.y = localPosition.y + 0.001;
  10394. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10395. zero.z = localPosition.z + 0.001;
  10396. }
  10397. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10398. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10399. this._localBillboard.invert();
  10400. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10401. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10402. }
  10403. // Local world
  10404. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10405. // Parent
  10406. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10407. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10408. }
  10409. else {
  10410. this._worldMatrix.copyFrom(this._localWorld);
  10411. }
  10412. // Bounding info
  10413. this._updateBoundingInfo();
  10414. // Absolute position
  10415. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10416. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10417. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10418. }
  10419. return this._worldMatrix;
  10420. };
  10421. /**
  10422. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10423. * @param func: callback function to add
  10424. */
  10425. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10426. this._onAfterWorldMatrixUpdate.push(func);
  10427. };
  10428. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10429. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10430. if (index > -1) {
  10431. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10432. }
  10433. };
  10434. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10435. this.computeWorldMatrix();
  10436. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10437. };
  10438. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10439. this.computeWorldMatrix();
  10440. var invLocalWorldMatrix = this._localWorld.clone();
  10441. invLocalWorldMatrix.invert();
  10442. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10443. };
  10444. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10445. this.computeWorldMatrix();
  10446. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10447. };
  10448. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10449. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10450. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10451. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10452. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10453. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10454. /// <returns>Mesh oriented towards targetMesh</returns>
  10455. yawCor = yawCor || 0; // default to zero if undefined
  10456. pitchCor = pitchCor || 0;
  10457. rollCor = rollCor || 0;
  10458. var dv = targetPoint.subtract(this.position);
  10459. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10460. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10461. var pitch = Math.atan2(dv.y, len);
  10462. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10463. };
  10464. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10465. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10466. return false;
  10467. }
  10468. return true;
  10469. };
  10470. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10471. if (!camera) {
  10472. camera = this.getScene().activeCamera;
  10473. }
  10474. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10475. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10476. return false;
  10477. }
  10478. return true;
  10479. };
  10480. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10481. if (!this._boundingInfo || !mesh._boundingInfo) {
  10482. return false;
  10483. }
  10484. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10485. };
  10486. AbstractMesh.prototype.intersectsPoint = function (point) {
  10487. if (!this._boundingInfo) {
  10488. return false;
  10489. }
  10490. return this._boundingInfo.intersectsPoint(point);
  10491. };
  10492. // Physics
  10493. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10494. var physicsEngine = this.getScene().getPhysicsEngine();
  10495. if (!physicsEngine) {
  10496. return;
  10497. }
  10498. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10499. if (impostor.impostor) {
  10500. // Old API
  10501. options = impostor;
  10502. impostor = impostor.impostor;
  10503. }
  10504. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10505. physicsEngine._unregisterMesh(this);
  10506. return;
  10507. }
  10508. if (!options) {
  10509. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10510. }
  10511. else {
  10512. if (!options.mass && options.mass !== 0)
  10513. options.mass = 0;
  10514. if (!options.friction && options.friction !== 0)
  10515. options.friction = 0.2;
  10516. if (!options.restitution && options.restitution !== 0)
  10517. options.restitution = 0.2;
  10518. }
  10519. this._physicImpostor = impostor;
  10520. this._physicsMass = options.mass;
  10521. this._physicsFriction = options.friction;
  10522. this._physicRestitution = options.restitution;
  10523. return physicsEngine._registerMesh(this, impostor, options);
  10524. };
  10525. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10526. if (!this._physicImpostor) {
  10527. return BABYLON.PhysicsEngine.NoImpostor;
  10528. }
  10529. return this._physicImpostor;
  10530. };
  10531. AbstractMesh.prototype.getPhysicsMass = function () {
  10532. if (!this._physicsMass) {
  10533. return 0;
  10534. }
  10535. return this._physicsMass;
  10536. };
  10537. AbstractMesh.prototype.getPhysicsFriction = function () {
  10538. if (!this._physicsFriction) {
  10539. return 0;
  10540. }
  10541. return this._physicsFriction;
  10542. };
  10543. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10544. if (!this._physicRestitution) {
  10545. return 0;
  10546. }
  10547. return this._physicRestitution;
  10548. };
  10549. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10550. if (!camera) {
  10551. camera = this.getScene().activeCamera;
  10552. }
  10553. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10554. };
  10555. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10556. if (!camera) {
  10557. camera = this.getScene().activeCamera;
  10558. }
  10559. return this.absolutePosition.subtract(camera.position).length();
  10560. };
  10561. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10562. if (!this._physicImpostor) {
  10563. return;
  10564. }
  10565. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10566. };
  10567. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10568. if (!this._physicImpostor) {
  10569. return;
  10570. }
  10571. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10572. };
  10573. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10574. if (!this._physicImpostor) {
  10575. return;
  10576. }
  10577. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10578. };
  10579. // Collisions
  10580. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10581. var globalPosition = this.getAbsolutePosition();
  10582. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10583. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10584. this._collider.radius = this.ellipsoid;
  10585. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10586. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10587. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10588. this.position.addInPlace(this._diffPositionForCollisions);
  10589. }
  10590. };
  10591. // Submeshes octree
  10592. /**
  10593. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10594. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10595. */
  10596. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10597. if (maxCapacity === void 0) { maxCapacity = 64; }
  10598. if (maxDepth === void 0) { maxDepth = 2; }
  10599. if (!this._submeshesOctree) {
  10600. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10601. }
  10602. this.computeWorldMatrix(true);
  10603. // Update octree
  10604. var bbox = this.getBoundingInfo().boundingBox;
  10605. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10606. return this._submeshesOctree;
  10607. };
  10608. // Collisions
  10609. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10610. this._generatePointsArray();
  10611. // Transformation
  10612. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10613. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10614. subMesh._lastColliderWorldVertices = [];
  10615. subMesh._trianglePlanes = [];
  10616. var start = subMesh.verticesStart;
  10617. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10618. for (var i = start; i < end; i++) {
  10619. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10620. }
  10621. }
  10622. // Collide
  10623. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10624. };
  10625. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10626. var subMeshes;
  10627. var len;
  10628. // Octrees
  10629. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10630. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10631. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10632. len = intersections.length;
  10633. subMeshes = intersections.data;
  10634. }
  10635. else {
  10636. subMeshes = this.subMeshes;
  10637. len = subMeshes.length;
  10638. }
  10639. for (var index = 0; index < len; index++) {
  10640. var subMesh = subMeshes[index];
  10641. // Bounding test
  10642. if (len > 1 && !subMesh._checkCollision(collider))
  10643. continue;
  10644. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10645. }
  10646. };
  10647. AbstractMesh.prototype._checkCollision = function (collider) {
  10648. // Bounding box test
  10649. if (!this._boundingInfo._checkCollision(collider))
  10650. return;
  10651. // Transformation matrix
  10652. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10653. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10654. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10655. };
  10656. // Picking
  10657. AbstractMesh.prototype._generatePointsArray = function () {
  10658. return false;
  10659. };
  10660. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10661. var pickingInfo = new BABYLON.PickingInfo();
  10662. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10663. return pickingInfo;
  10664. }
  10665. if (!this._generatePointsArray()) {
  10666. return pickingInfo;
  10667. }
  10668. var intersectInfo = null;
  10669. // Octrees
  10670. var subMeshes;
  10671. var len;
  10672. if (this._submeshesOctree && this.useOctreeForPicking) {
  10673. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10674. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10675. len = intersections.length;
  10676. subMeshes = intersections.data;
  10677. }
  10678. else {
  10679. subMeshes = this.subMeshes;
  10680. len = subMeshes.length;
  10681. }
  10682. for (var index = 0; index < len; index++) {
  10683. var subMesh = subMeshes[index];
  10684. // Bounding test
  10685. if (len > 1 && !subMesh.canIntersects(ray))
  10686. continue;
  10687. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10688. if (currentIntersectInfo) {
  10689. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10690. intersectInfo = currentIntersectInfo;
  10691. intersectInfo.subMeshId = index;
  10692. if (fastCheck) {
  10693. break;
  10694. }
  10695. }
  10696. }
  10697. }
  10698. if (intersectInfo) {
  10699. // Get picked point
  10700. var world = this.getWorldMatrix();
  10701. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10702. var direction = ray.direction.clone();
  10703. direction = direction.scale(intersectInfo.distance);
  10704. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10705. var pickedPoint = worldOrigin.add(worldDirection);
  10706. // Return result
  10707. pickingInfo.hit = true;
  10708. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10709. pickingInfo.pickedPoint = pickedPoint;
  10710. pickingInfo.pickedMesh = this;
  10711. pickingInfo.bu = intersectInfo.bu;
  10712. pickingInfo.bv = intersectInfo.bv;
  10713. pickingInfo.faceId = intersectInfo.faceId;
  10714. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10715. return pickingInfo;
  10716. }
  10717. return pickingInfo;
  10718. };
  10719. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10720. return null;
  10721. };
  10722. AbstractMesh.prototype.releaseSubMeshes = function () {
  10723. if (this.subMeshes) {
  10724. while (this.subMeshes.length) {
  10725. this.subMeshes[0].dispose();
  10726. }
  10727. }
  10728. else {
  10729. this.subMeshes = new Array();
  10730. }
  10731. };
  10732. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10733. var index;
  10734. // Physics
  10735. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10736. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10737. }
  10738. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10739. var other = this._intersectionsInProgress[index];
  10740. var pos = other._intersectionsInProgress.indexOf(this);
  10741. other._intersectionsInProgress.splice(pos, 1);
  10742. }
  10743. this._intersectionsInProgress = [];
  10744. // SubMeshes
  10745. this.releaseSubMeshes();
  10746. // Remove from scene
  10747. this.getScene().removeMesh(this);
  10748. if (!doNotRecurse) {
  10749. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10750. if (this.getScene().particleSystems[index].emitter === this) {
  10751. this.getScene().particleSystems[index].dispose();
  10752. index--;
  10753. }
  10754. }
  10755. // Children
  10756. var objects = this.getScene().meshes.slice(0);
  10757. for (index = 0; index < objects.length; index++) {
  10758. if (objects[index].parent === this) {
  10759. objects[index].dispose();
  10760. }
  10761. }
  10762. }
  10763. else {
  10764. for (index = 0; index < this.getScene().meshes.length; index++) {
  10765. var obj = this.getScene().meshes[index];
  10766. if (obj.parent === this) {
  10767. obj.parent = null;
  10768. obj.computeWorldMatrix(true);
  10769. }
  10770. }
  10771. }
  10772. this._onAfterWorldMatrixUpdate = [];
  10773. this._isDisposed = true;
  10774. // Callback
  10775. if (this.onDispose) {
  10776. this.onDispose();
  10777. }
  10778. };
  10779. // Statics
  10780. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10781. AbstractMesh._BILLBOARDMODE_X = 1;
  10782. AbstractMesh._BILLBOARDMODE_Y = 2;
  10783. AbstractMesh._BILLBOARDMODE_Z = 4;
  10784. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10785. return AbstractMesh;
  10786. })(BABYLON.Node);
  10787. BABYLON.AbstractMesh = AbstractMesh;
  10788. })(BABYLON || (BABYLON = {}));
  10789. //# sourceMappingURL=babylon.abstractMesh.js.map
  10790. var BABYLON;
  10791. (function (BABYLON) {
  10792. var _InstancesBatch = (function () {
  10793. function _InstancesBatch() {
  10794. this.mustReturn = false;
  10795. this.visibleInstances = new Array();
  10796. this.renderSelf = new Array();
  10797. }
  10798. return _InstancesBatch;
  10799. })();
  10800. BABYLON._InstancesBatch = _InstancesBatch;
  10801. var Mesh = (function (_super) {
  10802. __extends(Mesh, _super);
  10803. /**
  10804. * @constructor
  10805. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10806. * @param {Scene} scene - The scene to add this mesh to.
  10807. * @param {Node} parent - The parent of this mesh, if it has one
  10808. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10809. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10810. * When false, achieved by calling a clone(), also passing False.
  10811. * This will make creation of children, recursive.
  10812. */
  10813. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10814. if (parent === void 0) { parent = null; }
  10815. _super.call(this, name, scene);
  10816. // Members
  10817. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10818. this.instances = new Array();
  10819. this._LODLevels = new Array();
  10820. this._onBeforeRenderCallbacks = new Array();
  10821. this._onAfterRenderCallbacks = new Array();
  10822. this._visibleInstances = {};
  10823. this._renderIdForInstances = new Array();
  10824. this._batchCache = new _InstancesBatch();
  10825. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10826. if (source) {
  10827. // Geometry
  10828. if (source._geometry) {
  10829. source._geometry.applyToMesh(this);
  10830. }
  10831. // Deep copy
  10832. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10833. // Material
  10834. this.material = source.material;
  10835. if (!doNotCloneChildren) {
  10836. for (var index = 0; index < scene.meshes.length; index++) {
  10837. var mesh = scene.meshes[index];
  10838. if (mesh.parent === source) {
  10839. // doNotCloneChildren is always going to be False
  10840. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10841. }
  10842. }
  10843. }
  10844. for (index = 0; index < scene.particleSystems.length; index++) {
  10845. var system = scene.particleSystems[index];
  10846. if (system.emitter === source) {
  10847. system.clone(system.name, this);
  10848. }
  10849. }
  10850. this.computeWorldMatrix(true);
  10851. }
  10852. // Parent
  10853. if (parent !== null) {
  10854. this.parent = parent;
  10855. }
  10856. }
  10857. Object.defineProperty(Mesh, "FRONTSIDE", {
  10858. get: function () {
  10859. return Mesh._FRONTSIDE;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(Mesh, "BACKSIDE", {
  10865. get: function () {
  10866. return Mesh._BACKSIDE;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10872. get: function () {
  10873. return Mesh._DOUBLESIDE;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10879. get: function () {
  10880. return Mesh._DEFAULTSIDE;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10886. // Methods
  10887. get: function () {
  10888. return this._LODLevels.length > 0;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. Mesh.prototype._sortLODLevels = function () {
  10894. this._LODLevels.sort(function (a, b) {
  10895. if (a.distance < b.distance) {
  10896. return 1;
  10897. }
  10898. if (a.distance > b.distance) {
  10899. return -1;
  10900. }
  10901. return 0;
  10902. });
  10903. };
  10904. /**
  10905. * Add a mesh as LOD level triggered at the given distance.
  10906. * @param {number} distance - the distance from the center of the object to show this level
  10907. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10908. * @return {BABYLON.Mesh} this mesh (for chaining)
  10909. */
  10910. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10911. if (mesh && mesh._masterMesh) {
  10912. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10913. return this;
  10914. }
  10915. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10916. this._LODLevels.push(level);
  10917. if (mesh) {
  10918. mesh._masterMesh = this;
  10919. }
  10920. this._sortLODLevels();
  10921. return this;
  10922. };
  10923. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10924. for (var index = 0; index < this._LODLevels.length; index++) {
  10925. var level = this._LODLevels[index];
  10926. if (level.distance === distance) {
  10927. return level.mesh;
  10928. }
  10929. }
  10930. return null;
  10931. };
  10932. /**
  10933. * Remove a mesh from the LOD array
  10934. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10935. * @return {BABYLON.Mesh} this mesh (for chaining)
  10936. */
  10937. Mesh.prototype.removeLODLevel = function (mesh) {
  10938. for (var index = 0; index < this._LODLevels.length; index++) {
  10939. if (this._LODLevels[index].mesh === mesh) {
  10940. this._LODLevels.splice(index, 1);
  10941. if (mesh) {
  10942. mesh._masterMesh = null;
  10943. }
  10944. }
  10945. }
  10946. this._sortLODLevels();
  10947. return this;
  10948. };
  10949. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10950. if (!this._LODLevels || this._LODLevels.length === 0) {
  10951. return this;
  10952. }
  10953. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10954. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10955. if (this.onLODLevelSelection) {
  10956. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  10957. }
  10958. return this;
  10959. }
  10960. for (var index = 0; index < this._LODLevels.length; index++) {
  10961. var level = this._LODLevels[index];
  10962. if (level.distance < distanceToCamera) {
  10963. if (level.mesh) {
  10964. level.mesh._preActivate();
  10965. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10966. }
  10967. if (this.onLODLevelSelection) {
  10968. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  10969. }
  10970. return level.mesh;
  10971. }
  10972. }
  10973. if (this.onLODLevelSelection) {
  10974. this.onLODLevelSelection(distanceToCamera, this, this);
  10975. }
  10976. return this;
  10977. };
  10978. Object.defineProperty(Mesh.prototype, "geometry", {
  10979. get: function () {
  10980. return this._geometry;
  10981. },
  10982. enumerable: true,
  10983. configurable: true
  10984. });
  10985. Mesh.prototype.getTotalVertices = function () {
  10986. if (!this._geometry) {
  10987. return 0;
  10988. }
  10989. return this._geometry.getTotalVertices();
  10990. };
  10991. Mesh.prototype.getVerticesData = function (kind) {
  10992. if (!this._geometry) {
  10993. return null;
  10994. }
  10995. return this._geometry.getVerticesData(kind);
  10996. };
  10997. Mesh.prototype.getVertexBuffer = function (kind) {
  10998. if (!this._geometry) {
  10999. return undefined;
  11000. }
  11001. return this._geometry.getVertexBuffer(kind);
  11002. };
  11003. Mesh.prototype.isVerticesDataPresent = function (kind) {
  11004. if (!this._geometry) {
  11005. if (this._delayInfo) {
  11006. return this._delayInfo.indexOf(kind) !== -1;
  11007. }
  11008. return false;
  11009. }
  11010. return this._geometry.isVerticesDataPresent(kind);
  11011. };
  11012. Mesh.prototype.getVerticesDataKinds = function () {
  11013. if (!this._geometry) {
  11014. var result = [];
  11015. if (this._delayInfo) {
  11016. for (var kind in this._delayInfo) {
  11017. result.push(kind);
  11018. }
  11019. }
  11020. return result;
  11021. }
  11022. return this._geometry.getVerticesDataKinds();
  11023. };
  11024. Mesh.prototype.getTotalIndices = function () {
  11025. if (!this._geometry) {
  11026. return 0;
  11027. }
  11028. return this._geometry.getTotalIndices();
  11029. };
  11030. Mesh.prototype.getIndices = function () {
  11031. if (!this._geometry) {
  11032. return [];
  11033. }
  11034. return this._geometry.getIndices();
  11035. };
  11036. Object.defineProperty(Mesh.prototype, "isBlocked", {
  11037. get: function () {
  11038. return this._masterMesh !== null && this._masterMesh !== undefined;
  11039. },
  11040. enumerable: true,
  11041. configurable: true
  11042. });
  11043. Mesh.prototype.isReady = function () {
  11044. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11045. return false;
  11046. }
  11047. return _super.prototype.isReady.call(this);
  11048. };
  11049. Mesh.prototype.isDisposed = function () {
  11050. return this._isDisposed;
  11051. };
  11052. // Methods
  11053. Mesh.prototype._preActivate = function () {
  11054. var sceneRenderId = this.getScene().getRenderId();
  11055. if (this._preActivateId === sceneRenderId) {
  11056. return;
  11057. }
  11058. this._preActivateId = sceneRenderId;
  11059. this._visibleInstances = null;
  11060. };
  11061. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  11062. if (!this._visibleInstances) {
  11063. this._visibleInstances = {};
  11064. this._visibleInstances.defaultRenderId = renderId;
  11065. this._visibleInstances.selfDefaultRenderId = this._renderId;
  11066. }
  11067. if (!this._visibleInstances[renderId]) {
  11068. this._visibleInstances[renderId] = new Array();
  11069. }
  11070. this._visibleInstances[renderId].push(instance);
  11071. };
  11072. Mesh.prototype.refreshBoundingInfo = function () {
  11073. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11074. if (data) {
  11075. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  11076. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11077. }
  11078. if (this.subMeshes) {
  11079. for (var index = 0; index < this.subMeshes.length; index++) {
  11080. this.subMeshes[index].refreshBoundingInfo();
  11081. }
  11082. }
  11083. this._updateBoundingInfo();
  11084. };
  11085. Mesh.prototype._createGlobalSubMesh = function () {
  11086. var totalVertices = this.getTotalVertices();
  11087. if (!totalVertices || !this.getIndices()) {
  11088. return null;
  11089. }
  11090. this.releaseSubMeshes();
  11091. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  11092. };
  11093. Mesh.prototype.subdivide = function (count) {
  11094. if (count < 1) {
  11095. return;
  11096. }
  11097. var totalIndices = this.getTotalIndices();
  11098. var subdivisionSize = (totalIndices / count) | 0;
  11099. var offset = 0;
  11100. while (subdivisionSize % 3 !== 0) {
  11101. subdivisionSize++;
  11102. }
  11103. this.releaseSubMeshes();
  11104. for (var index = 0; index < count; index++) {
  11105. if (offset >= totalIndices) {
  11106. break;
  11107. }
  11108. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  11109. offset += subdivisionSize;
  11110. }
  11111. this.synchronizeInstances();
  11112. };
  11113. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11114. if (kind instanceof Array) {
  11115. var temp = data;
  11116. data = kind;
  11117. kind = temp;
  11118. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  11119. }
  11120. if (!this._geometry) {
  11121. var vertexData = new BABYLON.VertexData();
  11122. vertexData.set(data, kind);
  11123. var scene = this.getScene();
  11124. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  11125. }
  11126. else {
  11127. this._geometry.setVerticesData(kind, data, updatable, stride);
  11128. }
  11129. };
  11130. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11131. if (!this._geometry) {
  11132. return;
  11133. }
  11134. if (!makeItUnique) {
  11135. this._geometry.updateVerticesData(kind, data, updateExtends);
  11136. }
  11137. else {
  11138. this.makeGeometryUnique();
  11139. this.updateVerticesData(kind, data, updateExtends, false);
  11140. }
  11141. };
  11142. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11143. if (!this._geometry) {
  11144. return;
  11145. }
  11146. if (!makeItUnique) {
  11147. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11148. }
  11149. else {
  11150. this.makeGeometryUnique();
  11151. this.updateVerticesDataDirectly(kind, data, offset, false);
  11152. }
  11153. };
  11154. Mesh.prototype.makeGeometryUnique = function () {
  11155. if (!this._geometry) {
  11156. return;
  11157. }
  11158. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11159. geometry.applyToMesh(this);
  11160. };
  11161. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11162. if (!this._geometry) {
  11163. var vertexData = new BABYLON.VertexData();
  11164. vertexData.indices = indices;
  11165. var scene = this.getScene();
  11166. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11167. }
  11168. else {
  11169. this._geometry.setIndices(indices, totalVertices);
  11170. }
  11171. };
  11172. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11173. var engine = this.getScene().getEngine();
  11174. // Wireframe
  11175. var indexToBind;
  11176. switch (fillMode) {
  11177. case BABYLON.Material.PointFillMode:
  11178. indexToBind = null;
  11179. break;
  11180. case BABYLON.Material.WireFrameFillMode:
  11181. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11182. break;
  11183. default:
  11184. case BABYLON.Material.TriangleFillMode:
  11185. indexToBind = this._geometry.getIndexBuffer();
  11186. break;
  11187. }
  11188. // VBOs
  11189. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11190. };
  11191. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11192. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11193. return;
  11194. }
  11195. var engine = this.getScene().getEngine();
  11196. switch (fillMode) {
  11197. case BABYLON.Material.PointFillMode:
  11198. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11199. break;
  11200. case BABYLON.Material.WireFrameFillMode:
  11201. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11202. break;
  11203. default:
  11204. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11205. }
  11206. };
  11207. Mesh.prototype.registerBeforeRender = function (func) {
  11208. this._onBeforeRenderCallbacks.push(func);
  11209. };
  11210. Mesh.prototype.unregisterBeforeRender = function (func) {
  11211. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11212. if (index > -1) {
  11213. this._onBeforeRenderCallbacks.splice(index, 1);
  11214. }
  11215. };
  11216. Mesh.prototype.registerAfterRender = function (func) {
  11217. this._onAfterRenderCallbacks.push(func);
  11218. };
  11219. Mesh.prototype.unregisterAfterRender = function (func) {
  11220. var index = this._onAfterRenderCallbacks.indexOf(func);
  11221. if (index > -1) {
  11222. this._onAfterRenderCallbacks.splice(index, 1);
  11223. }
  11224. };
  11225. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11226. var scene = this.getScene();
  11227. this._batchCache.mustReturn = false;
  11228. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11229. this._batchCache.visibleInstances[subMeshId] = null;
  11230. if (this._visibleInstances) {
  11231. var currentRenderId = scene.getRenderId();
  11232. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11233. var selfRenderId = this._renderId;
  11234. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11235. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11236. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11237. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11238. }
  11239. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11240. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11241. this._batchCache.mustReturn = true;
  11242. return this._batchCache;
  11243. }
  11244. if (currentRenderId !== selfRenderId) {
  11245. this._batchCache.renderSelf[subMeshId] = false;
  11246. }
  11247. }
  11248. this._renderIdForInstances[subMeshId] = currentRenderId;
  11249. }
  11250. return this._batchCache;
  11251. };
  11252. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11253. var visibleInstances = batch.visibleInstances[subMesh._id];
  11254. var matricesCount = visibleInstances.length + 1;
  11255. var bufferSize = matricesCount * 16 * 4;
  11256. while (this._instancesBufferSize < bufferSize) {
  11257. this._instancesBufferSize *= 2;
  11258. }
  11259. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11260. if (this._worldMatricesInstancesBuffer) {
  11261. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11262. }
  11263. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11264. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11265. }
  11266. var offset = 0;
  11267. var instancesCount = 0;
  11268. var world = this.getWorldMatrix();
  11269. if (batch.renderSelf[subMesh._id]) {
  11270. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11271. offset += 16;
  11272. instancesCount++;
  11273. }
  11274. if (visibleInstances) {
  11275. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11276. var instance = visibleInstances[instanceIndex];
  11277. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11278. offset += 16;
  11279. instancesCount++;
  11280. }
  11281. }
  11282. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11283. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11284. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11285. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11286. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11287. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11288. this._draw(subMesh, fillMode, instancesCount);
  11289. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11290. };
  11291. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11292. var scene = this.getScene();
  11293. var engine = scene.getEngine();
  11294. if (hardwareInstancedRendering) {
  11295. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11296. }
  11297. else {
  11298. if (batch.renderSelf[subMesh._id]) {
  11299. // Draw
  11300. if (onBeforeDraw) {
  11301. onBeforeDraw(false, this.getWorldMatrix());
  11302. }
  11303. this._draw(subMesh, fillMode);
  11304. }
  11305. if (batch.visibleInstances[subMesh._id]) {
  11306. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11307. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11308. // World
  11309. var world = instance.getWorldMatrix();
  11310. if (onBeforeDraw) {
  11311. onBeforeDraw(true, world);
  11312. }
  11313. // Draw
  11314. this._draw(subMesh, fillMode);
  11315. }
  11316. }
  11317. }
  11318. };
  11319. Mesh.prototype.render = function (subMesh) {
  11320. var scene = this.getScene();
  11321. // Managing instances
  11322. var batch = this._getInstancesRenderList(subMesh._id);
  11323. if (batch.mustReturn) {
  11324. return;
  11325. }
  11326. // Checking geometry state
  11327. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11328. return;
  11329. }
  11330. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11331. this._onBeforeRenderCallbacks[callbackIndex](this);
  11332. }
  11333. var engine = scene.getEngine();
  11334. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11335. // Material
  11336. var effectiveMaterial = subMesh.getMaterial();
  11337. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11338. return;
  11339. }
  11340. // Outline - step 1
  11341. var savedDepthWrite = engine.getDepthWrite();
  11342. if (this.renderOutline) {
  11343. engine.setDepthWrite(false);
  11344. scene.getOutlineRenderer().render(subMesh, batch);
  11345. engine.setDepthWrite(savedDepthWrite);
  11346. }
  11347. effectiveMaterial._preBind();
  11348. var effect = effectiveMaterial.getEffect();
  11349. // Bind
  11350. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11351. this._bind(subMesh, effect, fillMode);
  11352. var world = this.getWorldMatrix();
  11353. effectiveMaterial.bind(world, this);
  11354. // Draw
  11355. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11356. if (isInstance) {
  11357. effectiveMaterial.bindOnlyWorldMatrix(world);
  11358. }
  11359. });
  11360. // Unbind
  11361. effectiveMaterial.unbind();
  11362. // Outline - step 2
  11363. if (this.renderOutline && savedDepthWrite) {
  11364. engine.setDepthWrite(true);
  11365. engine.setColorWrite(false);
  11366. scene.getOutlineRenderer().render(subMesh, batch);
  11367. engine.setColorWrite(true);
  11368. }
  11369. // Overlay
  11370. if (this.renderOverlay) {
  11371. var currentMode = engine.getAlphaMode();
  11372. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11373. scene.getOutlineRenderer().render(subMesh, batch, true);
  11374. engine.setAlphaMode(currentMode);
  11375. }
  11376. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11377. this._onAfterRenderCallbacks[callbackIndex](this);
  11378. }
  11379. };
  11380. Mesh.prototype.getEmittedParticleSystems = function () {
  11381. var results = new Array();
  11382. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11383. var particleSystem = this.getScene().particleSystems[index];
  11384. if (particleSystem.emitter === this) {
  11385. results.push(particleSystem);
  11386. }
  11387. }
  11388. return results;
  11389. };
  11390. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11391. var results = new Array();
  11392. var descendants = this.getDescendants();
  11393. descendants.push(this);
  11394. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11395. var particleSystem = this.getScene().particleSystems[index];
  11396. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11397. results.push(particleSystem);
  11398. }
  11399. }
  11400. return results;
  11401. };
  11402. Mesh.prototype.getChildren = function () {
  11403. var results = [];
  11404. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11405. var mesh = this.getScene().meshes[index];
  11406. if (mesh.parent === this) {
  11407. results.push(mesh);
  11408. }
  11409. }
  11410. return results;
  11411. };
  11412. Mesh.prototype._checkDelayState = function () {
  11413. var _this = this;
  11414. var that = this;
  11415. var scene = this.getScene();
  11416. if (this._geometry) {
  11417. this._geometry.load(scene);
  11418. }
  11419. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11420. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11421. scene._addPendingData(that);
  11422. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11423. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11424. if (data instanceof ArrayBuffer) {
  11425. _this._delayLoadingFunction(data, _this);
  11426. }
  11427. else {
  11428. _this._delayLoadingFunction(JSON.parse(data), _this);
  11429. }
  11430. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11431. scene._removePendingData(_this);
  11432. }, function () {
  11433. }, scene.database, getBinaryData);
  11434. }
  11435. };
  11436. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11437. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11438. return false;
  11439. }
  11440. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11441. return false;
  11442. }
  11443. this._checkDelayState();
  11444. return true;
  11445. };
  11446. Mesh.prototype.setMaterialByID = function (id) {
  11447. var materials = this.getScene().materials;
  11448. for (var index = 0; index < materials.length; index++) {
  11449. if (materials[index].id === id) {
  11450. this.material = materials[index];
  11451. return;
  11452. }
  11453. }
  11454. // Multi
  11455. var multiMaterials = this.getScene().multiMaterials;
  11456. for (index = 0; index < multiMaterials.length; index++) {
  11457. if (multiMaterials[index].id === id) {
  11458. this.material = multiMaterials[index];
  11459. return;
  11460. }
  11461. }
  11462. };
  11463. Mesh.prototype.getAnimatables = function () {
  11464. var results = [];
  11465. if (this.material) {
  11466. results.push(this.material);
  11467. }
  11468. if (this.skeleton) {
  11469. results.push(this.skeleton);
  11470. }
  11471. return results;
  11472. };
  11473. // Geometry
  11474. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11475. // Position
  11476. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11477. return;
  11478. }
  11479. this._resetPointsArrayCache();
  11480. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11481. var temp = [];
  11482. for (var index = 0; index < data.length; index += 3) {
  11483. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11484. }
  11485. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11486. // Normals
  11487. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11488. return;
  11489. }
  11490. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11491. for (index = 0; index < data.length; index += 3) {
  11492. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11493. }
  11494. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11495. };
  11496. // Cache
  11497. Mesh.prototype._resetPointsArrayCache = function () {
  11498. this._positions = null;
  11499. };
  11500. Mesh.prototype._generatePointsArray = function () {
  11501. if (this._positions)
  11502. return true;
  11503. this._positions = [];
  11504. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11505. if (!data) {
  11506. return false;
  11507. }
  11508. for (var index = 0; index < data.length; index += 3) {
  11509. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11510. }
  11511. return true;
  11512. };
  11513. // Clone
  11514. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11515. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11516. };
  11517. // Dispose
  11518. Mesh.prototype.dispose = function (doNotRecurse) {
  11519. if (this._geometry) {
  11520. this._geometry.releaseForMesh(this, true);
  11521. }
  11522. // Instances
  11523. if (this._worldMatricesInstancesBuffer) {
  11524. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11525. this._worldMatricesInstancesBuffer = null;
  11526. }
  11527. while (this.instances.length) {
  11528. this.instances[0].dispose();
  11529. }
  11530. _super.prototype.dispose.call(this, doNotRecurse);
  11531. };
  11532. // Geometric tools
  11533. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11534. var _this = this;
  11535. var scene = this.getScene();
  11536. var onload = function (img) {
  11537. // Getting height map data
  11538. var canvas = document.createElement("canvas");
  11539. var context = canvas.getContext("2d");
  11540. var heightMapWidth = img.width;
  11541. var heightMapHeight = img.height;
  11542. canvas.width = heightMapWidth;
  11543. canvas.height = heightMapHeight;
  11544. context.drawImage(img, 0, 0);
  11545. // Create VertexData from map data
  11546. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11547. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11548. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11549. //execute success callback, if set
  11550. if (onSuccess) {
  11551. onSuccess(_this);
  11552. }
  11553. };
  11554. BABYLON.Tools.LoadImage(url, onload, function () {
  11555. }, scene.database);
  11556. };
  11557. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11558. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11559. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11560. return;
  11561. }
  11562. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11563. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11564. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11565. var position = BABYLON.Vector3.Zero();
  11566. var normal = BABYLON.Vector3.Zero();
  11567. var uv = BABYLON.Vector2.Zero();
  11568. for (var index = 0; index < positions.length; index += 3) {
  11569. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11570. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11571. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11572. // Compute height
  11573. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11574. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11575. var pos = (u + v * heightMapWidth) * 4;
  11576. var r = buffer[pos] / 255.0;
  11577. var g = buffer[pos + 1] / 255.0;
  11578. var b = buffer[pos + 2] / 255.0;
  11579. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11580. normal.normalize();
  11581. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11582. position = position.add(normal);
  11583. position.toArray(positions, index);
  11584. }
  11585. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11586. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11587. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11588. };
  11589. Mesh.prototype.convertToFlatShadedMesh = function () {
  11590. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11591. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11592. var kinds = this.getVerticesDataKinds();
  11593. var vbs = [];
  11594. var data = [];
  11595. var newdata = [];
  11596. var updatableNormals = false;
  11597. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11598. var kind = kinds[kindIndex];
  11599. var vertexBuffer = this.getVertexBuffer(kind);
  11600. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11601. updatableNormals = vertexBuffer.isUpdatable();
  11602. kinds.splice(kindIndex, 1);
  11603. kindIndex--;
  11604. continue;
  11605. }
  11606. vbs[kind] = vertexBuffer;
  11607. data[kind] = vbs[kind].getData();
  11608. newdata[kind] = [];
  11609. }
  11610. // Save previous submeshes
  11611. var previousSubmeshes = this.subMeshes.slice(0);
  11612. var indices = this.getIndices();
  11613. var totalIndices = this.getTotalIndices();
  11614. for (var index = 0; index < totalIndices; index++) {
  11615. var vertexIndex = indices[index];
  11616. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11617. kind = kinds[kindIndex];
  11618. var stride = vbs[kind].getStrideSize();
  11619. for (var offset = 0; offset < stride; offset++) {
  11620. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11621. }
  11622. }
  11623. }
  11624. // Updating faces & normal
  11625. var normals = [];
  11626. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11627. for (index = 0; index < totalIndices; index += 3) {
  11628. indices[index] = index;
  11629. indices[index + 1] = index + 1;
  11630. indices[index + 2] = index + 2;
  11631. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11632. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11633. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11634. var p1p2 = p1.subtract(p2);
  11635. var p3p2 = p3.subtract(p2);
  11636. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11637. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11638. normals.push(normal.x);
  11639. normals.push(normal.y);
  11640. normals.push(normal.z);
  11641. }
  11642. }
  11643. this.setIndices(indices);
  11644. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11645. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11646. kind = kinds[kindIndex];
  11647. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11648. }
  11649. // Updating submeshes
  11650. this.releaseSubMeshes();
  11651. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11652. var previousOne = previousSubmeshes[submeshIndex];
  11653. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11654. }
  11655. this.synchronizeInstances();
  11656. };
  11657. // Instances
  11658. Mesh.prototype.createInstance = function (name) {
  11659. return new BABYLON.InstancedMesh(name, this);
  11660. };
  11661. Mesh.prototype.synchronizeInstances = function () {
  11662. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11663. var instance = this.instances[instanceIndex];
  11664. instance._syncSubMeshes();
  11665. }
  11666. };
  11667. /**
  11668. * Simplify the mesh according to the given array of settings.
  11669. * Function will return immediately and will simplify async.
  11670. * @param settings a collection of simplification settings.
  11671. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11672. * @param type the type of simplification to run.
  11673. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11674. */
  11675. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11676. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11677. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11678. this.getScene().simplificationQueue.addTask({
  11679. settings: settings,
  11680. parallelProcessing: parallelProcessing,
  11681. mesh: this,
  11682. simplificationType: simplificationType,
  11683. successCallback: successCallback
  11684. });
  11685. };
  11686. /**
  11687. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11688. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11689. * This should be used together with the simplification to avoid disappearing triangles.
  11690. * @param successCallback an optional success callback to be called after the optimization finished.
  11691. */
  11692. Mesh.prototype.optimizeIndices = function (successCallback) {
  11693. var _this = this;
  11694. var indices = this.getIndices();
  11695. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11696. var vectorPositions = [];
  11697. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11698. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11699. }
  11700. var dupes = [];
  11701. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11702. var realPos = vectorPositions.length - 1 - iteration;
  11703. var testedPosition = vectorPositions[realPos];
  11704. for (var j = 0; j < realPos; ++j) {
  11705. var againstPosition = vectorPositions[j];
  11706. if (testedPosition.equals(againstPosition)) {
  11707. dupes[realPos] = j;
  11708. break;
  11709. }
  11710. }
  11711. }, function () {
  11712. for (var i = 0; i < indices.length; ++i) {
  11713. indices[i] = dupes[indices[i]] || indices[i];
  11714. }
  11715. //indices are now reordered
  11716. var originalSubMeshes = _this.subMeshes.slice(0);
  11717. _this.setIndices(indices);
  11718. _this.subMeshes = originalSubMeshes;
  11719. if (successCallback) {
  11720. successCallback(_this);
  11721. }
  11722. });
  11723. };
  11724. // Statics
  11725. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11726. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11727. var ribbon = new Mesh(name, scene);
  11728. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11729. vertexData.applyToMesh(ribbon, updatable);
  11730. return ribbon;
  11731. };
  11732. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11733. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11734. var box = new Mesh(name, scene);
  11735. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11736. vertexData.applyToMesh(box, updatable);
  11737. return box;
  11738. };
  11739. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11740. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11741. var sphere = new Mesh(name, scene);
  11742. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11743. vertexData.applyToMesh(sphere, updatable);
  11744. return sphere;
  11745. };
  11746. // Cylinder and cone (Code inspired by SharpDX.org)
  11747. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11748. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11749. // subdivisions is a new parameter, we need to support old signature
  11750. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11751. if (scene !== undefined) {
  11752. updatable = scene;
  11753. }
  11754. scene = subdivisions;
  11755. subdivisions = 1;
  11756. }
  11757. var cylinder = new Mesh(name, scene);
  11758. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11759. vertexData.applyToMesh(cylinder, updatable);
  11760. return cylinder;
  11761. };
  11762. // Torus (Code from SharpDX.org)
  11763. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11764. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11765. var torus = new Mesh(name, scene);
  11766. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11767. vertexData.applyToMesh(torus, updatable);
  11768. return torus;
  11769. };
  11770. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11771. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11772. var torusKnot = new Mesh(name, scene);
  11773. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11774. vertexData.applyToMesh(torusKnot, updatable);
  11775. return torusKnot;
  11776. };
  11777. // Lines
  11778. Mesh.CreateLines = function (name, points, scene, updatable) {
  11779. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11780. var vertexData = BABYLON.VertexData.CreateLines(points);
  11781. vertexData.applyToMesh(lines, updatable);
  11782. return lines;
  11783. };
  11784. // Extrusion
  11785. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11786. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11787. scale = scale || 1;
  11788. rotation = rotation || 0;
  11789. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11790. return extruded;
  11791. };
  11792. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11793. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11794. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11795. return extrudedCustom;
  11796. };
  11797. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11798. var path3D = new BABYLON.Path3D(curve);
  11799. var tangents = path3D.getTangents();
  11800. var normals = path3D.getNormals();
  11801. var binormals = path3D.getBinormals();
  11802. var distances = path3D.getDistances();
  11803. var shapePaths = new Array();
  11804. var angle = 0;
  11805. var returnScale = function (i, distance) {
  11806. return scale;
  11807. };
  11808. var returnRotation = function (i, distance) {
  11809. return rotation;
  11810. };
  11811. var rotate = custom ? rotateFunction : returnRotation;
  11812. var scl = custom ? scaleFunction : returnScale;
  11813. for (var i = 0; i < curve.length; i++) {
  11814. var shapePath = new Array();
  11815. var angleStep = rotate(i, distances[i]);
  11816. var scaleRatio = scl(i, distances[i]);
  11817. for (var p = 0; p < shape.length; p++) {
  11818. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11819. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11820. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11821. shapePath.push(rotated);
  11822. }
  11823. shapePaths.push(shapePath);
  11824. angle += angleStep;
  11825. }
  11826. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11827. return extrudedGeneric;
  11828. };
  11829. // Plane & ground
  11830. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11831. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11832. var plane = new Mesh(name, scene);
  11833. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11834. vertexData.applyToMesh(plane, updatable);
  11835. return plane;
  11836. };
  11837. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11838. var ground = new BABYLON.GroundMesh(name, scene);
  11839. ground._setReady(false);
  11840. ground._subdivisions = subdivisions;
  11841. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11842. vertexData.applyToMesh(ground, updatable);
  11843. ground._setReady(true);
  11844. return ground;
  11845. };
  11846. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11847. var tiledGround = new Mesh(name, scene);
  11848. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11849. vertexData.applyToMesh(tiledGround, updatable);
  11850. return tiledGround;
  11851. };
  11852. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11853. var ground = new BABYLON.GroundMesh(name, scene);
  11854. ground._subdivisions = subdivisions;
  11855. ground._setReady(false);
  11856. var onload = function (img) {
  11857. // Getting height map data
  11858. var canvas = document.createElement("canvas");
  11859. var context = canvas.getContext("2d");
  11860. var heightMapWidth = img.width;
  11861. var heightMapHeight = img.height;
  11862. canvas.width = heightMapWidth;
  11863. canvas.height = heightMapHeight;
  11864. context.drawImage(img, 0, 0);
  11865. // Create VertexData from map data
  11866. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11867. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11868. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11869. vertexData.applyToMesh(ground, updatable);
  11870. ground._setReady(true);
  11871. //execute ready callback, if set
  11872. if (onReady) {
  11873. onReady(ground);
  11874. }
  11875. };
  11876. BABYLON.Tools.LoadImage(url, onload, function () {
  11877. }, scene.database);
  11878. return ground;
  11879. };
  11880. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11881. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11882. var path3D = new BABYLON.Path3D(path);
  11883. var tangents = path3D.getTangents();
  11884. var normals = path3D.getNormals();
  11885. var distances = path3D.getDistances();
  11886. var pi2 = Math.PI * 2;
  11887. var step = pi2 / tesselation;
  11888. var returnRadius = function (i, distance) { return radius; };
  11889. var radiusFunctionFinal = radiusFunction || returnRadius;
  11890. var circlePaths = new Array();
  11891. var circlePath;
  11892. var rad;
  11893. var normal;
  11894. var rotated;
  11895. var rotationMatrix;
  11896. for (var i = 0; i < path.length; i++) {
  11897. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11898. circlePath = Array(); // current circle array
  11899. normal = normals[i]; // current normal
  11900. for (var ang = 0; ang < pi2; ang += step) {
  11901. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11902. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11903. circlePath.push(rotated);
  11904. }
  11905. circlePaths.push(circlePath);
  11906. }
  11907. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11908. return tube;
  11909. };
  11910. // Decals
  11911. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  11912. if (angle === void 0) { angle = 0; }
  11913. var indices = sourceMesh.getIndices();
  11914. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11915. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11916. // Getting correct rotation
  11917. if (!normal) {
  11918. var target = new BABYLON.Vector3(0, 0, 1);
  11919. var camera = sourceMesh.getScene().activeCamera;
  11920. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  11921. normal = camera.globalPosition.subtract(cameraWorldTarget);
  11922. }
  11923. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  11924. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  11925. var pitch = Math.atan2(normal.y, len);
  11926. // Matrix
  11927. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  11928. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  11929. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  11930. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  11931. var vertexData = new BABYLON.VertexData();
  11932. vertexData.indices = [];
  11933. vertexData.positions = [];
  11934. vertexData.normals = [];
  11935. vertexData.uvs = [];
  11936. var currentVertexDataIndex = 0;
  11937. var extractDecalVector3 = function (indexId) {
  11938. var vertexId = indices[indexId];
  11939. var result = new BABYLON.PositionNormalVertex();
  11940. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  11941. // Send vector to decal local world
  11942. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  11943. // Get normal
  11944. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  11945. return result;
  11946. };
  11947. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  11948. var clip = function (vertices, axis) {
  11949. if (vertices.length === 0) {
  11950. return vertices;
  11951. }
  11952. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  11953. var clipVertices = function (v0, v1) {
  11954. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  11955. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  11956. };
  11957. var result = new Array();
  11958. for (var index = 0; index < vertices.length; index += 3) {
  11959. var v1Out;
  11960. var v2Out;
  11961. var v3Out;
  11962. var total = 0;
  11963. var nV1, nV2, nV3, nV4;
  11964. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  11965. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  11966. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  11967. v1Out = d1 > 0;
  11968. v2Out = d2 > 0;
  11969. v3Out = d3 > 0;
  11970. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  11971. switch (total) {
  11972. case 0:
  11973. result.push(vertices[index]);
  11974. result.push(vertices[index + 1]);
  11975. result.push(vertices[index + 2]);
  11976. break;
  11977. case 1:
  11978. if (v1Out) {
  11979. nV1 = vertices[index + 1];
  11980. nV2 = vertices[index + 2];
  11981. nV3 = clipVertices(vertices[index], nV1);
  11982. nV4 = clipVertices(vertices[index], nV2);
  11983. }
  11984. if (v2Out) {
  11985. nV1 = vertices[index];
  11986. nV2 = vertices[index + 2];
  11987. nV3 = clipVertices(vertices[index + 1], nV1);
  11988. nV4 = clipVertices(vertices[index + 1], nV2);
  11989. result.push(nV3);
  11990. result.push(nV2.clone());
  11991. result.push(nV1.clone());
  11992. result.push(nV2.clone());
  11993. result.push(nV3.clone());
  11994. result.push(nV4);
  11995. break;
  11996. }
  11997. if (v3Out) {
  11998. nV1 = vertices[index];
  11999. nV2 = vertices[index + 1];
  12000. nV3 = clipVertices(vertices[index + 2], nV1);
  12001. nV4 = clipVertices(vertices[index + 2], nV2);
  12002. }
  12003. result.push(nV1.clone());
  12004. result.push(nV2.clone());
  12005. result.push(nV3);
  12006. result.push(nV4);
  12007. result.push(nV3.clone());
  12008. result.push(nV2.clone());
  12009. break;
  12010. case 2:
  12011. if (!v1Out) {
  12012. nV1 = vertices[index].clone();
  12013. nV2 = clipVertices(nV1, vertices[index + 1]);
  12014. nV3 = clipVertices(nV1, vertices[index + 2]);
  12015. result.push(nV1);
  12016. result.push(nV2);
  12017. result.push(nV3);
  12018. }
  12019. if (!v2Out) {
  12020. nV1 = vertices[index + 1].clone();
  12021. nV2 = clipVertices(nV1, vertices[index + 2]);
  12022. nV3 = clipVertices(nV1, vertices[index]);
  12023. result.push(nV1);
  12024. result.push(nV2);
  12025. result.push(nV3);
  12026. }
  12027. if (!v3Out) {
  12028. nV1 = vertices[index + 2].clone();
  12029. nV2 = clipVertices(nV1, vertices[index]);
  12030. nV3 = clipVertices(nV1, vertices[index + 1]);
  12031. result.push(nV1);
  12032. result.push(nV2);
  12033. result.push(nV3);
  12034. }
  12035. break;
  12036. case 3:
  12037. break;
  12038. }
  12039. }
  12040. return result;
  12041. };
  12042. for (var index = 0; index < indices.length; index += 3) {
  12043. var faceVertices = new Array();
  12044. faceVertices.push(extractDecalVector3(index));
  12045. faceVertices.push(extractDecalVector3(index + 1));
  12046. faceVertices.push(extractDecalVector3(index + 2));
  12047. // Clip
  12048. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  12049. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  12050. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  12051. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  12052. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  12053. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  12054. if (faceVertices.length === 0) {
  12055. continue;
  12056. }
  12057. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  12058. var vertex = faceVertices[vIndex];
  12059. vertexData.indices.push(currentVertexDataIndex);
  12060. BABYLON.Vector3.TransformCoordinates(vertex.position, decalWorldMatrix).toArray(vertexData.positions, currentVertexDataIndex * 3);
  12061. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  12062. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  12063. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  12064. currentVertexDataIndex++;
  12065. }
  12066. }
  12067. // Return mesh
  12068. var decal = new Mesh(name, sourceMesh.getScene());
  12069. vertexData.applyToMesh(decal);
  12070. return decal;
  12071. };
  12072. // Tools
  12073. Mesh.MinMax = function (meshes) {
  12074. var minVector = null;
  12075. var maxVector = null;
  12076. for (var i in meshes) {
  12077. var mesh = meshes[i];
  12078. var boundingBox = mesh.getBoundingInfo().boundingBox;
  12079. if (!minVector) {
  12080. minVector = boundingBox.minimumWorld;
  12081. maxVector = boundingBox.maximumWorld;
  12082. continue;
  12083. }
  12084. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  12085. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  12086. }
  12087. return {
  12088. min: minVector,
  12089. max: maxVector
  12090. };
  12091. };
  12092. Mesh.Center = function (meshesOrMinMaxVector) {
  12093. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  12094. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  12095. };
  12096. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  12097. if (disposeSource === void 0) { disposeSource = true; }
  12098. var source = meshes[0];
  12099. var material = source.material;
  12100. var scene = source.getScene();
  12101. if (!allow32BitsIndices) {
  12102. var totalVertices = 0;
  12103. for (var index = 0; index < meshes.length; index++) {
  12104. totalVertices += meshes[index].getTotalVertices();
  12105. if (totalVertices > 65536) {
  12106. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  12107. return null;
  12108. }
  12109. }
  12110. }
  12111. // Merge
  12112. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  12113. vertexData.transform(source.getWorldMatrix());
  12114. for (index = 1; index < meshes.length; index++) {
  12115. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  12116. otherVertexData.transform(meshes[index].getWorldMatrix());
  12117. vertexData.merge(otherVertexData);
  12118. }
  12119. var newMesh = new Mesh(source.name + "_merged", scene);
  12120. vertexData.applyToMesh(newMesh);
  12121. // Setting properties
  12122. newMesh.material = material;
  12123. newMesh.checkCollisions = source.checkCollisions;
  12124. // Cleaning
  12125. if (disposeSource) {
  12126. for (index = 0; index < meshes.length; index++) {
  12127. meshes[index].dispose();
  12128. }
  12129. }
  12130. return newMesh;
  12131. };
  12132. // Consts
  12133. Mesh._FRONTSIDE = 0;
  12134. Mesh._BACKSIDE = 1;
  12135. Mesh._DOUBLESIDE = 2;
  12136. Mesh._DEFAULTSIDE = 0;
  12137. return Mesh;
  12138. })(BABYLON.AbstractMesh);
  12139. BABYLON.Mesh = Mesh;
  12140. })(BABYLON || (BABYLON = {}));
  12141. //# sourceMappingURL=babylon.mesh.js.map
  12142. var BABYLON;
  12143. (function (BABYLON) {
  12144. var GroundMesh = (function (_super) {
  12145. __extends(GroundMesh, _super);
  12146. function GroundMesh(name, scene) {
  12147. _super.call(this, name, scene);
  12148. this.generateOctree = false;
  12149. this._worldInverse = new BABYLON.Matrix();
  12150. }
  12151. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  12152. get: function () {
  12153. return this._subdivisions;
  12154. },
  12155. enumerable: true,
  12156. configurable: true
  12157. });
  12158. GroundMesh.prototype.optimize = function (chunksCount) {
  12159. this.subdivide(this._subdivisions);
  12160. this.createOrUpdateSubmeshesOctree(32);
  12161. };
  12162. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  12163. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  12164. this.getWorldMatrix().invertToRef(this._worldInverse);
  12165. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  12166. var pickInfo = this.intersects(ray);
  12167. if (pickInfo.hit) {
  12168. return pickInfo.pickedPoint.y;
  12169. }
  12170. return 0;
  12171. };
  12172. return GroundMesh;
  12173. })(BABYLON.Mesh);
  12174. BABYLON.GroundMesh = GroundMesh;
  12175. })(BABYLON || (BABYLON = {}));
  12176. //# sourceMappingURL=babylon.groundMesh.js.map
  12177. var BABYLON;
  12178. (function (BABYLON) {
  12179. /**
  12180. * Creates an instance based on a source mesh.
  12181. */
  12182. var InstancedMesh = (function (_super) {
  12183. __extends(InstancedMesh, _super);
  12184. function InstancedMesh(name, source) {
  12185. _super.call(this, name, source.getScene());
  12186. source.instances.push(this);
  12187. this._sourceMesh = source;
  12188. this.position.copyFrom(source.position);
  12189. this.rotation.copyFrom(source.rotation);
  12190. this.scaling.copyFrom(source.scaling);
  12191. if (source.rotationQuaternion) {
  12192. this.rotationQuaternion = source.rotationQuaternion.clone();
  12193. }
  12194. this.infiniteDistance = source.infiniteDistance;
  12195. this.setPivotMatrix(source.getPivotMatrix());
  12196. this.refreshBoundingInfo();
  12197. this._syncSubMeshes();
  12198. }
  12199. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12200. // Methods
  12201. get: function () {
  12202. return this._sourceMesh.receiveShadows;
  12203. },
  12204. enumerable: true,
  12205. configurable: true
  12206. });
  12207. Object.defineProperty(InstancedMesh.prototype, "material", {
  12208. get: function () {
  12209. return this._sourceMesh.material;
  12210. },
  12211. enumerable: true,
  12212. configurable: true
  12213. });
  12214. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12215. get: function () {
  12216. return this._sourceMesh.visibility;
  12217. },
  12218. enumerable: true,
  12219. configurable: true
  12220. });
  12221. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12222. get: function () {
  12223. return this._sourceMesh.skeleton;
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. InstancedMesh.prototype.getTotalVertices = function () {
  12229. return this._sourceMesh.getTotalVertices();
  12230. };
  12231. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12232. get: function () {
  12233. return this._sourceMesh;
  12234. },
  12235. enumerable: true,
  12236. configurable: true
  12237. });
  12238. InstancedMesh.prototype.getVerticesData = function (kind) {
  12239. return this._sourceMesh.getVerticesData(kind);
  12240. };
  12241. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12242. return this._sourceMesh.isVerticesDataPresent(kind);
  12243. };
  12244. InstancedMesh.prototype.getIndices = function () {
  12245. return this._sourceMesh.getIndices();
  12246. };
  12247. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12248. get: function () {
  12249. return this._sourceMesh._positions;
  12250. },
  12251. enumerable: true,
  12252. configurable: true
  12253. });
  12254. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12255. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12256. if (data) {
  12257. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12258. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12259. }
  12260. this._updateBoundingInfo();
  12261. };
  12262. InstancedMesh.prototype._preActivate = function () {
  12263. if (this._currentLOD) {
  12264. this._currentLOD._preActivate();
  12265. }
  12266. };
  12267. InstancedMesh.prototype._activate = function (renderId) {
  12268. if (this._currentLOD) {
  12269. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12270. }
  12271. };
  12272. InstancedMesh.prototype.getLOD = function (camera) {
  12273. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12274. if (this._currentLOD === this.sourceMesh) {
  12275. return this;
  12276. }
  12277. return this._currentLOD;
  12278. };
  12279. InstancedMesh.prototype._syncSubMeshes = function () {
  12280. this.releaseSubMeshes();
  12281. if (this._sourceMesh.subMeshes) {
  12282. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12283. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12284. }
  12285. }
  12286. };
  12287. InstancedMesh.prototype._generatePointsArray = function () {
  12288. return this._sourceMesh._generatePointsArray();
  12289. };
  12290. // Clone
  12291. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12292. var result = this._sourceMesh.createInstance(name);
  12293. // Deep copy
  12294. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12295. // Bounding info
  12296. this.refreshBoundingInfo();
  12297. // Parent
  12298. if (newParent) {
  12299. result.parent = newParent;
  12300. }
  12301. if (!doNotCloneChildren) {
  12302. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12303. var mesh = this.getScene().meshes[index];
  12304. if (mesh.parent === this) {
  12305. mesh.clone(mesh.name, result);
  12306. }
  12307. }
  12308. }
  12309. result.computeWorldMatrix(true);
  12310. return result;
  12311. };
  12312. // Dispoe
  12313. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12314. // Remove from mesh
  12315. var index = this._sourceMesh.instances.indexOf(this);
  12316. this._sourceMesh.instances.splice(index, 1);
  12317. _super.prototype.dispose.call(this, doNotRecurse);
  12318. };
  12319. return InstancedMesh;
  12320. })(BABYLON.AbstractMesh);
  12321. BABYLON.InstancedMesh = InstancedMesh;
  12322. })(BABYLON || (BABYLON = {}));
  12323. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12324. (function (BABYLON) {
  12325. var SubMesh = (function () {
  12326. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12327. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12328. this.materialIndex = materialIndex;
  12329. this.verticesStart = verticesStart;
  12330. this.verticesCount = verticesCount;
  12331. this.indexStart = indexStart;
  12332. this.indexCount = indexCount;
  12333. this._renderId = 0;
  12334. this._mesh = mesh;
  12335. this._renderingMesh = renderingMesh || mesh;
  12336. mesh.subMeshes.push(this);
  12337. this._id = mesh.subMeshes.length - 1;
  12338. if (createBoundingBox) {
  12339. this.refreshBoundingInfo();
  12340. mesh.computeWorldMatrix(true);
  12341. }
  12342. }
  12343. SubMesh.prototype.getBoundingInfo = function () {
  12344. return this._boundingInfo;
  12345. };
  12346. SubMesh.prototype.getMesh = function () {
  12347. return this._mesh;
  12348. };
  12349. SubMesh.prototype.getRenderingMesh = function () {
  12350. return this._renderingMesh;
  12351. };
  12352. SubMesh.prototype.getMaterial = function () {
  12353. var rootMaterial = this._renderingMesh.material;
  12354. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12355. var multiMaterial = rootMaterial;
  12356. return multiMaterial.getSubMaterial(this.materialIndex);
  12357. }
  12358. if (!rootMaterial) {
  12359. return this._mesh.getScene().defaultMaterial;
  12360. }
  12361. return rootMaterial;
  12362. };
  12363. // Methods
  12364. SubMesh.prototype.refreshBoundingInfo = function () {
  12365. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12366. if (!data) {
  12367. this._boundingInfo = this._mesh._boundingInfo;
  12368. return;
  12369. }
  12370. var indices = this._renderingMesh.getIndices();
  12371. var extend;
  12372. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12373. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12374. }
  12375. else {
  12376. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12377. }
  12378. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12379. };
  12380. SubMesh.prototype._checkCollision = function (collider) {
  12381. return this._boundingInfo._checkCollision(collider);
  12382. };
  12383. SubMesh.prototype.updateBoundingInfo = function (world) {
  12384. if (!this._boundingInfo) {
  12385. this.refreshBoundingInfo();
  12386. }
  12387. this._boundingInfo._update(world);
  12388. };
  12389. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12390. return this._boundingInfo.isInFrustum(frustumPlanes);
  12391. };
  12392. SubMesh.prototype.render = function () {
  12393. this._renderingMesh.render(this);
  12394. };
  12395. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12396. if (!this._linesIndexBuffer) {
  12397. var linesIndices = [];
  12398. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12399. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12400. }
  12401. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12402. this.linesIndexCount = linesIndices.length;
  12403. }
  12404. return this._linesIndexBuffer;
  12405. };
  12406. SubMesh.prototype.canIntersects = function (ray) {
  12407. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12408. };
  12409. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12410. var intersectInfo = null;
  12411. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12412. var p0 = positions[indices[index]];
  12413. var p1 = positions[indices[index + 1]];
  12414. var p2 = positions[indices[index + 2]];
  12415. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12416. if (currentIntersectInfo) {
  12417. if (currentIntersectInfo.distance < 0) {
  12418. continue;
  12419. }
  12420. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12421. intersectInfo = currentIntersectInfo;
  12422. intersectInfo.faceId = index / 3;
  12423. if (fastCheck) {
  12424. break;
  12425. }
  12426. }
  12427. }
  12428. }
  12429. return intersectInfo;
  12430. };
  12431. // Clone
  12432. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12433. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12434. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12435. return result;
  12436. };
  12437. // Dispose
  12438. SubMesh.prototype.dispose = function () {
  12439. if (this._linesIndexBuffer) {
  12440. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12441. this._linesIndexBuffer = null;
  12442. }
  12443. // Remove from mesh
  12444. var index = this._mesh.subMeshes.indexOf(this);
  12445. this._mesh.subMeshes.splice(index, 1);
  12446. };
  12447. // Statics
  12448. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12449. var minVertexIndex = Number.MAX_VALUE;
  12450. var maxVertexIndex = -Number.MAX_VALUE;
  12451. renderingMesh = renderingMesh || mesh;
  12452. var indices = renderingMesh.getIndices();
  12453. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12454. var vertexIndex = indices[index];
  12455. if (vertexIndex < minVertexIndex)
  12456. minVertexIndex = vertexIndex;
  12457. if (vertexIndex > maxVertexIndex)
  12458. maxVertexIndex = vertexIndex;
  12459. }
  12460. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12461. };
  12462. return SubMesh;
  12463. })();
  12464. BABYLON.SubMesh = SubMesh;
  12465. })(BABYLON || (BABYLON = {}));
  12466. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12467. (function (BABYLON) {
  12468. var BaseTexture = (function () {
  12469. function BaseTexture(scene) {
  12470. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12471. this.hasAlpha = false;
  12472. this.getAlphaFromRGB = false;
  12473. this.level = 1;
  12474. this.isCube = false;
  12475. this.isRenderTarget = false;
  12476. this.animations = new Array();
  12477. this.coordinatesIndex = 0;
  12478. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12479. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12480. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12481. this.anisotropicFilteringLevel = 4;
  12482. this._scene = scene;
  12483. this._scene.textures.push(this);
  12484. }
  12485. BaseTexture.prototype.getScene = function () {
  12486. return this._scene;
  12487. };
  12488. BaseTexture.prototype.getTextureMatrix = function () {
  12489. return null;
  12490. };
  12491. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12492. return null;
  12493. };
  12494. BaseTexture.prototype.getInternalTexture = function () {
  12495. return this._texture;
  12496. };
  12497. BaseTexture.prototype.isReady = function () {
  12498. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12499. return true;
  12500. }
  12501. if (this._texture) {
  12502. return this._texture.isReady;
  12503. }
  12504. return false;
  12505. };
  12506. BaseTexture.prototype.getSize = function () {
  12507. if (this._texture._width) {
  12508. return { width: this._texture._width, height: this._texture._height };
  12509. }
  12510. if (this._texture._size) {
  12511. return { width: this._texture._size, height: this._texture._size };
  12512. }
  12513. return { width: 0, height: 0 };
  12514. };
  12515. BaseTexture.prototype.getBaseSize = function () {
  12516. if (!this.isReady())
  12517. return { width: 0, height: 0 };
  12518. if (this._texture._size) {
  12519. return { width: this._texture._size, height: this._texture._size };
  12520. }
  12521. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12522. };
  12523. BaseTexture.prototype.scale = function (ratio) {
  12524. };
  12525. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12526. get: function () {
  12527. return false;
  12528. },
  12529. enumerable: true,
  12530. configurable: true
  12531. });
  12532. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12533. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12534. for (var index = 0; index < texturesCache.length; index++) {
  12535. var texturesCacheEntry = texturesCache[index];
  12536. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12537. texturesCache.splice(index, 1);
  12538. return;
  12539. }
  12540. }
  12541. };
  12542. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12543. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12544. for (var index = 0; index < texturesCache.length; index++) {
  12545. var texturesCacheEntry = texturesCache[index];
  12546. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12547. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12548. texturesCacheEntry.references++;
  12549. return texturesCacheEntry;
  12550. }
  12551. }
  12552. }
  12553. return null;
  12554. };
  12555. BaseTexture.prototype.delayLoad = function () {
  12556. };
  12557. BaseTexture.prototype.releaseInternalTexture = function () {
  12558. if (!this._texture) {
  12559. return;
  12560. }
  12561. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12562. this._texture.references--;
  12563. // Final reference ?
  12564. if (this._texture.references === 0) {
  12565. var index = texturesCache.indexOf(this._texture);
  12566. texturesCache.splice(index, 1);
  12567. this._scene.getEngine()._releaseTexture(this._texture);
  12568. delete this._texture;
  12569. }
  12570. };
  12571. BaseTexture.prototype.clone = function () {
  12572. return null;
  12573. };
  12574. BaseTexture.prototype.dispose = function () {
  12575. // Remove from scene
  12576. var index = this._scene.textures.indexOf(this);
  12577. if (index >= 0) {
  12578. this._scene.textures.splice(index, 1);
  12579. }
  12580. if (this._texture === undefined) {
  12581. return;
  12582. }
  12583. this.releaseInternalTexture();
  12584. // Callback
  12585. if (this.onDispose) {
  12586. this.onDispose();
  12587. }
  12588. };
  12589. return BaseTexture;
  12590. })();
  12591. BABYLON.BaseTexture = BaseTexture;
  12592. })(BABYLON || (BABYLON = {}));
  12593. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12594. (function (BABYLON) {
  12595. var RenderingGroup = (function () {
  12596. function RenderingGroup(index, scene) {
  12597. this.index = index;
  12598. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12599. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12600. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12601. this._scene = scene;
  12602. }
  12603. RenderingGroup.prototype.render = function (customRenderFunction) {
  12604. if (customRenderFunction) {
  12605. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12606. return true;
  12607. }
  12608. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12609. return false;
  12610. }
  12611. var engine = this._scene.getEngine();
  12612. // Opaque
  12613. var subIndex;
  12614. var submesh;
  12615. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12616. submesh = this._opaqueSubMeshes.data[subIndex];
  12617. submesh.render();
  12618. }
  12619. // Alpha test
  12620. engine.setAlphaTesting(true);
  12621. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12622. submesh = this._alphaTestSubMeshes.data[subIndex];
  12623. submesh.render();
  12624. }
  12625. engine.setAlphaTesting(false);
  12626. // Transparent
  12627. if (this._transparentSubMeshes.length) {
  12628. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12629. submesh = this._transparentSubMeshes.data[subIndex];
  12630. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12631. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12632. }
  12633. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12634. sortedArray.sort(function (a, b) {
  12635. // Alpha index first
  12636. if (a._alphaIndex > b._alphaIndex) {
  12637. return 1;
  12638. }
  12639. if (a._alphaIndex < b._alphaIndex) {
  12640. return -1;
  12641. }
  12642. // Then distance to camera
  12643. if (a._distanceToCamera < b._distanceToCamera) {
  12644. return 1;
  12645. }
  12646. if (a._distanceToCamera > b._distanceToCamera) {
  12647. return -1;
  12648. }
  12649. return 0;
  12650. });
  12651. // Rendering
  12652. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12653. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12654. submesh = sortedArray[subIndex];
  12655. submesh.render();
  12656. }
  12657. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12658. }
  12659. return true;
  12660. };
  12661. RenderingGroup.prototype.prepare = function () {
  12662. this._opaqueSubMeshes.reset();
  12663. this._transparentSubMeshes.reset();
  12664. this._alphaTestSubMeshes.reset();
  12665. };
  12666. RenderingGroup.prototype.dispatch = function (subMesh) {
  12667. var material = subMesh.getMaterial();
  12668. var mesh = subMesh.getMesh();
  12669. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12670. this._transparentSubMeshes.push(subMesh);
  12671. }
  12672. else if (material.needAlphaTesting()) {
  12673. this._alphaTestSubMeshes.push(subMesh);
  12674. }
  12675. else {
  12676. this._opaqueSubMeshes.push(subMesh); // Opaque
  12677. }
  12678. };
  12679. return RenderingGroup;
  12680. })();
  12681. BABYLON.RenderingGroup = RenderingGroup;
  12682. })(BABYLON || (BABYLON = {}));
  12683. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12684. (function (BABYLON) {
  12685. var RenderingManager = (function () {
  12686. function RenderingManager(scene) {
  12687. this._renderingGroups = new Array();
  12688. this._scene = scene;
  12689. }
  12690. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12691. if (this._scene._activeParticleSystems.length === 0) {
  12692. return;
  12693. }
  12694. // Particles
  12695. var beforeParticlesDate = BABYLON.Tools.Now;
  12696. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12697. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12698. if (particleSystem.renderingGroupId !== index) {
  12699. continue;
  12700. }
  12701. this._clearDepthBuffer();
  12702. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12703. this._scene._activeParticles += particleSystem.render();
  12704. }
  12705. }
  12706. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12707. };
  12708. RenderingManager.prototype._renderSprites = function (index) {
  12709. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12710. return;
  12711. }
  12712. // Sprites
  12713. var beforeSpritessDate = BABYLON.Tools.Now;
  12714. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12715. var spriteManager = this._scene.spriteManagers[id];
  12716. if (spriteManager.renderingGroupId === index) {
  12717. this._clearDepthBuffer();
  12718. spriteManager.render();
  12719. }
  12720. }
  12721. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12722. };
  12723. RenderingManager.prototype._clearDepthBuffer = function () {
  12724. if (this._depthBufferAlreadyCleaned) {
  12725. return;
  12726. }
  12727. this._scene.getEngine().clear(0, false, true);
  12728. this._depthBufferAlreadyCleaned = true;
  12729. };
  12730. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12731. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12732. this._depthBufferAlreadyCleaned = false;
  12733. var renderingGroup = this._renderingGroups[index];
  12734. var needToStepBack = false;
  12735. if (renderingGroup) {
  12736. this._clearDepthBuffer();
  12737. if (!renderingGroup.render(customRenderFunction)) {
  12738. this._renderingGroups.splice(index, 1);
  12739. needToStepBack = true;
  12740. }
  12741. }
  12742. if (renderSprites) {
  12743. this._renderSprites(index);
  12744. }
  12745. if (renderParticles) {
  12746. this._renderParticles(index, activeMeshes);
  12747. }
  12748. if (needToStepBack) {
  12749. index--;
  12750. }
  12751. }
  12752. };
  12753. RenderingManager.prototype.reset = function () {
  12754. for (var index in this._renderingGroups) {
  12755. var renderingGroup = this._renderingGroups[index];
  12756. renderingGroup.prepare();
  12757. }
  12758. };
  12759. RenderingManager.prototype.dispatch = function (subMesh) {
  12760. var mesh = subMesh.getMesh();
  12761. var renderingGroupId = mesh.renderingGroupId || 0;
  12762. if (!this._renderingGroups[renderingGroupId]) {
  12763. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12764. }
  12765. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12766. };
  12767. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12768. return RenderingManager;
  12769. })();
  12770. BABYLON.RenderingManager = RenderingManager;
  12771. })(BABYLON || (BABYLON = {}));
  12772. //# sourceMappingURL=babylon.renderingManager.js.map
  12773. var BABYLON;
  12774. (function (BABYLON) {
  12775. var Texture = (function (_super) {
  12776. __extends(Texture, _super);
  12777. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12778. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12779. if (onLoad === void 0) { onLoad = null; }
  12780. if (onError === void 0) { onError = null; }
  12781. if (buffer === void 0) { buffer = null; }
  12782. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12783. _super.call(this, scene);
  12784. this.uOffset = 0;
  12785. this.vOffset = 0;
  12786. this.uScale = 1.0;
  12787. this.vScale = 1.0;
  12788. this.uAng = 0;
  12789. this.vAng = 0;
  12790. this.wAng = 0;
  12791. this.name = url;
  12792. this.url = url;
  12793. this._noMipmap = noMipmap;
  12794. this._invertY = invertY;
  12795. this._samplingMode = samplingMode;
  12796. this._buffer = buffer;
  12797. this._deleteBuffer = deleteBuffer;
  12798. if (!url) {
  12799. return;
  12800. }
  12801. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12802. if (!this._texture) {
  12803. if (!scene.useDelayedTextureLoading) {
  12804. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12805. if (deleteBuffer) {
  12806. delete this._buffer;
  12807. }
  12808. }
  12809. else {
  12810. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12811. }
  12812. }
  12813. }
  12814. Texture.prototype.delayLoad = function () {
  12815. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12816. return;
  12817. }
  12818. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12819. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12820. if (!this._texture) {
  12821. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12822. if (this._deleteBuffer) {
  12823. delete this._buffer;
  12824. }
  12825. }
  12826. };
  12827. Texture.prototype.updateSamplingMode = function (samplingMode) {
  12828. if (!this._texture) {
  12829. return;
  12830. }
  12831. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  12832. };
  12833. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12834. x -= this.uOffset + 0.5;
  12835. y -= this.vOffset + 0.5;
  12836. z -= 0.5;
  12837. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12838. t.x *= this.uScale;
  12839. t.y *= this.vScale;
  12840. t.x += 0.5;
  12841. t.y += 0.5;
  12842. t.z += 0.5;
  12843. };
  12844. Texture.prototype.getTextureMatrix = function () {
  12845. 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) {
  12846. return this._cachedTextureMatrix;
  12847. }
  12848. this._cachedUOffset = this.uOffset;
  12849. this._cachedVOffset = this.vOffset;
  12850. this._cachedUScale = this.uScale;
  12851. this._cachedVScale = this.vScale;
  12852. this._cachedUAng = this.uAng;
  12853. this._cachedVAng = this.vAng;
  12854. this._cachedWAng = this.wAng;
  12855. if (!this._cachedTextureMatrix) {
  12856. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12857. this._rowGenerationMatrix = new BABYLON.Matrix();
  12858. this._t0 = BABYLON.Vector3.Zero();
  12859. this._t1 = BABYLON.Vector3.Zero();
  12860. this._t2 = BABYLON.Vector3.Zero();
  12861. }
  12862. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12863. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12864. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12865. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12866. this._t1.subtractInPlace(this._t0);
  12867. this._t2.subtractInPlace(this._t0);
  12868. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12869. this._cachedTextureMatrix.m[0] = this._t1.x;
  12870. this._cachedTextureMatrix.m[1] = this._t1.y;
  12871. this._cachedTextureMatrix.m[2] = this._t1.z;
  12872. this._cachedTextureMatrix.m[4] = this._t2.x;
  12873. this._cachedTextureMatrix.m[5] = this._t2.y;
  12874. this._cachedTextureMatrix.m[6] = this._t2.z;
  12875. this._cachedTextureMatrix.m[8] = this._t0.x;
  12876. this._cachedTextureMatrix.m[9] = this._t0.y;
  12877. this._cachedTextureMatrix.m[10] = this._t0.z;
  12878. return this._cachedTextureMatrix;
  12879. };
  12880. Texture.prototype.getReflectionTextureMatrix = function () {
  12881. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12882. return this._cachedTextureMatrix;
  12883. }
  12884. if (!this._cachedTextureMatrix) {
  12885. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12886. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12887. }
  12888. this._cachedCoordinatesMode = this.coordinatesMode;
  12889. switch (this.coordinatesMode) {
  12890. case Texture.SPHERICAL_MODE:
  12891. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12892. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12893. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12894. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12895. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12896. break;
  12897. case Texture.PLANAR_MODE:
  12898. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12899. this._cachedTextureMatrix[0] = this.uScale;
  12900. this._cachedTextureMatrix[5] = this.vScale;
  12901. this._cachedTextureMatrix[12] = this.uOffset;
  12902. this._cachedTextureMatrix[13] = this.vOffset;
  12903. break;
  12904. case Texture.PROJECTION_MODE:
  12905. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12906. this._projectionModeMatrix.m[0] = 0.5;
  12907. this._projectionModeMatrix.m[5] = -0.5;
  12908. this._projectionModeMatrix.m[10] = 0.0;
  12909. this._projectionModeMatrix.m[12] = 0.5;
  12910. this._projectionModeMatrix.m[13] = 0.5;
  12911. this._projectionModeMatrix.m[14] = 1.0;
  12912. this._projectionModeMatrix.m[15] = 1.0;
  12913. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12914. break;
  12915. default:
  12916. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12917. break;
  12918. }
  12919. return this._cachedTextureMatrix;
  12920. };
  12921. Texture.prototype.clone = function () {
  12922. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12923. // Base texture
  12924. newTexture.hasAlpha = this.hasAlpha;
  12925. newTexture.level = this.level;
  12926. newTexture.wrapU = this.wrapU;
  12927. newTexture.wrapV = this.wrapV;
  12928. newTexture.coordinatesIndex = this.coordinatesIndex;
  12929. newTexture.coordinatesMode = this.coordinatesMode;
  12930. // Texture
  12931. newTexture.uOffset = this.uOffset;
  12932. newTexture.vOffset = this.vOffset;
  12933. newTexture.uScale = this.uScale;
  12934. newTexture.vScale = this.vScale;
  12935. newTexture.uAng = this.uAng;
  12936. newTexture.vAng = this.vAng;
  12937. newTexture.wAng = this.wAng;
  12938. return newTexture;
  12939. };
  12940. // Statics
  12941. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12942. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12943. if (onLoad === void 0) { onLoad = null; }
  12944. if (onError === void 0) { onError = null; }
  12945. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12946. };
  12947. // Constants
  12948. Texture.NEAREST_SAMPLINGMODE = 1;
  12949. Texture.BILINEAR_SAMPLINGMODE = 2;
  12950. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12951. Texture.EXPLICIT_MODE = 0;
  12952. Texture.SPHERICAL_MODE = 1;
  12953. Texture.PLANAR_MODE = 2;
  12954. Texture.CUBIC_MODE = 3;
  12955. Texture.PROJECTION_MODE = 4;
  12956. Texture.SKYBOX_MODE = 5;
  12957. Texture.CLAMP_ADDRESSMODE = 0;
  12958. Texture.WRAP_ADDRESSMODE = 1;
  12959. Texture.MIRROR_ADDRESSMODE = 2;
  12960. return Texture;
  12961. })(BABYLON.BaseTexture);
  12962. BABYLON.Texture = Texture;
  12963. })(BABYLON || (BABYLON = {}));
  12964. //# sourceMappingURL=babylon.texture.js.map
  12965. var BABYLON;
  12966. (function (BABYLON) {
  12967. var CubeTexture = (function (_super) {
  12968. __extends(CubeTexture, _super);
  12969. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12970. _super.call(this, scene);
  12971. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12972. this.name = rootUrl;
  12973. this.url = rootUrl;
  12974. this._noMipmap = noMipmap;
  12975. this.hasAlpha = false;
  12976. this._texture = this._getFromCache(rootUrl, noMipmap);
  12977. if (!extensions) {
  12978. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12979. }
  12980. this._extensions = extensions;
  12981. if (!this._texture) {
  12982. if (!scene.useDelayedTextureLoading) {
  12983. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12984. }
  12985. else {
  12986. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12987. }
  12988. }
  12989. this.isCube = true;
  12990. this._textureMatrix = BABYLON.Matrix.Identity();
  12991. }
  12992. CubeTexture.prototype.clone = function () {
  12993. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12994. // Base texture
  12995. newTexture.level = this.level;
  12996. newTexture.wrapU = this.wrapU;
  12997. newTexture.wrapV = this.wrapV;
  12998. newTexture.coordinatesIndex = this.coordinatesIndex;
  12999. newTexture.coordinatesMode = this.coordinatesMode;
  13000. return newTexture;
  13001. };
  13002. // Methods
  13003. CubeTexture.prototype.delayLoad = function () {
  13004. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13005. return;
  13006. }
  13007. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13008. this._texture = this._getFromCache(this.url, this._noMipmap);
  13009. if (!this._texture) {
  13010. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  13011. }
  13012. };
  13013. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  13014. return this._textureMatrix;
  13015. };
  13016. return CubeTexture;
  13017. })(BABYLON.BaseTexture);
  13018. BABYLON.CubeTexture = CubeTexture;
  13019. })(BABYLON || (BABYLON = {}));
  13020. //# sourceMappingURL=babylon.cubeTexture.js.map
  13021. var BABYLON;
  13022. (function (BABYLON) {
  13023. var RenderTargetTexture = (function (_super) {
  13024. __extends(RenderTargetTexture, _super);
  13025. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  13026. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  13027. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  13028. _super.call(this, null, scene, !generateMipMaps);
  13029. this.renderList = new Array();
  13030. this.renderParticles = true;
  13031. this.renderSprites = false;
  13032. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  13033. this._currentRefreshId = -1;
  13034. this._refreshRate = 1;
  13035. this.name = name;
  13036. this.isRenderTarget = true;
  13037. this._size = size;
  13038. this._generateMipMaps = generateMipMaps;
  13039. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  13040. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  13041. // Rendering groups
  13042. this._renderingManager = new BABYLON.RenderingManager(scene);
  13043. }
  13044. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  13045. this._currentRefreshId = -1;
  13046. };
  13047. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  13048. get: function () {
  13049. return this._refreshRate;
  13050. },
  13051. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13052. set: function (value) {
  13053. this._refreshRate = value;
  13054. this.resetRefreshCounter();
  13055. },
  13056. enumerable: true,
  13057. configurable: true
  13058. });
  13059. RenderTargetTexture.prototype._shouldRender = function () {
  13060. if (this._currentRefreshId === -1) {
  13061. this._currentRefreshId = 1;
  13062. return true;
  13063. }
  13064. if (this.refreshRate === this._currentRefreshId) {
  13065. this._currentRefreshId = 1;
  13066. return true;
  13067. }
  13068. this._currentRefreshId++;
  13069. return false;
  13070. };
  13071. RenderTargetTexture.prototype.isReady = function () {
  13072. if (!this.getScene().renderTargetsEnabled) {
  13073. return false;
  13074. }
  13075. return _super.prototype.isReady.call(this);
  13076. };
  13077. RenderTargetTexture.prototype.getRenderSize = function () {
  13078. return this._size;
  13079. };
  13080. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  13081. get: function () {
  13082. return true;
  13083. },
  13084. enumerable: true,
  13085. configurable: true
  13086. });
  13087. RenderTargetTexture.prototype.scale = function (ratio) {
  13088. var newSize = this._size * ratio;
  13089. this.resize(newSize, this._generateMipMaps);
  13090. };
  13091. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  13092. this.releaseInternalTexture();
  13093. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13094. };
  13095. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  13096. var scene = this.getScene();
  13097. var engine = scene.getEngine();
  13098. if (this._waitingRenderList) {
  13099. this.renderList = [];
  13100. for (var index = 0; index < this._waitingRenderList.length; index++) {
  13101. var id = this._waitingRenderList[index];
  13102. this.renderList.push(scene.getMeshByID(id));
  13103. }
  13104. delete this._waitingRenderList;
  13105. }
  13106. if (this.renderList && this.renderList.length === 0) {
  13107. return;
  13108. }
  13109. // Bind
  13110. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  13111. engine.bindFramebuffer(this._texture);
  13112. }
  13113. this._renderingManager.reset();
  13114. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  13115. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  13116. var mesh = currentRenderList[meshIndex];
  13117. if (mesh) {
  13118. if (!mesh.isReady()) {
  13119. // Reset _currentRefreshId
  13120. this.resetRefreshCounter();
  13121. continue;
  13122. }
  13123. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  13124. mesh._activate(scene.getRenderId());
  13125. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13126. var subMesh = mesh.subMeshes[subIndex];
  13127. scene._activeVertices += subMesh.indexCount;
  13128. this._renderingManager.dispatch(subMesh);
  13129. }
  13130. }
  13131. }
  13132. }
  13133. if (this.onBeforeRender) {
  13134. this.onBeforeRender();
  13135. }
  13136. // Clear
  13137. if (this.onClear) {
  13138. this.onClear(engine);
  13139. }
  13140. else {
  13141. engine.clear(scene.clearColor, true, true);
  13142. }
  13143. if (!this._doNotChangeAspectRatio) {
  13144. scene.updateTransformMatrix(true);
  13145. }
  13146. // Render
  13147. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  13148. if (useCameraPostProcess) {
  13149. scene.postProcessManager._finalizeFrame(false, this._texture);
  13150. }
  13151. if (!this._doNotChangeAspectRatio) {
  13152. scene.updateTransformMatrix(true);
  13153. }
  13154. if (this.onAfterRender) {
  13155. this.onAfterRender();
  13156. }
  13157. // Dump ?
  13158. if (dumpForDebug) {
  13159. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  13160. }
  13161. // Unbind
  13162. engine.unBindFramebuffer(this._texture);
  13163. if (this.onAfterUnbind) {
  13164. this.onAfterUnbind();
  13165. }
  13166. };
  13167. RenderTargetTexture.prototype.clone = function () {
  13168. var textureSize = this.getSize();
  13169. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13170. // Base texture
  13171. newTexture.hasAlpha = this.hasAlpha;
  13172. newTexture.level = this.level;
  13173. // RenderTarget Texture
  13174. newTexture.coordinatesMode = this.coordinatesMode;
  13175. newTexture.renderList = this.renderList.slice(0);
  13176. return newTexture;
  13177. };
  13178. return RenderTargetTexture;
  13179. })(BABYLON.Texture);
  13180. BABYLON.RenderTargetTexture = RenderTargetTexture;
  13181. })(BABYLON || (BABYLON = {}));
  13182. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  13183. var BABYLON;
  13184. (function (BABYLON) {
  13185. var ProceduralTexture = (function (_super) {
  13186. __extends(ProceduralTexture, _super);
  13187. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  13188. if (generateMipMaps === void 0) { generateMipMaps = true; }
  13189. _super.call(this, null, scene, !generateMipMaps);
  13190. this._currentRefreshId = -1;
  13191. this._refreshRate = 1;
  13192. this._vertexDeclaration = [2];
  13193. this._vertexStrideSize = 2 * 4;
  13194. this._uniforms = new Array();
  13195. this._samplers = new Array();
  13196. this._textures = new Array();
  13197. this._floats = new Array();
  13198. this._floatsArrays = {};
  13199. this._colors3 = new Array();
  13200. this._colors4 = new Array();
  13201. this._vectors2 = new Array();
  13202. this._vectors3 = new Array();
  13203. this._matrices = new Array();
  13204. this._fallbackTextureUsed = false;
  13205. scene._proceduralTextures.push(this);
  13206. this.name = name;
  13207. this.isRenderTarget = true;
  13208. this._size = size;
  13209. this._generateMipMaps = generateMipMaps;
  13210. this.setFragment(fragment);
  13211. this._fallbackTexture = fallbackTexture;
  13212. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  13213. // VBO
  13214. var vertices = [];
  13215. vertices.push(1, 1);
  13216. vertices.push(-1, 1);
  13217. vertices.push(-1, -1);
  13218. vertices.push(1, -1);
  13219. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13220. // Indices
  13221. var indices = [];
  13222. indices.push(0);
  13223. indices.push(1);
  13224. indices.push(2);
  13225. indices.push(0);
  13226. indices.push(2);
  13227. indices.push(3);
  13228. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13229. }
  13230. ProceduralTexture.prototype.reset = function () {
  13231. if (this._effect === undefined) {
  13232. return;
  13233. }
  13234. var engine = this.getScene().getEngine();
  13235. engine._releaseEffect(this._effect);
  13236. };
  13237. ProceduralTexture.prototype.isReady = function () {
  13238. var _this = this;
  13239. var engine = this.getScene().getEngine();
  13240. var shaders;
  13241. if (!this._fragment) {
  13242. return false;
  13243. }
  13244. if (this._fallbackTextureUsed) {
  13245. return true;
  13246. }
  13247. if (this._fragment.fragmentElement !== undefined) {
  13248. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  13249. }
  13250. else {
  13251. shaders = { vertex: "procedural", fragment: this._fragment };
  13252. }
  13253. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  13254. _this.releaseInternalTexture();
  13255. if (_this._fallbackTexture) {
  13256. _this._texture = _this._fallbackTexture._texture;
  13257. _this._texture.references++;
  13258. }
  13259. _this._fallbackTextureUsed = true;
  13260. });
  13261. return this._effect.isReady();
  13262. };
  13263. ProceduralTexture.prototype.resetRefreshCounter = function () {
  13264. this._currentRefreshId = -1;
  13265. };
  13266. ProceduralTexture.prototype.setFragment = function (fragment) {
  13267. this._fragment = fragment;
  13268. };
  13269. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  13270. get: function () {
  13271. return this._refreshRate;
  13272. },
  13273. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13274. set: function (value) {
  13275. this._refreshRate = value;
  13276. this.resetRefreshCounter();
  13277. },
  13278. enumerable: true,
  13279. configurable: true
  13280. });
  13281. ProceduralTexture.prototype._shouldRender = function () {
  13282. if (!this.isReady() || !this._texture) {
  13283. return false;
  13284. }
  13285. if (this._fallbackTextureUsed) {
  13286. return false;
  13287. }
  13288. if (this._currentRefreshId === -1) {
  13289. this._currentRefreshId = 1;
  13290. return true;
  13291. }
  13292. if (this.refreshRate === this._currentRefreshId) {
  13293. this._currentRefreshId = 1;
  13294. return true;
  13295. }
  13296. this._currentRefreshId++;
  13297. return false;
  13298. };
  13299. ProceduralTexture.prototype.getRenderSize = function () {
  13300. return this._size;
  13301. };
  13302. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13303. if (this._fallbackTextureUsed) {
  13304. return;
  13305. }
  13306. this.releaseInternalTexture();
  13307. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13308. };
  13309. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13310. if (this._uniforms.indexOf(uniformName) === -1) {
  13311. this._uniforms.push(uniformName);
  13312. }
  13313. };
  13314. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13315. if (this._samplers.indexOf(name) === -1) {
  13316. this._samplers.push(name);
  13317. }
  13318. this._textures[name] = texture;
  13319. return this;
  13320. };
  13321. ProceduralTexture.prototype.setFloat = function (name, value) {
  13322. this._checkUniform(name);
  13323. this._floats[name] = value;
  13324. return this;
  13325. };
  13326. ProceduralTexture.prototype.setFloats = function (name, value) {
  13327. this._checkUniform(name);
  13328. this._floatsArrays[name] = value;
  13329. return this;
  13330. };
  13331. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13332. this._checkUniform(name);
  13333. this._colors3[name] = value;
  13334. return this;
  13335. };
  13336. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13337. this._checkUniform(name);
  13338. this._colors4[name] = value;
  13339. return this;
  13340. };
  13341. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13342. this._checkUniform(name);
  13343. this._vectors2[name] = value;
  13344. return this;
  13345. };
  13346. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13347. this._checkUniform(name);
  13348. this._vectors3[name] = value;
  13349. return this;
  13350. };
  13351. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13352. this._checkUniform(name);
  13353. this._matrices[name] = value;
  13354. return this;
  13355. };
  13356. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13357. var scene = this.getScene();
  13358. var engine = scene.getEngine();
  13359. engine.bindFramebuffer(this._texture);
  13360. // Clear
  13361. engine.clear(scene.clearColor, true, true);
  13362. // Render
  13363. engine.enableEffect(this._effect);
  13364. engine.setState(false);
  13365. for (var name in this._textures) {
  13366. this._effect.setTexture(name, this._textures[name]);
  13367. }
  13368. for (name in this._floats) {
  13369. this._effect.setFloat(name, this._floats[name]);
  13370. }
  13371. for (name in this._floatsArrays) {
  13372. this._effect.setArray(name, this._floatsArrays[name]);
  13373. }
  13374. for (name in this._colors3) {
  13375. this._effect.setColor3(name, this._colors3[name]);
  13376. }
  13377. for (name in this._colors4) {
  13378. var color = this._colors4[name];
  13379. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13380. }
  13381. for (name in this._vectors2) {
  13382. this._effect.setVector2(name, this._vectors2[name]);
  13383. }
  13384. for (name in this._vectors3) {
  13385. this._effect.setVector3(name, this._vectors3[name]);
  13386. }
  13387. for (name in this._matrices) {
  13388. this._effect.setMatrix(name, this._matrices[name]);
  13389. }
  13390. // VBOs
  13391. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13392. // Draw order
  13393. engine.draw(true, 0, 6);
  13394. // Unbind
  13395. engine.unBindFramebuffer(this._texture);
  13396. };
  13397. ProceduralTexture.prototype.clone = function () {
  13398. var textureSize = this.getSize();
  13399. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13400. // Base texture
  13401. newTexture.hasAlpha = this.hasAlpha;
  13402. newTexture.level = this.level;
  13403. // RenderTarget Texture
  13404. newTexture.coordinatesMode = this.coordinatesMode;
  13405. return newTexture;
  13406. };
  13407. ProceduralTexture.prototype.dispose = function () {
  13408. var index = this.getScene()._proceduralTextures.indexOf(this);
  13409. if (index >= 0) {
  13410. this.getScene()._proceduralTextures.splice(index, 1);
  13411. }
  13412. _super.prototype.dispose.call(this);
  13413. };
  13414. return ProceduralTexture;
  13415. })(BABYLON.Texture);
  13416. BABYLON.ProceduralTexture = ProceduralTexture;
  13417. })(BABYLON || (BABYLON = {}));
  13418. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13419. var BABYLON;
  13420. (function (BABYLON) {
  13421. var WoodProceduralTexture = (function (_super) {
  13422. __extends(WoodProceduralTexture, _super);
  13423. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13424. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13425. this._ampScale = 100.0;
  13426. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13427. this.updateShaderUniforms();
  13428. this.refreshRate = 0;
  13429. }
  13430. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13431. this.setFloat("ampScale", this._ampScale);
  13432. this.setColor3("woodColor", this._woodColor);
  13433. };
  13434. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13435. get: function () {
  13436. return this._ampScale;
  13437. },
  13438. set: function (value) {
  13439. this._ampScale = value;
  13440. this.updateShaderUniforms();
  13441. },
  13442. enumerable: true,
  13443. configurable: true
  13444. });
  13445. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13446. get: function () {
  13447. return this._woodColor;
  13448. },
  13449. set: function (value) {
  13450. this._woodColor = value;
  13451. this.updateShaderUniforms();
  13452. },
  13453. enumerable: true,
  13454. configurable: true
  13455. });
  13456. return WoodProceduralTexture;
  13457. })(BABYLON.ProceduralTexture);
  13458. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13459. var FireProceduralTexture = (function (_super) {
  13460. __extends(FireProceduralTexture, _super);
  13461. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13462. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13463. this._time = 0.0;
  13464. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13465. this._autoGenerateTime = true;
  13466. this._alphaThreshold = 0.5;
  13467. this._fireColors = FireProceduralTexture.RedFireColors;
  13468. this.updateShaderUniforms();
  13469. this.refreshRate = 1;
  13470. }
  13471. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13472. this.setFloat("time", this._time);
  13473. this.setVector2("speed", this._speed);
  13474. this.setColor3("c1", this._fireColors[0]);
  13475. this.setColor3("c2", this._fireColors[1]);
  13476. this.setColor3("c3", this._fireColors[2]);
  13477. this.setColor3("c4", this._fireColors[3]);
  13478. this.setColor3("c5", this._fireColors[4]);
  13479. this.setColor3("c6", this._fireColors[5]);
  13480. this.setFloat("alphaThreshold", this._alphaThreshold);
  13481. };
  13482. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13483. if (this._autoGenerateTime) {
  13484. this._time += this.getScene().getAnimationRatio() * 0.03;
  13485. this.updateShaderUniforms();
  13486. }
  13487. _super.prototype.render.call(this, useCameraPostProcess);
  13488. };
  13489. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13490. get: function () {
  13491. return [
  13492. new BABYLON.Color3(0.5, 0.0, 1.0),
  13493. new BABYLON.Color3(0.9, 0.0, 1.0),
  13494. new BABYLON.Color3(0.2, 0.0, 1.0),
  13495. new BABYLON.Color3(1.0, 0.9, 1.0),
  13496. new BABYLON.Color3(0.1, 0.1, 1.0),
  13497. new BABYLON.Color3(0.9, 0.9, 1.0)
  13498. ];
  13499. },
  13500. enumerable: true,
  13501. configurable: true
  13502. });
  13503. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13504. get: function () {
  13505. return [
  13506. new BABYLON.Color3(0.5, 1.0, 0.0),
  13507. new BABYLON.Color3(0.5, 1.0, 0.0),
  13508. new BABYLON.Color3(0.3, 0.4, 0.0),
  13509. new BABYLON.Color3(0.5, 1.0, 0.0),
  13510. new BABYLON.Color3(0.2, 0.0, 0.0),
  13511. new BABYLON.Color3(0.5, 1.0, 0.0)
  13512. ];
  13513. },
  13514. enumerable: true,
  13515. configurable: true
  13516. });
  13517. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13518. get: function () {
  13519. return [
  13520. new BABYLON.Color3(0.5, 0.0, 0.1),
  13521. new BABYLON.Color3(0.9, 0.0, 0.0),
  13522. new BABYLON.Color3(0.2, 0.0, 0.0),
  13523. new BABYLON.Color3(1.0, 0.9, 0.0),
  13524. new BABYLON.Color3(0.1, 0.1, 0.1),
  13525. new BABYLON.Color3(0.9, 0.9, 0.9)
  13526. ];
  13527. },
  13528. enumerable: true,
  13529. configurable: true
  13530. });
  13531. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13532. get: function () {
  13533. return [
  13534. new BABYLON.Color3(0.1, 0.0, 0.5),
  13535. new BABYLON.Color3(0.0, 0.0, 0.5),
  13536. new BABYLON.Color3(0.1, 0.0, 0.2),
  13537. new BABYLON.Color3(0.0, 0.0, 1.0),
  13538. new BABYLON.Color3(0.1, 0.2, 0.3),
  13539. new BABYLON.Color3(0.0, 0.2, 0.9)
  13540. ];
  13541. },
  13542. enumerable: true,
  13543. configurable: true
  13544. });
  13545. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13546. get: function () {
  13547. return this._fireColors;
  13548. },
  13549. set: function (value) {
  13550. this._fireColors = value;
  13551. this.updateShaderUniforms();
  13552. },
  13553. enumerable: true,
  13554. configurable: true
  13555. });
  13556. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13557. get: function () {
  13558. return this._time;
  13559. },
  13560. set: function (value) {
  13561. this._time = value;
  13562. this.updateShaderUniforms();
  13563. },
  13564. enumerable: true,
  13565. configurable: true
  13566. });
  13567. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13568. get: function () {
  13569. return this._speed;
  13570. },
  13571. set: function (value) {
  13572. this._speed = value;
  13573. this.updateShaderUniforms();
  13574. },
  13575. enumerable: true,
  13576. configurable: true
  13577. });
  13578. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13579. get: function () {
  13580. return this._alphaThreshold;
  13581. },
  13582. set: function (value) {
  13583. this._alphaThreshold = value;
  13584. this.updateShaderUniforms();
  13585. },
  13586. enumerable: true,
  13587. configurable: true
  13588. });
  13589. return FireProceduralTexture;
  13590. })(BABYLON.ProceduralTexture);
  13591. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13592. var CloudProceduralTexture = (function (_super) {
  13593. __extends(CloudProceduralTexture, _super);
  13594. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13595. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13596. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13597. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13598. this.updateShaderUniforms();
  13599. this.refreshRate = 0;
  13600. }
  13601. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13602. this.setColor3("skyColor", this._skyColor);
  13603. this.setColor3("cloudColor", this._cloudColor);
  13604. };
  13605. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13606. get: function () {
  13607. return this._skyColor;
  13608. },
  13609. set: function (value) {
  13610. this._skyColor = value;
  13611. this.updateShaderUniforms();
  13612. },
  13613. enumerable: true,
  13614. configurable: true
  13615. });
  13616. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13617. get: function () {
  13618. return this._cloudColor;
  13619. },
  13620. set: function (value) {
  13621. this._cloudColor = value;
  13622. this.updateShaderUniforms();
  13623. },
  13624. enumerable: true,
  13625. configurable: true
  13626. });
  13627. return CloudProceduralTexture;
  13628. })(BABYLON.ProceduralTexture);
  13629. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13630. var GrassProceduralTexture = (function (_super) {
  13631. __extends(GrassProceduralTexture, _super);
  13632. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13633. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13634. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13635. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13636. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13637. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13638. this._grassColors = [
  13639. new BABYLON.Color3(0.29, 0.38, 0.02),
  13640. new BABYLON.Color3(0.36, 0.49, 0.09),
  13641. new BABYLON.Color3(0.51, 0.6, 0.28)
  13642. ];
  13643. this.updateShaderUniforms();
  13644. this.refreshRate = 0;
  13645. }
  13646. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13647. this.setColor3("herb1Color", this._grassColors[0]);
  13648. this.setColor3("herb2Color", this._grassColors[1]);
  13649. this.setColor3("herb3Color", this._grassColors[2]);
  13650. this.setColor3("groundColor", this._groundColor);
  13651. };
  13652. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13653. get: function () {
  13654. return this._grassColors;
  13655. },
  13656. set: function (value) {
  13657. this._grassColors = value;
  13658. this.updateShaderUniforms();
  13659. },
  13660. enumerable: true,
  13661. configurable: true
  13662. });
  13663. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13664. get: function () {
  13665. return this._groundColor;
  13666. },
  13667. set: function (value) {
  13668. this.groundColor = value;
  13669. this.updateShaderUniforms();
  13670. },
  13671. enumerable: true,
  13672. configurable: true
  13673. });
  13674. return GrassProceduralTexture;
  13675. })(BABYLON.ProceduralTexture);
  13676. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13677. var RoadProceduralTexture = (function (_super) {
  13678. __extends(RoadProceduralTexture, _super);
  13679. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13680. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13681. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13682. this.updateShaderUniforms();
  13683. this.refreshRate = 0;
  13684. }
  13685. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13686. this.setColor3("roadColor", this._roadColor);
  13687. };
  13688. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13689. get: function () {
  13690. return this._roadColor;
  13691. },
  13692. set: function (value) {
  13693. this._roadColor = value;
  13694. this.updateShaderUniforms();
  13695. },
  13696. enumerable: true,
  13697. configurable: true
  13698. });
  13699. return RoadProceduralTexture;
  13700. })(BABYLON.ProceduralTexture);
  13701. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13702. var BrickProceduralTexture = (function (_super) {
  13703. __extends(BrickProceduralTexture, _super);
  13704. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13705. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13706. this._numberOfBricksHeight = 15;
  13707. this._numberOfBricksWidth = 5;
  13708. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13709. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13710. this.updateShaderUniforms();
  13711. this.refreshRate = 0;
  13712. }
  13713. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13714. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13715. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13716. this.setColor3("brickColor", this._brickColor);
  13717. this.setColor3("jointColor", this._jointColor);
  13718. };
  13719. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13720. get: function () {
  13721. return this._numberOfBricksHeight;
  13722. },
  13723. set: function (value) {
  13724. this._numberOfBricksHeight = value;
  13725. this.updateShaderUniforms();
  13726. },
  13727. enumerable: true,
  13728. configurable: true
  13729. });
  13730. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13731. get: function () {
  13732. return this._numberOfBricksWidth;
  13733. },
  13734. set: function (value) {
  13735. this._numberOfBricksHeight = value;
  13736. this.updateShaderUniforms();
  13737. },
  13738. enumerable: true,
  13739. configurable: true
  13740. });
  13741. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13742. get: function () {
  13743. return this._jointColor;
  13744. },
  13745. set: function (value) {
  13746. this._jointColor = value;
  13747. this.updateShaderUniforms();
  13748. },
  13749. enumerable: true,
  13750. configurable: true
  13751. });
  13752. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13753. get: function () {
  13754. return this._brickColor;
  13755. },
  13756. set: function (value) {
  13757. this._brickColor = value;
  13758. this.updateShaderUniforms();
  13759. },
  13760. enumerable: true,
  13761. configurable: true
  13762. });
  13763. return BrickProceduralTexture;
  13764. })(BABYLON.ProceduralTexture);
  13765. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13766. var MarbleProceduralTexture = (function (_super) {
  13767. __extends(MarbleProceduralTexture, _super);
  13768. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13769. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13770. this._numberOfTilesHeight = 3;
  13771. this._numberOfTilesWidth = 3;
  13772. this._amplitude = 9.0;
  13773. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13774. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13775. this.updateShaderUniforms();
  13776. this.refreshRate = 0;
  13777. }
  13778. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13779. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13780. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13781. this.setFloat("amplitude", this._amplitude);
  13782. this.setColor3("marbleColor", this._marbleColor);
  13783. this.setColor3("jointColor", this._jointColor);
  13784. };
  13785. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13786. get: function () {
  13787. return this._numberOfTilesHeight;
  13788. },
  13789. set: function (value) {
  13790. this._numberOfTilesHeight = value;
  13791. this.updateShaderUniforms();
  13792. },
  13793. enumerable: true,
  13794. configurable: true
  13795. });
  13796. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13797. get: function () {
  13798. return this._numberOfTilesWidth;
  13799. },
  13800. set: function (value) {
  13801. this._numberOfTilesWidth = value;
  13802. this.updateShaderUniforms();
  13803. },
  13804. enumerable: true,
  13805. configurable: true
  13806. });
  13807. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13808. get: function () {
  13809. return this._jointColor;
  13810. },
  13811. set: function (value) {
  13812. this._jointColor = value;
  13813. this.updateShaderUniforms();
  13814. },
  13815. enumerable: true,
  13816. configurable: true
  13817. });
  13818. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13819. get: function () {
  13820. return this._marbleColor;
  13821. },
  13822. set: function (value) {
  13823. this._marbleColor = value;
  13824. this.updateShaderUniforms();
  13825. },
  13826. enumerable: true,
  13827. configurable: true
  13828. });
  13829. return MarbleProceduralTexture;
  13830. })(BABYLON.ProceduralTexture);
  13831. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13832. })(BABYLON || (BABYLON = {}));
  13833. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13834. var BABYLON;
  13835. (function (BABYLON) {
  13836. var CustomProceduralTexture = (function (_super) {
  13837. __extends(CustomProceduralTexture, _super);
  13838. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13839. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13840. this._animate = true;
  13841. this._time = 0;
  13842. this._texturePath = texturePath;
  13843. //Try to load json
  13844. this.loadJson(texturePath);
  13845. this.refreshRate = 1;
  13846. }
  13847. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13848. var _this = this;
  13849. var that = this;
  13850. function noConfigFile() {
  13851. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13852. try {
  13853. that.setFragment(that._texturePath);
  13854. }
  13855. catch (ex) {
  13856. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13857. }
  13858. }
  13859. var configFileUrl = jsonUrl + "/config.json";
  13860. var xhr = new XMLHttpRequest();
  13861. xhr.open("GET", configFileUrl, true);
  13862. xhr.addEventListener("load", function () {
  13863. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13864. try {
  13865. _this._config = JSON.parse(xhr.response);
  13866. _this.updateShaderUniforms();
  13867. _this.updateTextures();
  13868. _this.setFragment(_this._texturePath + "/custom");
  13869. _this._animate = _this._config.animate;
  13870. _this.refreshRate = _this._config.refreshrate;
  13871. }
  13872. catch (ex) {
  13873. noConfigFile();
  13874. }
  13875. }
  13876. else {
  13877. noConfigFile();
  13878. }
  13879. }, false);
  13880. xhr.addEventListener("error", function () {
  13881. noConfigFile();
  13882. }, false);
  13883. try {
  13884. xhr.send();
  13885. }
  13886. catch (ex) {
  13887. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13888. }
  13889. };
  13890. CustomProceduralTexture.prototype.isReady = function () {
  13891. if (!_super.prototype.isReady.call(this)) {
  13892. return false;
  13893. }
  13894. for (var name in this._textures) {
  13895. var texture = this._textures[name];
  13896. if (!texture.isReady()) {
  13897. return false;
  13898. }
  13899. }
  13900. return true;
  13901. };
  13902. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13903. if (this._animate) {
  13904. this._time += this.getScene().getAnimationRatio() * 0.03;
  13905. this.updateShaderUniforms();
  13906. }
  13907. _super.prototype.render.call(this, useCameraPostProcess);
  13908. };
  13909. CustomProceduralTexture.prototype.updateTextures = function () {
  13910. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13911. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13912. }
  13913. };
  13914. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13915. if (this._config) {
  13916. for (var j = 0; j < this._config.uniforms.length; j++) {
  13917. var uniform = this._config.uniforms[j];
  13918. switch (uniform.type) {
  13919. case "float":
  13920. this.setFloat(uniform.name, uniform.value);
  13921. break;
  13922. case "color3":
  13923. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13924. break;
  13925. case "color4":
  13926. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13927. break;
  13928. case "vector2":
  13929. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13930. break;
  13931. case "vector3":
  13932. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13933. break;
  13934. }
  13935. }
  13936. }
  13937. this.setFloat("time", this._time);
  13938. };
  13939. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13940. get: function () {
  13941. return this._animate;
  13942. },
  13943. set: function (value) {
  13944. this._animate = value;
  13945. },
  13946. enumerable: true,
  13947. configurable: true
  13948. });
  13949. return CustomProceduralTexture;
  13950. })(BABYLON.ProceduralTexture);
  13951. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13952. })(BABYLON || (BABYLON = {}));
  13953. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13954. var BABYLON;
  13955. (function (BABYLON) {
  13956. var MirrorTexture = (function (_super) {
  13957. __extends(MirrorTexture, _super);
  13958. function MirrorTexture(name, size, scene, generateMipMaps) {
  13959. var _this = this;
  13960. _super.call(this, name, size, scene, generateMipMaps, true);
  13961. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13962. this._transformMatrix = BABYLON.Matrix.Zero();
  13963. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13964. this.onBeforeRender = function () {
  13965. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13966. _this._savedViewMatrix = scene.getViewMatrix();
  13967. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13968. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13969. scene.clipPlane = _this.mirrorPlane;
  13970. scene.getEngine().cullBackFaces = false;
  13971. };
  13972. this.onAfterRender = function () {
  13973. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13974. scene.getEngine().cullBackFaces = true;
  13975. delete scene.clipPlane;
  13976. };
  13977. }
  13978. MirrorTexture.prototype.clone = function () {
  13979. var textureSize = this.getSize();
  13980. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13981. // Base texture
  13982. newTexture.hasAlpha = this.hasAlpha;
  13983. newTexture.level = this.level;
  13984. // Mirror Texture
  13985. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13986. newTexture.renderList = this.renderList.slice(0);
  13987. return newTexture;
  13988. };
  13989. return MirrorTexture;
  13990. })(BABYLON.RenderTargetTexture);
  13991. BABYLON.MirrorTexture = MirrorTexture;
  13992. })(BABYLON || (BABYLON = {}));
  13993. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13994. var BABYLON;
  13995. (function (BABYLON) {
  13996. var DynamicTexture = (function (_super) {
  13997. __extends(DynamicTexture, _super);
  13998. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14000. _super.call(this, null, scene, !generateMipMaps);
  14001. this.name = name;
  14002. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14003. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14004. this._generateMipMaps = generateMipMaps;
  14005. if (options.getContext) {
  14006. this._canvas = options;
  14007. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14008. }
  14009. else {
  14010. this._canvas = document.createElement("canvas");
  14011. if (options.width) {
  14012. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14013. }
  14014. else {
  14015. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  14016. }
  14017. }
  14018. var textureSize = this.getSize();
  14019. this._canvas.width = textureSize.width;
  14020. this._canvas.height = textureSize.height;
  14021. this._context = this._canvas.getContext("2d");
  14022. }
  14023. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  14024. get: function () {
  14025. return true;
  14026. },
  14027. enumerable: true,
  14028. configurable: true
  14029. });
  14030. DynamicTexture.prototype.scale = function (ratio) {
  14031. var textureSize = this.getSize();
  14032. textureSize.width *= ratio;
  14033. textureSize.height *= ratio;
  14034. this._canvas.width = textureSize.width;
  14035. this._canvas.height = textureSize.height;
  14036. this.releaseInternalTexture();
  14037. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  14038. };
  14039. DynamicTexture.prototype.getContext = function () {
  14040. return this._context;
  14041. };
  14042. DynamicTexture.prototype.clear = function () {
  14043. var size = this.getSize();
  14044. this._context.fillRect(0, 0, size.width, size.height);
  14045. };
  14046. DynamicTexture.prototype.update = function (invertY) {
  14047. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  14048. };
  14049. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  14050. if (update === void 0) { update = true; }
  14051. var size = this.getSize();
  14052. if (clearColor) {
  14053. this._context.fillStyle = clearColor;
  14054. this._context.fillRect(0, 0, size.width, size.height);
  14055. }
  14056. this._context.font = font;
  14057. if (x === null) {
  14058. var textSize = this._context.measureText(text);
  14059. x = (size.width - textSize.width) / 2;
  14060. }
  14061. this._context.fillStyle = color;
  14062. this._context.fillText(text, x, y);
  14063. if (update) {
  14064. this.update(invertY);
  14065. }
  14066. };
  14067. DynamicTexture.prototype.clone = function () {
  14068. var textureSize = this.getSize();
  14069. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14070. // Base texture
  14071. newTexture.hasAlpha = this.hasAlpha;
  14072. newTexture.level = this.level;
  14073. // Dynamic Texture
  14074. newTexture.wrapU = this.wrapU;
  14075. newTexture.wrapV = this.wrapV;
  14076. return newTexture;
  14077. };
  14078. return DynamicTexture;
  14079. })(BABYLON.Texture);
  14080. BABYLON.DynamicTexture = DynamicTexture;
  14081. })(BABYLON || (BABYLON = {}));
  14082. //# sourceMappingURL=babylon.dynamicTexture.js.map
  14083. var BABYLON;
  14084. (function (BABYLON) {
  14085. var VideoTexture = (function (_super) {
  14086. __extends(VideoTexture, _super);
  14087. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  14088. var _this = this;
  14089. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14090. _super.call(this, null, scene, !generateMipMaps, invertY);
  14091. this._autoLaunch = true;
  14092. this.name = name;
  14093. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14094. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14095. var requiredWidth = size.width || size;
  14096. var requiredHeight = size.height || size;
  14097. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  14098. var textureSize = this.getSize();
  14099. this.video = document.createElement("video");
  14100. this.video.width = textureSize.width;
  14101. this.video.height = textureSize.height;
  14102. this.video.autoplay = false;
  14103. this.video.loop = true;
  14104. this.video.addEventListener("canplaythrough", function () {
  14105. if (_this._texture) {
  14106. _this._texture.isReady = true;
  14107. }
  14108. });
  14109. urls.forEach(function (url) {
  14110. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  14111. var source = document.createElement("source");
  14112. source.src = url;
  14113. _this.video.appendChild(source);
  14114. });
  14115. this._lastUpdate = BABYLON.Tools.Now;
  14116. }
  14117. VideoTexture.prototype.update = function () {
  14118. if (this._autoLaunch) {
  14119. this._autoLaunch = false;
  14120. this.video.play();
  14121. }
  14122. var now = BABYLON.Tools.Now;
  14123. if (now - this._lastUpdate < 15) {
  14124. return false;
  14125. }
  14126. this._lastUpdate = now;
  14127. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  14128. return true;
  14129. };
  14130. return VideoTexture;
  14131. })(BABYLON.Texture);
  14132. BABYLON.VideoTexture = VideoTexture;
  14133. })(BABYLON || (BABYLON = {}));
  14134. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  14135. (function (BABYLON) {
  14136. var EffectFallbacks = (function () {
  14137. function EffectFallbacks() {
  14138. this._defines = {};
  14139. this._currentRank = 32;
  14140. this._maxRank = -1;
  14141. }
  14142. EffectFallbacks.prototype.addFallback = function (rank, define) {
  14143. if (!this._defines[rank]) {
  14144. if (rank < this._currentRank) {
  14145. this._currentRank = rank;
  14146. }
  14147. if (rank > this._maxRank) {
  14148. this._maxRank = rank;
  14149. }
  14150. this._defines[rank] = new Array();
  14151. }
  14152. this._defines[rank].push(define);
  14153. };
  14154. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  14155. get: function () {
  14156. return this._currentRank <= this._maxRank;
  14157. },
  14158. enumerable: true,
  14159. configurable: true
  14160. });
  14161. EffectFallbacks.prototype.reduce = function (currentDefines) {
  14162. var currentFallbacks = this._defines[this._currentRank];
  14163. for (var index = 0; index < currentFallbacks.length; index++) {
  14164. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  14165. }
  14166. this._currentRank++;
  14167. return currentDefines;
  14168. };
  14169. return EffectFallbacks;
  14170. })();
  14171. BABYLON.EffectFallbacks = EffectFallbacks;
  14172. var Effect = (function () {
  14173. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  14174. var _this = this;
  14175. this._isReady = false;
  14176. this._compilationError = "";
  14177. this._valueCache = [];
  14178. this._engine = engine;
  14179. this.name = baseName;
  14180. this.defines = defines;
  14181. this._uniformsNames = uniformsNames.concat(samplers);
  14182. this._samplers = samplers;
  14183. this._attributesNames = attributesNames;
  14184. this.onError = onError;
  14185. this.onCompiled = onCompiled;
  14186. var vertexSource;
  14187. var fragmentSource;
  14188. if (baseName.vertexElement) {
  14189. vertexSource = document.getElementById(baseName.vertexElement);
  14190. if (!vertexSource) {
  14191. vertexSource = baseName.vertexElement;
  14192. }
  14193. }
  14194. else {
  14195. vertexSource = baseName.vertex || baseName;
  14196. }
  14197. if (baseName.fragmentElement) {
  14198. fragmentSource = document.getElementById(baseName.fragmentElement);
  14199. if (!fragmentSource) {
  14200. fragmentSource = baseName.fragmentElement;
  14201. }
  14202. }
  14203. else {
  14204. fragmentSource = baseName.fragment || baseName;
  14205. }
  14206. this._loadVertexShader(vertexSource, function (vertexCode) {
  14207. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  14208. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  14209. });
  14210. });
  14211. }
  14212. // Properties
  14213. Effect.prototype.isReady = function () {
  14214. return this._isReady;
  14215. };
  14216. Effect.prototype.getProgram = function () {
  14217. return this._program;
  14218. };
  14219. Effect.prototype.getAttributesNames = function () {
  14220. return this._attributesNames;
  14221. };
  14222. Effect.prototype.getAttributeLocation = function (index) {
  14223. return this._attributes[index];
  14224. };
  14225. Effect.prototype.getAttributeLocationByName = function (name) {
  14226. var index = this._attributesNames.indexOf(name);
  14227. return this._attributes[index];
  14228. };
  14229. Effect.prototype.getAttributesCount = function () {
  14230. return this._attributes.length;
  14231. };
  14232. Effect.prototype.getUniformIndex = function (uniformName) {
  14233. return this._uniformsNames.indexOf(uniformName);
  14234. };
  14235. Effect.prototype.getUniform = function (uniformName) {
  14236. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  14237. };
  14238. Effect.prototype.getSamplers = function () {
  14239. return this._samplers;
  14240. };
  14241. Effect.prototype.getCompilationError = function () {
  14242. return this._compilationError;
  14243. };
  14244. // Methods
  14245. Effect.prototype._loadVertexShader = function (vertex, callback) {
  14246. // DOM element ?
  14247. if (vertex instanceof HTMLElement) {
  14248. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  14249. callback(vertexCode);
  14250. return;
  14251. }
  14252. // Is in local store ?
  14253. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  14254. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  14255. return;
  14256. }
  14257. var vertexShaderUrl;
  14258. if (vertex[0] === ".") {
  14259. vertexShaderUrl = vertex;
  14260. }
  14261. else {
  14262. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  14263. }
  14264. // Vertex shader
  14265. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  14266. };
  14267. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  14268. // DOM element ?
  14269. if (fragment instanceof HTMLElement) {
  14270. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  14271. callback(fragmentCode);
  14272. return;
  14273. }
  14274. // Is in local store ?
  14275. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  14276. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  14277. return;
  14278. }
  14279. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14280. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14281. return;
  14282. }
  14283. var fragmentShaderUrl;
  14284. if (fragment[0] === ".") {
  14285. fragmentShaderUrl = fragment;
  14286. }
  14287. else {
  14288. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14289. }
  14290. // Fragment shader
  14291. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14292. };
  14293. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14294. try {
  14295. var engine = this._engine;
  14296. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14297. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14298. this._attributes = engine.getAttributes(this._program, attributesNames);
  14299. for (var index = 0; index < this._samplers.length; index++) {
  14300. var sampler = this.getUniform(this._samplers[index]);
  14301. if (sampler == null) {
  14302. this._samplers.splice(index, 1);
  14303. index--;
  14304. }
  14305. }
  14306. engine.bindSamplers(this);
  14307. this._isReady = true;
  14308. if (this.onCompiled) {
  14309. this.onCompiled(this);
  14310. }
  14311. }
  14312. catch (e) {
  14313. // Is it a problem with precision?
  14314. if (e.message.indexOf("highp") !== -1) {
  14315. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14316. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14317. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14318. return;
  14319. }
  14320. // Let's go through fallbacks then
  14321. if (fallbacks && fallbacks.isMoreFallbacks) {
  14322. defines = fallbacks.reduce(defines);
  14323. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14324. }
  14325. else {
  14326. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14327. BABYLON.Tools.Error("Defines: " + defines);
  14328. BABYLON.Tools.Error("Error: " + e.message);
  14329. this._compilationError = e.message;
  14330. if (this.onError) {
  14331. this.onError(this, this._compilationError);
  14332. }
  14333. }
  14334. }
  14335. };
  14336. Effect.prototype._bindTexture = function (channel, texture) {
  14337. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14338. };
  14339. Effect.prototype.setTexture = function (channel, texture) {
  14340. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14341. };
  14342. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14343. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14344. };
  14345. //public _cacheMatrix(uniformName, matrix) {
  14346. // if (!this._valueCache[uniformName]) {
  14347. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14348. // }
  14349. // for (var index = 0; index < 16; index++) {
  14350. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14351. // }
  14352. //};
  14353. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14354. if (!this._valueCache[uniformName]) {
  14355. this._valueCache[uniformName] = [x, y];
  14356. return;
  14357. }
  14358. this._valueCache[uniformName][0] = x;
  14359. this._valueCache[uniformName][1] = y;
  14360. };
  14361. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14362. if (!this._valueCache[uniformName]) {
  14363. this._valueCache[uniformName] = [x, y, z];
  14364. return;
  14365. }
  14366. this._valueCache[uniformName][0] = x;
  14367. this._valueCache[uniformName][1] = y;
  14368. this._valueCache[uniformName][2] = z;
  14369. };
  14370. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14371. if (!this._valueCache[uniformName]) {
  14372. this._valueCache[uniformName] = [x, y, z, w];
  14373. return;
  14374. }
  14375. this._valueCache[uniformName][0] = x;
  14376. this._valueCache[uniformName][1] = y;
  14377. this._valueCache[uniformName][2] = z;
  14378. this._valueCache[uniformName][3] = w;
  14379. };
  14380. Effect.prototype.setArray = function (uniformName, array) {
  14381. this._engine.setArray(this.getUniform(uniformName), array);
  14382. return this;
  14383. };
  14384. Effect.prototype.setArray2 = function (uniformName, array) {
  14385. this._engine.setArray2(this.getUniform(uniformName), array);
  14386. return this;
  14387. };
  14388. Effect.prototype.setArray3 = function (uniformName, array) {
  14389. this._engine.setArray3(this.getUniform(uniformName), array);
  14390. return this;
  14391. };
  14392. Effect.prototype.setArray4 = function (uniformName, array) {
  14393. this._engine.setArray4(this.getUniform(uniformName), array);
  14394. return this;
  14395. };
  14396. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14397. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14398. return this;
  14399. };
  14400. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14401. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14402. // return;
  14403. //this._cacheMatrix(uniformName, matrix);
  14404. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14405. return this;
  14406. };
  14407. Effect.prototype.setFloat = function (uniformName, value) {
  14408. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14409. return this;
  14410. this._valueCache[uniformName] = value;
  14411. this._engine.setFloat(this.getUniform(uniformName), value);
  14412. return this;
  14413. };
  14414. Effect.prototype.setBool = function (uniformName, bool) {
  14415. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14416. return this;
  14417. this._valueCache[uniformName] = bool;
  14418. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14419. return this;
  14420. };
  14421. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14422. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14423. return this;
  14424. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14425. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14426. return this;
  14427. };
  14428. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14429. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14430. return this;
  14431. this._cacheFloat2(uniformName, x, y);
  14432. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14433. return this;
  14434. };
  14435. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14436. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14437. return this;
  14438. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14439. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14440. return this;
  14441. };
  14442. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14443. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14444. return this;
  14445. this._cacheFloat3(uniformName, x, y, z);
  14446. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14447. return this;
  14448. };
  14449. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14450. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14451. return this;
  14452. this._cacheFloat4(uniformName, x, y, z, w);
  14453. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14454. return this;
  14455. };
  14456. Effect.prototype.setColor3 = function (uniformName, color3) {
  14457. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14458. return this;
  14459. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14460. this._engine.setColor3(this.getUniform(uniformName), color3);
  14461. return this;
  14462. };
  14463. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14464. 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)
  14465. return this;
  14466. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14467. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14468. return this;
  14469. };
  14470. // Statics
  14471. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\nvec4 leftFrag = texture2D(leftSampler, vUV);\nleftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\nvec4 rightFrag = texture2D(textureSampler, vUV);\nrightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\ngl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  14472. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\nfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\ngl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  14473. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\nfloat weights[7];\nweights[0] = 0.05;\nweights[1] = 0.1;\nweights[2] = 0.2;\nweights[3] = 0.3;\nweights[4] = 0.2;\nweights[5] = 0.1;\nweights[6] = 0.05;\n\nvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\nvec2 texelStep = texelSize * direction * blurWidth;\nvec2 start = vUV - 3.0 * texelStep;\n\nvec4 baseColor = vec4(0., 0., 0., 0.);\nvec2 texelOffset = vec2(0., 0.);\n\nfor (int i = 0; i < 7; i++)\n{\nbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\ntexelOffset += texelStep;\n}\n\ngl_FragColor = baseColor;\n}",
  14474. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\nfloat brickW = 1.0 / numberOfBricksWidth;\nfloat brickH = 1.0 / numberOfBricksHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.05;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\nif (brickColorSwitch == 0.0)\ncolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\nelse if (brickColorSwitch == 2.0)\ncolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n}\n\ngl_FragColor = vec4(color, 1.0);\n}",
  14475. chromaticAberrationPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvoid main(void)\n{\nvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;\nfloat radius = sqrt(radius2);\n\nvec4 original = texture2D(textureSampler, vUV);\n\nif (chromatic_aberration > 0.0) {\nvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\nfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\nfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\n\nvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\noriginal.r = texture2D(textureSampler, ref_coords_r).r;\noriginal.g = texture2D(textureSampler, ref_coords_g).g;\noriginal.b = texture2D(textureSampler, ref_coords_b).b;\n}\n\ngl_FragColor = original;\n}",
  14476. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\n\nvec2 p = vUV * 12.0;\nvec3 c = mix(skyColor, cloudColor, fbm(p));\ngl_FragColor = vec4(c, 1);\n\n}",
  14477. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\ngl_FragColor = color;\n}",
  14478. colorVertexShader:"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\ngl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14479. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\nfloat sliceSize = 1.0 / width; // space of 1 slice\nfloat slicePixelSize = sliceSize / width; // space of 1 pixel\nfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\nfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\nfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\nfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\nfloat s0 = xOffset + (zSlice0 * sliceSize);\nfloat s1 = xOffset + (zSlice1 * sliceSize);\nvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\nvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\nfloat zOffset = mod(uv.z * width, 1.0);\nvec4 result = mix(slice0Color, slice1Color, zOffset);\nreturn result;\n}\n\nvoid main(void)\n{\nvec4 screen_color = texture2D(textureSampler, vUV);\ngl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  14480. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\nvec2 onePixel = vec2(1.0, 1.0) / screenSize;\nvec4 colorSum =\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\n\nif (kernelWeight <= 0.0) {\nkernelWeight = 1.0;\n}\n\ngl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  14481. 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\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\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#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#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn 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#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{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn vPositionUVW;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\nreturn dot(color, bit_shift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\nif (depth.z > shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat visibility = 1.;\n\nvec2 poissonDisk[4];\npoissonDisk[0] = vec2(-0.94201624, -0.39906216);\npoissonDisk[1] = vec2(0.94558609, -0.76890725);\npoissonDisk[2] = vec2(-0.094184101, -0.92938870);\npoissonDisk[3] = vec2(0.34495938, 0.29387760);\n\nfloat biasedDepth = depth.z - bias;\n\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\n\nreturn visibility;\n}\n\nfloat linstep(float low, float high, float v) {\nreturn clamp((v - low) / (high - low), 0.0, 1.0);\n}\n\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\n{\nfloat p = smoothstep(compare - bias, compare, moments.x);\nfloat variance = max(moments.y - moments.x * moments.x, 0.02);\nfloat d = compare - moments.x;\nfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\n\nreturn clamp(max(p, p_max), 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn 1.0 - ChebychevInequality(moments, depth.z, bias);\n}\n#endif\n\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\nvec3 dp1 = dFdx(p);\nvec3 dp2 = dFdy(p);\nvec2 duv1 = dFdx(uv);\nvec2 duv2 = dFdy(uv);\n\nvec3 dp2perp = cross(dp2, normal);\nvec3 dp1perp = cross(normal, dp1);\nvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\nvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\nfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\nreturn mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\nvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\nmap = map * 255. / 127. - 128. / 127.;\nmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\nreturn normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nstruct lightingInfo\n{\nvec3 diffuse;\nvec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 lightVectorW;\nfloat attenuation = 1.0;\nif (lightData.w == 0.)\n{\nvec3 direction = lightData.xyz - vPositionW;\n\nattenuation = max(0., 1.0 - length(direction) / range);\nlightVectorW = normalize(direction);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, max(1., vSpecularColor.a));\n\nresult.diffuse = ndl * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * attenuation;\n\nreturn result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 direction = lightData.xyz - vPositionW;\nvec3 lightVectorW = normalize(direction);\nfloat attenuation = max(0., 1.0 - length(direction) / range);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * spotAtten * attenuation;\n\nreturn result;\n}\n\nresult.diffuse = vec3(0.);\nresult.specular = vec3(0.);\n\nreturn result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\nlightingInfo result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = mix(groundColor, diffuseColor, ndl);\nresult.specular = specComp * specularColor;\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\nalpha *= baseColor.a;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n#ifdef NORMAL\nvec3 normalW = normalize(vNormalW);\n#else\nvec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\nnormalW = perturbNormal(viewDirectionW);\n#endif\n\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\nlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\n#else\n#ifdef SHADOWPCF0\nshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\n#else\n#ifdef SHADOWPCF1\nshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\n#else\n#ifdef SHADOWPCF2\nshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\n#else\n#ifdef SHADOWPCF3\nshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\nalpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14482. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\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\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\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) {\nmat4 finalWorld;\n\n#ifdef REFLECTION\nvPositionUVW = position;\n#endif\n\n#ifdef INSTANCES\nfinalWorld = mat4(world0, world1, world2, world3);\n#else\nfinalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = finalWorld * (m0 + m1 + m2);\n#endif\n\n#endif\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\n\n#ifdef NORMAL\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize = pointSize;\n#endif\n}",
  14483. 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\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\nfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\ngl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  14484. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\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#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\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14485. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\n\nvoid main(void)\n{\nvec4 colorDepth = vec4(0.0);\n\nfor (int x = -OFFSET; x <= OFFSET; x++)\nfor (int y = -OFFSET; y <= OFFSET; y++)\ncolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\ngl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  14486. depthOfFieldPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\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 edge_blur;\nuniform bool highlights;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\nvec2 getDistortedCoords(vec2 coords) {\n\nif (distortion == 0.0) { return coords; }\n\nvec2 direction = 1.0 * normalize(centered_screen_pos);\nvec2 dist_coords = vec2(0.5, 0.5);\ndist_coords.x = 0.5 + direction.x * radius2 * 1.0;\ndist_coords.y = 0.5 + direction.y * radius2 * 1.0;\nfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\ndist_coords = mix(coords, dist_coords, dist_amount);\n\nreturn dist_coords;\n}\n\nvec4 getBlurColor(vec2 coords, float size) {\n\nvec4 col = texture2D(textureSampler, coords);\nif (size == 0.0) { return col; }\n\nfloat blur_level = min(3.0, ceil(size / 1.0));\n\nfloat w = (size / screen_width);\nfloat h = (size / screen_height);\nfloat total_weight = 1.0;\n\ncol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\ncol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\ncol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\ncol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\ncol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\ncol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\ncol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\ncol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\ncol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\ncol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\ntotal_weight += 8.18;\n\nif (blur_level > 1.0) {\ncol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\ncol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\ncol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\ncol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\ncol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\ncol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\ncol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\ncol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\ncol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\ncol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\ntotal_weight += 5.96;\n}\n\nif (blur_level > 2.0) {\ncol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\ncol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\ncol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\ncol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\ncol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\ncol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\ncol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\ncol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\ncol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\ntotal_weight += 2.97;\n}\n\ncol /= total_weight; // scales color according to weights\ncol.a = 1.0;\n\n\nreturn col;\n}\n\nvec2 rand(vec2 co)\n{\nfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\nfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\nreturn clamp(vec2(noise1, noise2), 0.0, 1.0);\n}\n\nvoid main(void)\n{\n\ncentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\nradius = sqrt(radius2);\n\nvec4 final_color;\nvec2 distorted_coords = getDistortedCoords(vUV);\nvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\nfloat dof_blur_amount = 0.0;\nfloat depth_bias = 0.0; // positive if the pixel is further than focus depth; negative if closer\nif (focus_depth != -1.0) {\nvec4 depth_sample = texture2D(depthSampler, distorted_coords);\nfloat depth = depth_sample.r;\ndepth_bias = depth - focus_depth;\n\nif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\nelse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\n\nif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n}\n\nfloat edge_blur_amount = 0.0;\nif (edge_blur > 0.0) {\nedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\n}\n\nfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\n\nif (blur_amount == 0.0) {\ngl_FragColor = texture2D(textureSampler, distorted_coords);\n}\nelse {\n\ngl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\n\nif (depth_bias > 0.0 && highlights) {\ngl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\n}\n\nif (blur_noise) {\nvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\nvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\ngl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\n}\n}\n\nif (grain_amount > 0.0) {\nvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\ngl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\n}\n}",
  14487. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(passSampler, vUV);\n}",
  14488. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\nvec3 baseColor = texture2D(textureSampler, vUV).rgb;\nvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\ngl_FragColor = vec4(updatedColor, 1.0);\n}",
  14489. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\nvec2 p = vUV * 8.0;\nfloat q = fbm(p - time * 0.1);\nvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\nvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\nvec3 color = c * cos(shift * vUV.y);\nfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\ngl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  14490. 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(){\nvec2 localTexelSize = texelSize;\nvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\nvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\nvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\nvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\nvec4 rgbM = texture2D(textureSampler, vUV);\nvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM = dot(rgbM, luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\nvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\nfloat dirReduce = max(\n(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\n\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\ndir * rcpDirMin)) * localTexelSize;\n\nvec4 rgbA = 0.5 * (\ntexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\ntexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\nvec4 rgbB = rgbA * 0.5 + 0.25 * (\ntexture2D(textureSampler, vUV + dir * -0.5) +\ntexture2D(textureSampler, vUV + dir * 0.5));\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\ngl_FragColor = rgbA;\n}\nelse {\ngl_FragColor = rgbB;\n}\n}",
  14491. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\ncolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\ncolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\ncolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\ngl_FragColor = vec4(color, 1.0);\n}",
  14492. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14493. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14494. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\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#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#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn 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#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\nreturn dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv));\n\nif (depth.z > shadow)\n{\nreturn 0.;\n}\nreturn 1.;\n}\n\nfloat ChebychevInequality(vec2 moments, float t)\n{\nif (t <= moments.x)\n{\nreturn 1.0;\n}\n\nfloat variance = moments.y - (moments.x * moments.x);\nvariance = max(variance, 0.);\n\nfloat d = t - moments.x;\nreturn variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW;\nif (lightData.w == 0.)\n{\nlightVectorW = normalize(lightData.xyz - vPositionW);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\nresult[0] = ndl * diffuseColor.rgb;\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = ndl * spotAtten * diffuseColor.rgb;\nresult[1] = specComp * specularColor * spotAtten;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nresult[0] = vec3(0.);\nresult[1] = vec3(0.);\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\nmat3 result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\nvec3 normalW = normalize(vNormalW);\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\nmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14495. 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\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\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\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{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn position;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\nmat4 finalWorld;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = world * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = world * (m0 + m1 + m2);\n#endif\n\n#else\nfinalWorld = world;\n#endif\n\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef REFLECTION\nvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n}",
  14496. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14497. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  14498. lensHighlightsPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float gain;\nuniform float threshold;\nuniform bool pentagon;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight = color;\nfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\nfloat lum_threshold;\nif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\nelse { lum_threshold = 0.5 + 0.44 * threshold; }\n\nluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\n\nhighlight *= luminance * gain;\nhighlight.a = 1.0;\n\nreturn highlight;\n}\n\nvoid main(void)\n{\nvec4 original = texture2D(textureSampler, vUV);\n\nif (gain == -1.0) {\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nreturn;\n}\n\nfloat w = 2.0 / screen_width;\nfloat h = 2.0 / screen_height;\n\nfloat weight = 1.0;\n\nvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\n\nif (pentagon) {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\n}\nelse {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\n}\n\nblurred /= 39.0;\n\ngl_FragColor = blurred;\n\n}",
  14499. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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{\nfloat val = 0.0;\nfloat freq = 1.0;\nfor (int i = 0; i < 4; i++)\n{\nval += abs(noise(P*freq) / freq);\nfreq *= 2.07;\n}\nreturn val;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\nvec3 col;\nx = 0.5*(x + 1.);\nx = sqrt(x);\nx = sqrt(x);\nx = sqrt(x);\ncol = vec3(.2 + .75*x);\ncol.b *= 0.95;\nreturn col;\n}\n\nvoid main()\n{\nfloat brickW = 1.0 / numberOfTilesWidth;\nfloat brickH = 1.0 / numberOfTilesHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.01;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\nt += amplitude * turbulence(brickvUV.xy);\nt = sin(t);\ncolor = marble_color(t);\n}\n\ngl_FragColor = vec4(color, 0.0);\n}",
  14500. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\nvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\nfloat rSq = theta.x * theta.x + theta.y * theta.y;\nvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\nreturn LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\nvec2 tc = HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nelse{\ngl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n}\n}",
  14501. 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\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\ngl_FragColor = color;\n}",
  14502. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\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\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\nvec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14503. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\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\nif (fClipDistance > 0.0)\ndiscard;\n#endif\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\ngl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  14504. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\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) {\nvec3 viewPos = (view * vec4(position, 1.0)).xyz;\nvec3 cornerPos;\nfloat size = options.y;\nfloat angle = options.x;\nvec2 offset = options.zw;\n\ncornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\nvUV = offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos = invView * vec4(viewPos, 1.0);\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  14505. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(textureSampler, vUV);\n}",
  14506. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14507. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\nvPosition = position;\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14508. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\nfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\nvec2 uv = vUV - vec2(0.5);\nvec2 offset = uv * depth * ref;\nvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\ngl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  14509. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\nvec3 color = roadColor * ratioy;\ngl_FragColor = vec4(color, 1.0);\n}",
  14510. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\nconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\nconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\nvec4 res = fract(depth * bit_shift);\nres -= res.xxyz * bit_mask;\n\nreturn res;\n}\n\nvec2 packHalf(float depth)\n{\nconst vec2 bitOffset = vec2(1.0 / 255., 0.);\nvec2 color = vec2(depth, fract(depth * 255.));\n\nreturn 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\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\nfloat depth = vPosition.z / vPosition.w;\ndepth = depth * 0.5 + 0.5;\n\n#ifdef VSM\nfloat moment1 = depth;\nfloat moment2 = moment1 * moment1;\n\ngl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\ngl_FragColor = pack(depth);\n#endif\n}",
  14511. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\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\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\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#endif\n\nvPosition = viewProjection * finalWorld * vec4(position, 1.0);\ngl_Position = vPosition;\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14512. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\nif (alphaTest)\n{\nif (baseColor.a < 0.95)\ndiscard;\n}\n\nbaseColor *= vColor;\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\nbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = baseColor;\n}",
  14513. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) {\nvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz;\nvec2 cornerPos;\n\nfloat angle = position.w;\nvec2 size = vec2(options.x, options.y);\nvec2 offset = options.zw;\nvec2 uvScale = textureInfos.xy;\n\ncornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\n\nvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\nvUV = (uvOffset + cellInfo.zw) * uvScale;\n\n#ifdef FOG\nfFogDistance = viewPos.z;\n#endif\n}",
  14514. 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.001);\nconst vec2 offset2 = vec2(0.001, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\nfloat depth1 = texture2D(textureSampler, coords + offset1).r;\nfloat depth2 = texture2D(textureSampler, coords + offset2).r;\n\nvec3 p1 = vec3(offset1, depth1 - depth);\nvec3 p2 = vec3(offset2, depth2 - depth);\n\nvec3 normal = cross(p1, p2);\nnormal.z = -normal.z;\n\nreturn normalize(normal);\n}\n\nvoid main(void)\n{\nconst float base = 0.2;\n\nvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\nfloat depth = texture2D(textureSampler, vUV).r;\nvec3 position = vec3(vUV, depth);\nvec3 normal = normalFromDepth(depth, vUV);\nfloat radiusDepth = radius / depth;\nfloat occlusion = 0.0;\n\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\n\nfor (int i = 0; i < SAMPLES; i++)\n{\nray = radiusDepth * reflect(sampleSphere[i], random);\nhemiRay = position + sign(dot(ray, normal)) * ray;\n\nocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\ndifference = depth - occlusionDepth;\n\nocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n}\n\nfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\nfloat result = clamp(ao + base, 0.0, 1.0);\ngl_FragColor.r = result;\ngl_FragColor.g = result;\ngl_FragColor.b = result;\ngl_FragColor.a = 1.0;\n}",
  14515. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\ngl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  14516. 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) {\nvec2 tc = vUV;\nvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\ndeltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\nfloat illuminationDecay = 1.0;\n\nvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\nfor(int i=0; i < NUM_SAMPLES; i++) {\ntc -= deltaTexCoord;\nvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\nsample *= illuminationDecay * weight;\ncolor += sample;\nilluminationDecay *= decay;\n}\n\nvec4 realColor = texture2D(textureSampler, vUV);\ngl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  14517. 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)\nvec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\nif (diffuseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef OPACITY\nvec4 opacityColor = texture2D(opacitySampler, vUV);\nfloat alpha = 1.0;\n\n#ifdef OPACITYRGB\nopacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n#else\nalpha *= opacityColor.a * opacityLevel;\n#endif\n\n#if defined(BASIC_RENDER)\ngl_FragColor = vec4(diffuseColor.rgb, alpha);\n#else\ngl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n#endif\n\ngl_FragColor.a = alpha;\n#else\n#ifndef BASIC_RENDER\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#else\ngl_FragColor = diffuseColor;\n#endif\n#endif\n\n}",
  14518. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\nvec3 wood = woodColor * ratioy;\ngl_FragColor = vec4(wood, 1.0);\n}",
  14519. };
  14520. return Effect;
  14521. })();
  14522. BABYLON.Effect = Effect;
  14523. })(BABYLON || (BABYLON = {}));
  14524. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14525. (function (BABYLON) {
  14526. var Material = (function () {
  14527. function Material(name, scene, doNotAdd) {
  14528. this.name = name;
  14529. this.checkReadyOnEveryCall = true;
  14530. this.checkReadyOnlyOnce = false;
  14531. this.state = "";
  14532. this.alpha = 1.0;
  14533. this.backFaceCulling = true;
  14534. this._wasPreviouslyReady = false;
  14535. this._fillMode = Material.TriangleFillMode;
  14536. this.pointSize = 1.0;
  14537. this.zOffset = 0;
  14538. this.id = name;
  14539. this._scene = scene;
  14540. if (!doNotAdd) {
  14541. scene.materials.push(this);
  14542. }
  14543. }
  14544. Object.defineProperty(Material, "TriangleFillMode", {
  14545. get: function () {
  14546. return Material._TriangleFillMode;
  14547. },
  14548. enumerable: true,
  14549. configurable: true
  14550. });
  14551. Object.defineProperty(Material, "WireFrameFillMode", {
  14552. get: function () {
  14553. return Material._WireFrameFillMode;
  14554. },
  14555. enumerable: true,
  14556. configurable: true
  14557. });
  14558. Object.defineProperty(Material, "PointFillMode", {
  14559. get: function () {
  14560. return Material._PointFillMode;
  14561. },
  14562. enumerable: true,
  14563. configurable: true
  14564. });
  14565. Object.defineProperty(Material.prototype, "wireframe", {
  14566. get: function () {
  14567. return this._fillMode === Material.WireFrameFillMode;
  14568. },
  14569. set: function (value) {
  14570. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14571. },
  14572. enumerable: true,
  14573. configurable: true
  14574. });
  14575. Object.defineProperty(Material.prototype, "pointsCloud", {
  14576. get: function () {
  14577. return this._fillMode === Material.PointFillMode;
  14578. },
  14579. set: function (value) {
  14580. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14581. },
  14582. enumerable: true,
  14583. configurable: true
  14584. });
  14585. Object.defineProperty(Material.prototype, "fillMode", {
  14586. get: function () {
  14587. return this._fillMode;
  14588. },
  14589. set: function (value) {
  14590. this._fillMode = value;
  14591. },
  14592. enumerable: true,
  14593. configurable: true
  14594. });
  14595. Material.prototype.isReady = function (mesh, useInstances) {
  14596. return true;
  14597. };
  14598. Material.prototype.getEffect = function () {
  14599. return this._effect;
  14600. };
  14601. Material.prototype.getScene = function () {
  14602. return this._scene;
  14603. };
  14604. Material.prototype.needAlphaBlending = function () {
  14605. return (this.alpha < 1.0);
  14606. };
  14607. Material.prototype.needAlphaTesting = function () {
  14608. return false;
  14609. };
  14610. Material.prototype.getAlphaTestTexture = function () {
  14611. return null;
  14612. };
  14613. Material.prototype.trackCreation = function (onCompiled, onError) {
  14614. };
  14615. Material.prototype._preBind = function () {
  14616. var engine = this._scene.getEngine();
  14617. engine.enableEffect(this._effect);
  14618. engine.setState(this.backFaceCulling, this.zOffset);
  14619. };
  14620. Material.prototype.bind = function (world, mesh) {
  14621. this._scene._cachedMaterial = this;
  14622. if (this.onBind) {
  14623. this.onBind(this, mesh);
  14624. }
  14625. };
  14626. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14627. };
  14628. Material.prototype.unbind = function () {
  14629. };
  14630. Material.prototype.dispose = function (forceDisposeEffect) {
  14631. // Remove from scene
  14632. var index = this._scene.materials.indexOf(this);
  14633. this._scene.materials.splice(index, 1);
  14634. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14635. if (forceDisposeEffect && this._effect) {
  14636. this._scene.getEngine()._releaseEffect(this._effect);
  14637. this._effect = null;
  14638. }
  14639. // Callback
  14640. if (this.onDispose) {
  14641. this.onDispose();
  14642. }
  14643. };
  14644. Material._TriangleFillMode = 0;
  14645. Material._WireFrameFillMode = 1;
  14646. Material._PointFillMode = 2;
  14647. return Material;
  14648. })();
  14649. BABYLON.Material = Material;
  14650. })(BABYLON || (BABYLON = {}));
  14651. //# sourceMappingURL=babylon.material.js.map
  14652. var BABYLON;
  14653. (function (BABYLON) {
  14654. var maxSimultaneousLights = 4;
  14655. var FresnelParameters = (function () {
  14656. function FresnelParameters() {
  14657. this.isEnabled = true;
  14658. this.leftColor = BABYLON.Color3.White();
  14659. this.rightColor = BABYLON.Color3.Black();
  14660. this.bias = 0;
  14661. this.power = 1;
  14662. }
  14663. return FresnelParameters;
  14664. })();
  14665. BABYLON.FresnelParameters = FresnelParameters;
  14666. var StandardMaterial = (function (_super) {
  14667. __extends(StandardMaterial, _super);
  14668. function StandardMaterial(name, scene) {
  14669. var _this = this;
  14670. _super.call(this, name, scene);
  14671. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14672. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14673. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14674. this.specularPower = 64;
  14675. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14676. this.useAlphaFromDiffuseTexture = false;
  14677. this.useSpecularOverAlpha = true;
  14678. this.fogEnabled = true;
  14679. this._cachedDefines = null;
  14680. this._renderTargets = new BABYLON.SmartArray(16);
  14681. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14682. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14683. this._scaledDiffuse = new BABYLON.Color3();
  14684. this._scaledSpecular = new BABYLON.Color3();
  14685. this.getRenderTargetTextures = function () {
  14686. _this._renderTargets.reset();
  14687. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14688. _this._renderTargets.push(_this.reflectionTexture);
  14689. }
  14690. return _this._renderTargets;
  14691. };
  14692. }
  14693. StandardMaterial.prototype.needAlphaBlending = function () {
  14694. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14695. };
  14696. StandardMaterial.prototype.needAlphaTesting = function () {
  14697. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14698. };
  14699. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14700. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14701. };
  14702. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14703. return this.diffuseTexture;
  14704. };
  14705. // Methods
  14706. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14707. if (this.checkReadyOnlyOnce) {
  14708. if (this._wasPreviouslyReady) {
  14709. }
  14710. }
  14711. var scene = this.getScene();
  14712. if (!this.checkReadyOnEveryCall) {
  14713. if (this._renderId === scene.getRenderId()) {
  14714. }
  14715. }
  14716. var engine = scene.getEngine();
  14717. var defines = [];
  14718. var fallbacks = new BABYLON.EffectFallbacks();
  14719. var needNormals = false;
  14720. var needUVs = false;
  14721. // Textures
  14722. if (scene.texturesEnabled) {
  14723. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14724. if (!this.diffuseTexture.isReady()) {
  14725. return false;
  14726. }
  14727. else {
  14728. needUVs = true;
  14729. defines.push("#define DIFFUSE");
  14730. }
  14731. }
  14732. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14733. if (!this.ambientTexture.isReady()) {
  14734. return false;
  14735. }
  14736. else {
  14737. needUVs = true;
  14738. defines.push("#define AMBIENT");
  14739. }
  14740. }
  14741. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14742. if (!this.opacityTexture.isReady()) {
  14743. return false;
  14744. }
  14745. else {
  14746. needUVs = true;
  14747. defines.push("#define OPACITY");
  14748. if (this.opacityTexture.getAlphaFromRGB) {
  14749. defines.push("#define OPACITYRGB");
  14750. }
  14751. }
  14752. }
  14753. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14754. if (!this.reflectionTexture.isReady()) {
  14755. return false;
  14756. }
  14757. else {
  14758. needNormals = true;
  14759. needUVs = true;
  14760. defines.push("#define REFLECTION");
  14761. fallbacks.addFallback(0, "REFLECTION");
  14762. }
  14763. }
  14764. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14765. if (!this.emissiveTexture.isReady()) {
  14766. return false;
  14767. }
  14768. else {
  14769. needUVs = true;
  14770. defines.push("#define EMISSIVE");
  14771. }
  14772. }
  14773. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14774. if (!this.specularTexture.isReady()) {
  14775. return false;
  14776. }
  14777. else {
  14778. needUVs = true;
  14779. defines.push("#define SPECULAR");
  14780. fallbacks.addFallback(0, "SPECULAR");
  14781. }
  14782. }
  14783. }
  14784. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14785. if (!this.bumpTexture.isReady()) {
  14786. return false;
  14787. }
  14788. else {
  14789. needUVs = true;
  14790. defines.push("#define BUMP");
  14791. fallbacks.addFallback(0, "BUMP");
  14792. }
  14793. }
  14794. // Effect
  14795. if (this.useSpecularOverAlpha) {
  14796. defines.push("#define SPECULAROVERALPHA");
  14797. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14798. }
  14799. if (scene.clipPlane) {
  14800. defines.push("#define CLIPPLANE");
  14801. }
  14802. if (engine.getAlphaTesting()) {
  14803. defines.push("#define ALPHATEST");
  14804. }
  14805. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14806. defines.push("#define ALPHAFROMDIFFUSE");
  14807. }
  14808. // Point size
  14809. if (this.pointsCloud || scene.forcePointsCloud) {
  14810. defines.push("#define POINTSIZE");
  14811. }
  14812. // Fog
  14813. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14814. defines.push("#define FOG");
  14815. fallbacks.addFallback(1, "FOG");
  14816. }
  14817. var shadowsActivated = false;
  14818. var lightIndex = 0;
  14819. if (scene.lightsEnabled) {
  14820. for (var index = 0; index < scene.lights.length; index++) {
  14821. var light = scene.lights[index];
  14822. if (!light.isEnabled()) {
  14823. continue;
  14824. }
  14825. // Excluded check
  14826. if (light._excludedMeshesIds.length > 0) {
  14827. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14828. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14829. if (excludedMesh) {
  14830. light.excludedMeshes.push(excludedMesh);
  14831. }
  14832. }
  14833. light._excludedMeshesIds = [];
  14834. }
  14835. // Included check
  14836. if (light._includedOnlyMeshesIds.length > 0) {
  14837. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14838. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14839. if (includedOnlyMesh) {
  14840. light.includedOnlyMeshes.push(includedOnlyMesh);
  14841. }
  14842. }
  14843. light._includedOnlyMeshesIds = [];
  14844. }
  14845. if (!light.canAffectMesh(mesh)) {
  14846. continue;
  14847. }
  14848. needNormals = true;
  14849. defines.push("#define LIGHT" + lightIndex);
  14850. if (lightIndex > 0) {
  14851. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14852. }
  14853. var type;
  14854. if (light instanceof BABYLON.SpotLight) {
  14855. type = "#define SPOTLIGHT" + lightIndex;
  14856. }
  14857. else if (light instanceof BABYLON.HemisphericLight) {
  14858. type = "#define HEMILIGHT" + lightIndex;
  14859. }
  14860. else {
  14861. type = "#define POINTDIRLIGHT" + lightIndex;
  14862. }
  14863. defines.push(type);
  14864. if (lightIndex > 0) {
  14865. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14866. }
  14867. // Shadows
  14868. if (scene.shadowsEnabled) {
  14869. var shadowGenerator = light.getShadowGenerator();
  14870. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14871. defines.push("#define SHADOW" + lightIndex);
  14872. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14873. if (!shadowsActivated) {
  14874. defines.push("#define SHADOWS");
  14875. shadowsActivated = true;
  14876. }
  14877. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14878. defines.push("#define SHADOWVSM" + lightIndex);
  14879. if (lightIndex > 0) {
  14880. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14881. }
  14882. }
  14883. if (shadowGenerator.usePoissonSampling) {
  14884. defines.push("#define SHADOWPCF" + lightIndex);
  14885. if (lightIndex > 0) {
  14886. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14887. }
  14888. }
  14889. }
  14890. }
  14891. lightIndex++;
  14892. if (lightIndex === maxSimultaneousLights)
  14893. break;
  14894. }
  14895. }
  14896. if (StandardMaterial.FresnelEnabled) {
  14897. // Fresnel
  14898. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14899. var fresnelRank = 1;
  14900. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14901. defines.push("#define DIFFUSEFRESNEL");
  14902. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14903. fresnelRank++;
  14904. }
  14905. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14906. defines.push("#define OPACITYFRESNEL");
  14907. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14908. fresnelRank++;
  14909. }
  14910. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14911. defines.push("#define REFLECTIONFRESNEL");
  14912. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14913. fresnelRank++;
  14914. }
  14915. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14916. defines.push("#define EMISSIVEFRESNEL");
  14917. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14918. fresnelRank++;
  14919. }
  14920. needNormals = true;
  14921. defines.push("#define FRESNEL");
  14922. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14923. }
  14924. }
  14925. // Attribs
  14926. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14927. if (mesh) {
  14928. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14929. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14930. defines.push("#define NORMAL");
  14931. }
  14932. if (needUVs) {
  14933. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14934. attribs.push(BABYLON.VertexBuffer.UVKind);
  14935. defines.push("#define UV1");
  14936. }
  14937. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14938. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14939. defines.push("#define UV2");
  14940. }
  14941. }
  14942. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14943. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14944. defines.push("#define VERTEXCOLOR");
  14945. if (mesh.hasVertexAlpha) {
  14946. defines.push("#define VERTEXALPHA");
  14947. }
  14948. }
  14949. if (mesh.useBones) {
  14950. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14951. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14952. defines.push("#define BONES");
  14953. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14954. defines.push("#define BONES4");
  14955. fallbacks.addFallback(0, "BONES4");
  14956. }
  14957. // Instances
  14958. if (useInstances) {
  14959. defines.push("#define INSTANCES");
  14960. attribs.push("world0");
  14961. attribs.push("world1");
  14962. attribs.push("world2");
  14963. attribs.push("world3");
  14964. }
  14965. }
  14966. // Get correct effect
  14967. var join = defines.join("\n");
  14968. if (this._cachedDefines !== join) {
  14969. this._cachedDefines = join;
  14970. scene.resetCachedMaterial();
  14971. // Legacy browser patch
  14972. var shaderName = "default";
  14973. if (!scene.getEngine().getCaps().standardDerivatives) {
  14974. shaderName = "legacydefault";
  14975. }
  14976. 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);
  14977. }
  14978. if (!this._effect.isReady()) {
  14979. return false;
  14980. }
  14981. this._renderId = scene.getRenderId();
  14982. this._wasPreviouslyReady = true;
  14983. return true;
  14984. };
  14985. StandardMaterial.prototype.unbind = function () {
  14986. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14987. this._effect.setTexture("reflection2DSampler", null);
  14988. }
  14989. };
  14990. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14991. this._effect.setMatrix("world", world);
  14992. };
  14993. StandardMaterial.prototype.bind = function (world, mesh) {
  14994. var scene = this.getScene();
  14995. // Matrices
  14996. this.bindOnlyWorldMatrix(world);
  14997. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14998. // Bones
  14999. if (mesh && mesh.useBones) {
  15000. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  15001. }
  15002. if (scene.getCachedMaterial() !== this) {
  15003. if (StandardMaterial.FresnelEnabled) {
  15004. // Fresnel
  15005. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15006. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  15007. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  15008. }
  15009. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15010. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  15011. }
  15012. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15013. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  15014. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  15015. }
  15016. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15017. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  15018. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  15019. }
  15020. }
  15021. // Textures
  15022. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15023. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  15024. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  15025. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  15026. }
  15027. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15028. this._effect.setTexture("ambientSampler", this.ambientTexture);
  15029. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  15030. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  15031. }
  15032. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15033. this._effect.setTexture("opacitySampler", this.opacityTexture);
  15034. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  15035. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  15036. }
  15037. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15038. if (this.reflectionTexture.isCube) {
  15039. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  15040. }
  15041. else {
  15042. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  15043. }
  15044. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  15045. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  15046. }
  15047. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15048. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  15049. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  15050. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  15051. }
  15052. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15053. this._effect.setTexture("specularSampler", this.specularTexture);
  15054. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  15055. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  15056. }
  15057. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  15058. this._effect.setTexture("bumpSampler", this.bumpTexture);
  15059. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  15060. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  15061. }
  15062. // Clip plane
  15063. if (scene.clipPlane) {
  15064. var clipPlane = scene.clipPlane;
  15065. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15066. }
  15067. // Point size
  15068. if (this.pointsCloud) {
  15069. this._effect.setFloat("pointSize", this.pointSize);
  15070. }
  15071. // Colors
  15072. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  15073. // Scaling down color according to emissive
  15074. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15075. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15076. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15077. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  15078. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  15079. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  15080. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  15081. }
  15082. // Scaling down color according to emissive
  15083. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15084. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15085. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15086. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  15087. if (scene.lightsEnabled) {
  15088. var lightIndex = 0;
  15089. for (var index = 0; index < scene.lights.length; index++) {
  15090. var light = scene.lights[index];
  15091. if (!light.isEnabled()) {
  15092. continue;
  15093. }
  15094. if (!light.canAffectMesh(mesh)) {
  15095. continue;
  15096. }
  15097. if (light instanceof BABYLON.PointLight) {
  15098. // Point Light
  15099. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15100. }
  15101. else if (light instanceof BABYLON.DirectionalLight) {
  15102. // Directional Light
  15103. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15104. }
  15105. else if (light instanceof BABYLON.SpotLight) {
  15106. // Spot Light
  15107. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  15108. }
  15109. else if (light instanceof BABYLON.HemisphericLight) {
  15110. // Hemispheric Light
  15111. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  15112. }
  15113. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  15114. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  15115. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  15116. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  15117. // Shadows
  15118. if (scene.shadowsEnabled) {
  15119. var shadowGenerator = light.getShadowGenerator();
  15120. if (mesh.receiveShadows && shadowGenerator) {
  15121. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  15122. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  15123. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  15124. }
  15125. }
  15126. lightIndex++;
  15127. if (lightIndex === maxSimultaneousLights)
  15128. break;
  15129. }
  15130. }
  15131. // View
  15132. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  15133. this._effect.setMatrix("view", scene.getViewMatrix());
  15134. }
  15135. // Fog
  15136. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  15137. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  15138. this._effect.setColor3("vFogColor", scene.fogColor);
  15139. }
  15140. _super.prototype.bind.call(this, world, mesh);
  15141. };
  15142. StandardMaterial.prototype.getAnimatables = function () {
  15143. var results = [];
  15144. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  15145. results.push(this.diffuseTexture);
  15146. }
  15147. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  15148. results.push(this.ambientTexture);
  15149. }
  15150. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  15151. results.push(this.opacityTexture);
  15152. }
  15153. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  15154. results.push(this.reflectionTexture);
  15155. }
  15156. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  15157. results.push(this.emissiveTexture);
  15158. }
  15159. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  15160. results.push(this.specularTexture);
  15161. }
  15162. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  15163. results.push(this.bumpTexture);
  15164. }
  15165. return results;
  15166. };
  15167. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  15168. if (this.diffuseTexture) {
  15169. this.diffuseTexture.dispose();
  15170. }
  15171. if (this.ambientTexture) {
  15172. this.ambientTexture.dispose();
  15173. }
  15174. if (this.opacityTexture) {
  15175. this.opacityTexture.dispose();
  15176. }
  15177. if (this.reflectionTexture) {
  15178. this.reflectionTexture.dispose();
  15179. }
  15180. if (this.emissiveTexture) {
  15181. this.emissiveTexture.dispose();
  15182. }
  15183. if (this.specularTexture) {
  15184. this.specularTexture.dispose();
  15185. }
  15186. if (this.bumpTexture) {
  15187. this.bumpTexture.dispose();
  15188. }
  15189. _super.prototype.dispose.call(this, forceDisposeEffect);
  15190. };
  15191. StandardMaterial.prototype.clone = function (name) {
  15192. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  15193. // Base material
  15194. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  15195. newStandardMaterial.alpha = this.alpha;
  15196. newStandardMaterial.fillMode = this.fillMode;
  15197. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  15198. // Standard material
  15199. if (this.diffuseTexture && this.diffuseTexture.clone) {
  15200. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  15201. }
  15202. if (this.ambientTexture && this.ambientTexture.clone) {
  15203. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  15204. }
  15205. if (this.opacityTexture && this.opacityTexture.clone) {
  15206. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  15207. }
  15208. if (this.reflectionTexture && this.reflectionTexture.clone) {
  15209. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  15210. }
  15211. if (this.emissiveTexture && this.emissiveTexture.clone) {
  15212. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  15213. }
  15214. if (this.specularTexture && this.specularTexture.clone) {
  15215. newStandardMaterial.specularTexture = this.specularTexture.clone();
  15216. }
  15217. if (this.bumpTexture && this.bumpTexture.clone) {
  15218. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  15219. }
  15220. newStandardMaterial.ambientColor = this.ambientColor.clone();
  15221. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  15222. newStandardMaterial.specularColor = this.specularColor.clone();
  15223. newStandardMaterial.specularPower = this.specularPower;
  15224. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  15225. return newStandardMaterial;
  15226. };
  15227. // Statics
  15228. // Flags used to enable or disable a type of texture for all Standard Materials
  15229. StandardMaterial.DiffuseTextureEnabled = true;
  15230. StandardMaterial.AmbientTextureEnabled = true;
  15231. StandardMaterial.OpacityTextureEnabled = true;
  15232. StandardMaterial.ReflectionTextureEnabled = true;
  15233. StandardMaterial.EmissiveTextureEnabled = true;
  15234. StandardMaterial.SpecularTextureEnabled = true;
  15235. StandardMaterial.BumpTextureEnabled = true;
  15236. StandardMaterial.FresnelEnabled = true;
  15237. return StandardMaterial;
  15238. })(BABYLON.Material);
  15239. BABYLON.StandardMaterial = StandardMaterial;
  15240. })(BABYLON || (BABYLON = {}));
  15241. //# sourceMappingURL=babylon.standardMaterial.js.map
  15242. var BABYLON;
  15243. (function (BABYLON) {
  15244. var MultiMaterial = (function (_super) {
  15245. __extends(MultiMaterial, _super);
  15246. function MultiMaterial(name, scene) {
  15247. _super.call(this, name, scene, true);
  15248. this.subMaterials = new Array();
  15249. scene.multiMaterials.push(this);
  15250. }
  15251. // Properties
  15252. MultiMaterial.prototype.getSubMaterial = function (index) {
  15253. if (index < 0 || index >= this.subMaterials.length) {
  15254. return this.getScene().defaultMaterial;
  15255. }
  15256. return this.subMaterials[index];
  15257. };
  15258. // Methods
  15259. MultiMaterial.prototype.isReady = function (mesh) {
  15260. for (var index = 0; index < this.subMaterials.length; index++) {
  15261. var subMaterial = this.subMaterials[index];
  15262. if (subMaterial) {
  15263. if (!this.subMaterials[index].isReady(mesh)) {
  15264. return false;
  15265. }
  15266. }
  15267. }
  15268. return true;
  15269. };
  15270. return MultiMaterial;
  15271. })(BABYLON.Material);
  15272. BABYLON.MultiMaterial = MultiMaterial;
  15273. })(BABYLON || (BABYLON = {}));
  15274. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  15275. (function (BABYLON) {
  15276. var Database = (function () {
  15277. function Database(urlToScene, callbackManifestChecked) {
  15278. // Handling various flavors of prefixed version of IndexedDB
  15279. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  15280. this.callbackManifestChecked = callbackManifestChecked;
  15281. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15282. this.db = null;
  15283. this.enableSceneOffline = false;
  15284. this.enableTexturesOffline = false;
  15285. this.manifestVersionFound = 0;
  15286. this.mustUpdateRessources = false;
  15287. this.hasReachedQuota = false;
  15288. this.checkManifestFile();
  15289. }
  15290. Database.prototype.checkManifestFile = function () {
  15291. var _this = this;
  15292. function noManifestFile() {
  15293. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15294. that.enableSceneOffline = false;
  15295. that.enableTexturesOffline = false;
  15296. that.callbackManifestChecked(false);
  15297. }
  15298. var that = this;
  15299. var manifestURL = this.currentSceneUrl + ".manifest";
  15300. var xhr = new XMLHttpRequest();
  15301. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15302. xhr.open("GET", manifestURLTimeStamped, true);
  15303. xhr.addEventListener("load", function () {
  15304. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15305. try {
  15306. var manifestFile = JSON.parse(xhr.response);
  15307. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15308. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15309. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15310. _this.manifestVersionFound = manifestFile.version;
  15311. }
  15312. if (_this.callbackManifestChecked) {
  15313. _this.callbackManifestChecked(true);
  15314. }
  15315. }
  15316. catch (ex) {
  15317. noManifestFile();
  15318. }
  15319. }
  15320. else {
  15321. noManifestFile();
  15322. }
  15323. }, false);
  15324. xhr.addEventListener("error", function (event) {
  15325. noManifestFile();
  15326. }, false);
  15327. try {
  15328. xhr.send();
  15329. }
  15330. catch (ex) {
  15331. BABYLON.Tools.Error("Error on XHR send request.");
  15332. that.callbackManifestChecked(false);
  15333. }
  15334. };
  15335. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15336. var _this = this;
  15337. function handleError() {
  15338. that.isSupported = false;
  15339. if (errorCallback)
  15340. errorCallback();
  15341. }
  15342. var that = this;
  15343. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15344. // Your browser doesn't support IndexedDB
  15345. this.isSupported = false;
  15346. if (errorCallback)
  15347. errorCallback();
  15348. }
  15349. else {
  15350. // If the DB hasn't been opened or created yet
  15351. if (!this.db) {
  15352. this.hasReachedQuota = false;
  15353. this.isSupported = true;
  15354. var request = this.idbFactory.open("babylonjs", 1);
  15355. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15356. request.onerror = function (event) {
  15357. handleError();
  15358. };
  15359. // executes when a version change transaction cannot complete due to other active transactions
  15360. request.onblocked = function (event) {
  15361. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15362. handleError();
  15363. };
  15364. // DB has been opened successfully
  15365. request.onsuccess = function (event) {
  15366. _this.db = request.result;
  15367. successCallback();
  15368. };
  15369. // Initialization of the DB. Creating Scenes & Textures stores
  15370. request.onupgradeneeded = function (event) {
  15371. _this.db = (event.target).result;
  15372. try {
  15373. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15374. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15375. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15376. }
  15377. catch (ex) {
  15378. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15379. handleError();
  15380. }
  15381. };
  15382. }
  15383. else {
  15384. if (successCallback)
  15385. successCallback();
  15386. }
  15387. }
  15388. };
  15389. Database.prototype.loadImageFromDB = function (url, image) {
  15390. var _this = this;
  15391. var completeURL = Database.ReturnFullUrlLocation(url);
  15392. var saveAndLoadImage = function () {
  15393. if (!_this.hasReachedQuota && _this.db !== null) {
  15394. // the texture is not yet in the DB, let's try to save it
  15395. _this._saveImageIntoDBAsync(completeURL, image);
  15396. }
  15397. else {
  15398. image.src = url;
  15399. }
  15400. };
  15401. if (!this.mustUpdateRessources) {
  15402. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15403. }
  15404. else {
  15405. saveAndLoadImage();
  15406. }
  15407. };
  15408. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15409. if (this.isSupported && this.db !== null) {
  15410. var texture;
  15411. var transaction = this.db.transaction(["textures"]);
  15412. transaction.onabort = function (event) {
  15413. image.src = url;
  15414. };
  15415. transaction.oncomplete = function (event) {
  15416. var blobTextureURL;
  15417. if (texture) {
  15418. var URL = window.URL || window.webkitURL;
  15419. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15420. image.onerror = function () {
  15421. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15422. image.src = url;
  15423. };
  15424. image.src = blobTextureURL;
  15425. }
  15426. else {
  15427. notInDBCallback();
  15428. }
  15429. };
  15430. var getRequest = transaction.objectStore("textures").get(url);
  15431. getRequest.onsuccess = function (event) {
  15432. texture = (event.target).result;
  15433. };
  15434. getRequest.onerror = function (event) {
  15435. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15436. image.src = url;
  15437. };
  15438. }
  15439. else {
  15440. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15441. image.src = url;
  15442. }
  15443. };
  15444. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15445. var _this = this;
  15446. if (this.isSupported) {
  15447. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15448. var generateBlobUrl = function () {
  15449. var blobTextureURL;
  15450. if (blob) {
  15451. var URL = window.URL || window.webkitURL;
  15452. try {
  15453. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15454. }
  15455. catch (ex) {
  15456. blobTextureURL = URL.createObjectURL(blob);
  15457. }
  15458. }
  15459. image.src = blobTextureURL;
  15460. };
  15461. if (Database.isUASupportingBlobStorage) {
  15462. var xhr = new XMLHttpRequest(), blob;
  15463. xhr.open("GET", url, true);
  15464. xhr.responseType = "blob";
  15465. xhr.addEventListener("load", function () {
  15466. if (xhr.status === 200) {
  15467. // Blob as response (XHR2)
  15468. blob = xhr.response;
  15469. var transaction = _this.db.transaction(["textures"], "readwrite");
  15470. // the transaction could abort because of a QuotaExceededError error
  15471. transaction.onabort = function (event) {
  15472. try {
  15473. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15474. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15475. this.hasReachedQuota = true;
  15476. }
  15477. }
  15478. catch (ex) {
  15479. }
  15480. generateBlobUrl();
  15481. };
  15482. transaction.oncomplete = function (event) {
  15483. generateBlobUrl();
  15484. };
  15485. var newTexture = { textureUrl: url, data: blob };
  15486. try {
  15487. // Put the blob into the dabase
  15488. var addRequest = transaction.objectStore("textures").put(newTexture);
  15489. addRequest.onsuccess = function (event) {
  15490. };
  15491. addRequest.onerror = function (event) {
  15492. generateBlobUrl();
  15493. };
  15494. }
  15495. catch (ex) {
  15496. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15497. if (ex.code === 25) {
  15498. Database.isUASupportingBlobStorage = false;
  15499. }
  15500. image.src = url;
  15501. }
  15502. }
  15503. else {
  15504. image.src = url;
  15505. }
  15506. }, false);
  15507. xhr.addEventListener("error", function (event) {
  15508. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15509. image.src = url;
  15510. }, false);
  15511. xhr.send();
  15512. }
  15513. else {
  15514. image.src = url;
  15515. }
  15516. }
  15517. else {
  15518. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15519. image.src = url;
  15520. }
  15521. };
  15522. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15523. var _this = this;
  15524. var updateVersion = function (event) {
  15525. // the version is not yet in the DB or we need to update it
  15526. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15527. };
  15528. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15529. };
  15530. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15531. var _this = this;
  15532. if (this.isSupported) {
  15533. var version;
  15534. try {
  15535. var transaction = this.db.transaction(["versions"]);
  15536. transaction.oncomplete = function (event) {
  15537. if (version) {
  15538. // If the version in the JSON file is > than the version in DB
  15539. if (_this.manifestVersionFound > version.data) {
  15540. _this.mustUpdateRessources = true;
  15541. updateInDBCallback();
  15542. }
  15543. else {
  15544. callback(version.data);
  15545. }
  15546. }
  15547. else {
  15548. _this.mustUpdateRessources = true;
  15549. updateInDBCallback();
  15550. }
  15551. };
  15552. transaction.onabort = function (event) {
  15553. callback(-1);
  15554. };
  15555. var getRequest = transaction.objectStore("versions").get(url);
  15556. getRequest.onsuccess = function (event) {
  15557. version = (event.target).result;
  15558. };
  15559. getRequest.onerror = function (event) {
  15560. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15561. callback(-1);
  15562. };
  15563. }
  15564. catch (ex) {
  15565. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15566. callback(-1);
  15567. }
  15568. }
  15569. else {
  15570. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15571. callback(-1);
  15572. }
  15573. };
  15574. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15575. var _this = this;
  15576. if (this.isSupported && !this.hasReachedQuota) {
  15577. try {
  15578. // Open a transaction to the database
  15579. var transaction = this.db.transaction(["versions"], "readwrite");
  15580. // the transaction could abort because of a QuotaExceededError error
  15581. transaction.onabort = function (event) {
  15582. try {
  15583. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15584. _this.hasReachedQuota = true;
  15585. }
  15586. }
  15587. catch (ex) {
  15588. }
  15589. callback(-1);
  15590. };
  15591. transaction.oncomplete = function (event) {
  15592. callback(_this.manifestVersionFound);
  15593. };
  15594. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15595. // Put the scene into the database
  15596. var addRequest = transaction.objectStore("versions").put(newVersion);
  15597. addRequest.onsuccess = function (event) {
  15598. };
  15599. addRequest.onerror = function (event) {
  15600. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15601. };
  15602. }
  15603. catch (ex) {
  15604. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15605. callback(-1);
  15606. }
  15607. }
  15608. else {
  15609. callback(-1);
  15610. }
  15611. };
  15612. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15613. var _this = this;
  15614. var completeUrl = Database.ReturnFullUrlLocation(url);
  15615. var saveAndLoadFile = function (event) {
  15616. // the scene is not yet in the DB, let's try to save it
  15617. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15618. };
  15619. this._checkVersionFromDB(completeUrl, function (version) {
  15620. if (version !== -1) {
  15621. if (!_this.mustUpdateRessources) {
  15622. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15623. }
  15624. else {
  15625. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15626. }
  15627. }
  15628. else {
  15629. errorCallback();
  15630. }
  15631. });
  15632. };
  15633. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15634. if (this.isSupported) {
  15635. var targetStore;
  15636. if (url.indexOf(".babylon") !== -1) {
  15637. targetStore = "scenes";
  15638. }
  15639. else {
  15640. targetStore = "textures";
  15641. }
  15642. var file;
  15643. var transaction = this.db.transaction([targetStore]);
  15644. transaction.oncomplete = function (event) {
  15645. if (file) {
  15646. callback(file.data);
  15647. }
  15648. else {
  15649. notInDBCallback();
  15650. }
  15651. };
  15652. transaction.onabort = function (event) {
  15653. notInDBCallback();
  15654. };
  15655. var getRequest = transaction.objectStore(targetStore).get(url);
  15656. getRequest.onsuccess = function (event) {
  15657. file = (event.target).result;
  15658. };
  15659. getRequest.onerror = function (event) {
  15660. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15661. notInDBCallback();
  15662. };
  15663. }
  15664. else {
  15665. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15666. callback();
  15667. }
  15668. };
  15669. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15670. var _this = this;
  15671. if (this.isSupported) {
  15672. var targetStore;
  15673. if (url.indexOf(".babylon") !== -1) {
  15674. targetStore = "scenes";
  15675. }
  15676. else {
  15677. targetStore = "textures";
  15678. }
  15679. // Create XHR
  15680. var xhr = new XMLHttpRequest(), fileData;
  15681. xhr.open("GET", url, true);
  15682. if (useArrayBuffer) {
  15683. xhr.responseType = "arraybuffer";
  15684. }
  15685. xhr.onprogress = progressCallback;
  15686. xhr.addEventListener("load", function () {
  15687. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15688. // Blob as response (XHR2)
  15689. //fileData = xhr.responseText;
  15690. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15691. if (!_this.hasReachedQuota) {
  15692. // Open a transaction to the database
  15693. var transaction = _this.db.transaction([targetStore], "readwrite");
  15694. // the transaction could abort because of a QuotaExceededError error
  15695. transaction.onabort = function (event) {
  15696. try {
  15697. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15698. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15699. this.hasReachedQuota = true;
  15700. }
  15701. }
  15702. catch (ex) {
  15703. }
  15704. callback(fileData);
  15705. };
  15706. transaction.oncomplete = function (event) {
  15707. callback(fileData);
  15708. };
  15709. var newFile;
  15710. if (targetStore === "scenes") {
  15711. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15712. }
  15713. else {
  15714. newFile = { textureUrl: url, data: fileData };
  15715. }
  15716. try {
  15717. // Put the scene into the database
  15718. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15719. addRequest.onsuccess = function (event) {
  15720. };
  15721. addRequest.onerror = function (event) {
  15722. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15723. };
  15724. }
  15725. catch (ex) {
  15726. callback(fileData);
  15727. }
  15728. }
  15729. else {
  15730. callback(fileData);
  15731. }
  15732. }
  15733. else {
  15734. callback();
  15735. }
  15736. }, false);
  15737. xhr.addEventListener("error", function (event) {
  15738. BABYLON.Tools.Error("error on XHR request.");
  15739. callback();
  15740. }, false);
  15741. xhr.send();
  15742. }
  15743. else {
  15744. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15745. callback();
  15746. }
  15747. };
  15748. Database.isUASupportingBlobStorage = true;
  15749. Database.parseURL = function (url) {
  15750. var a = document.createElement('a');
  15751. a.href = url;
  15752. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15753. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15754. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15755. return absLocation;
  15756. };
  15757. Database.ReturnFullUrlLocation = function (url) {
  15758. if (url.indexOf("http:/") === -1) {
  15759. return (BABYLON.Database.parseURL(window.location.href) + url);
  15760. }
  15761. else {
  15762. return url;
  15763. }
  15764. };
  15765. return Database;
  15766. })();
  15767. BABYLON.Database = Database;
  15768. })(BABYLON || (BABYLON = {}));
  15769. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15770. (function (BABYLON) {
  15771. var SpriteManager = (function () {
  15772. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15774. this.name = name;
  15775. this.cellSize = cellSize;
  15776. this.sprites = new Array();
  15777. this.renderingGroupId = 0;
  15778. this.fogEnabled = true;
  15779. this._vertexDeclaration = [4, 4, 4, 4];
  15780. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15781. this._capacity = capacity;
  15782. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15783. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15784. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15785. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15786. this._scene = scene;
  15787. this._scene.spriteManagers.push(this);
  15788. // VBO
  15789. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15790. var indices = [];
  15791. var index = 0;
  15792. for (var count = 0; count < capacity; count++) {
  15793. indices.push(index);
  15794. indices.push(index + 1);
  15795. indices.push(index + 2);
  15796. indices.push(index);
  15797. indices.push(index + 2);
  15798. indices.push(index + 3);
  15799. index += 4;
  15800. }
  15801. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15802. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15803. // Effects
  15804. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15805. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15806. }
  15807. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15808. var arrayOffset = index * 16;
  15809. if (offsetX === 0)
  15810. offsetX = this._epsilon;
  15811. else if (offsetX === 1)
  15812. offsetX = 1 - this._epsilon;
  15813. if (offsetY === 0)
  15814. offsetY = this._epsilon;
  15815. else if (offsetY === 1)
  15816. offsetY = 1 - this._epsilon;
  15817. this._vertices[arrayOffset] = sprite.position.x;
  15818. this._vertices[arrayOffset + 1] = sprite.position.y;
  15819. this._vertices[arrayOffset + 2] = sprite.position.z;
  15820. this._vertices[arrayOffset + 3] = sprite.angle;
  15821. this._vertices[arrayOffset + 4] = sprite.width;
  15822. this._vertices[arrayOffset + 5] = sprite.height;
  15823. this._vertices[arrayOffset + 6] = offsetX;
  15824. this._vertices[arrayOffset + 7] = offsetY;
  15825. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  15826. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  15827. var offset = (sprite.cellIndex / rowSize) >> 0;
  15828. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  15829. this._vertices[arrayOffset + 11] = offset;
  15830. // Color
  15831. this._vertices[arrayOffset + 12] = sprite.color.r;
  15832. this._vertices[arrayOffset + 13] = sprite.color.g;
  15833. this._vertices[arrayOffset + 14] = sprite.color.b;
  15834. this._vertices[arrayOffset + 15] = sprite.color.a;
  15835. };
  15836. SpriteManager.prototype.render = function () {
  15837. // Check
  15838. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15839. return;
  15840. var engine = this._scene.getEngine();
  15841. var baseSize = this._spriteTexture.getBaseSize();
  15842. // Sprites
  15843. var deltaTime = engine.getDeltaTime();
  15844. var max = Math.min(this._capacity, this.sprites.length);
  15845. var rowSize = baseSize.width / this.cellSize;
  15846. var offset = 0;
  15847. for (var index = 0; index < max; index++) {
  15848. var sprite = this.sprites[index];
  15849. if (!sprite) {
  15850. continue;
  15851. }
  15852. sprite._animate(deltaTime);
  15853. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15854. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15855. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15856. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15857. }
  15858. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15859. // Render
  15860. var effect = this._effectBase;
  15861. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15862. effect = this._effectFog;
  15863. }
  15864. engine.enableEffect(effect);
  15865. var viewMatrix = this._scene.getViewMatrix();
  15866. effect.setTexture("diffuseSampler", this._spriteTexture);
  15867. effect.setMatrix("view", viewMatrix);
  15868. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15869. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15870. // Fog
  15871. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15872. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15873. effect.setColor3("vFogColor", this._scene.fogColor);
  15874. }
  15875. // VBOs
  15876. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15877. // Draw order
  15878. effect.setBool("alphaTest", true);
  15879. engine.setColorWrite(false);
  15880. engine.draw(true, 0, max * 6);
  15881. engine.setColorWrite(true);
  15882. effect.setBool("alphaTest", false);
  15883. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15884. engine.draw(true, 0, max * 6);
  15885. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15886. };
  15887. SpriteManager.prototype.dispose = function () {
  15888. if (this._vertexBuffer) {
  15889. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15890. this._vertexBuffer = null;
  15891. }
  15892. if (this._indexBuffer) {
  15893. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15894. this._indexBuffer = null;
  15895. }
  15896. if (this._spriteTexture) {
  15897. this._spriteTexture.dispose();
  15898. this._spriteTexture = null;
  15899. }
  15900. // Remove from scene
  15901. var index = this._scene.spriteManagers.indexOf(this);
  15902. this._scene.spriteManagers.splice(index, 1);
  15903. // Callback
  15904. if (this.onDispose) {
  15905. this.onDispose();
  15906. }
  15907. };
  15908. return SpriteManager;
  15909. })();
  15910. BABYLON.SpriteManager = SpriteManager;
  15911. })(BABYLON || (BABYLON = {}));
  15912. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15913. (function (BABYLON) {
  15914. var Sprite = (function () {
  15915. function Sprite(name, manager) {
  15916. this.name = name;
  15917. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15918. this.width = 1.0;
  15919. this.height = 1.0;
  15920. this.angle = 0;
  15921. this.cellIndex = 0;
  15922. this.invertU = 0;
  15923. this.invertV = 0;
  15924. this.animations = new Array();
  15925. this._animationStarted = false;
  15926. this._loopAnimation = false;
  15927. this._fromIndex = 0;
  15928. this._toIndex = 0;
  15929. this._delay = 0;
  15930. this._direction = 1;
  15931. this._frameCount = 0;
  15932. this._time = 0;
  15933. this._manager = manager;
  15934. this._manager.sprites.push(this);
  15935. this.position = BABYLON.Vector3.Zero();
  15936. }
  15937. Object.defineProperty(Sprite.prototype, "size", {
  15938. get: function () {
  15939. return this.width;
  15940. },
  15941. set: function (value) {
  15942. this.width = value;
  15943. this.height = value;
  15944. },
  15945. enumerable: true,
  15946. configurable: true
  15947. });
  15948. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15949. this._fromIndex = from;
  15950. this._toIndex = to;
  15951. this._loopAnimation = loop;
  15952. this._delay = delay;
  15953. this._animationStarted = true;
  15954. this._direction = from < to ? 1 : -1;
  15955. this.cellIndex = from;
  15956. this._time = 0;
  15957. };
  15958. Sprite.prototype.stopAnimation = function () {
  15959. this._animationStarted = false;
  15960. };
  15961. Sprite.prototype._animate = function (deltaTime) {
  15962. if (!this._animationStarted)
  15963. return;
  15964. this._time += deltaTime;
  15965. if (this._time > this._delay) {
  15966. this._time = this._time % this._delay;
  15967. this.cellIndex += this._direction;
  15968. if (this.cellIndex == this._toIndex) {
  15969. if (this._loopAnimation) {
  15970. this.cellIndex = this._fromIndex;
  15971. }
  15972. else {
  15973. this._animationStarted = false;
  15974. if (this.disposeWhenFinishedAnimating) {
  15975. this.dispose();
  15976. }
  15977. }
  15978. }
  15979. }
  15980. };
  15981. Sprite.prototype.dispose = function () {
  15982. for (var i = 0; i < this._manager.sprites.length; i++) {
  15983. if (this._manager.sprites[i] == this) {
  15984. this._manager.sprites.splice(i, 1);
  15985. }
  15986. }
  15987. };
  15988. return Sprite;
  15989. })();
  15990. BABYLON.Sprite = Sprite;
  15991. })(BABYLON || (BABYLON = {}));
  15992. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15993. (function (BABYLON) {
  15994. var Layer = (function () {
  15995. function Layer(name, imgUrl, scene, isBackground, color) {
  15996. this.name = name;
  15997. this._vertexDeclaration = [2];
  15998. this._vertexStrideSize = 2 * 4;
  15999. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  16000. this.isBackground = isBackground === undefined ? true : isBackground;
  16001. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  16002. this._scene = scene;
  16003. this._scene.layers.push(this);
  16004. // VBO
  16005. var vertices = [];
  16006. vertices.push(1, 1);
  16007. vertices.push(-1, 1);
  16008. vertices.push(-1, -1);
  16009. vertices.push(1, -1);
  16010. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16011. // Indices
  16012. var indices = [];
  16013. indices.push(0);
  16014. indices.push(1);
  16015. indices.push(2);
  16016. indices.push(0);
  16017. indices.push(2);
  16018. indices.push(3);
  16019. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16020. // Effects
  16021. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  16022. }
  16023. Layer.prototype.render = function () {
  16024. // Check
  16025. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  16026. return;
  16027. var engine = this._scene.getEngine();
  16028. // Render
  16029. engine.enableEffect(this._effect);
  16030. engine.setState(false);
  16031. // Texture
  16032. this._effect.setTexture("textureSampler", this.texture);
  16033. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  16034. // Color
  16035. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  16036. // VBOs
  16037. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16038. // Draw order
  16039. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16040. engine.draw(true, 0, 6);
  16041. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16042. };
  16043. Layer.prototype.dispose = function () {
  16044. if (this._vertexBuffer) {
  16045. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16046. this._vertexBuffer = null;
  16047. }
  16048. if (this._indexBuffer) {
  16049. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16050. this._indexBuffer = null;
  16051. }
  16052. if (this.texture) {
  16053. this.texture.dispose();
  16054. this.texture = null;
  16055. }
  16056. // Remove from scene
  16057. var index = this._scene.layers.indexOf(this);
  16058. this._scene.layers.splice(index, 1);
  16059. // Callback
  16060. if (this.onDispose) {
  16061. this.onDispose();
  16062. }
  16063. };
  16064. return Layer;
  16065. })();
  16066. BABYLON.Layer = Layer;
  16067. })(BABYLON || (BABYLON = {}));
  16068. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  16069. (function (BABYLON) {
  16070. var Particle = (function () {
  16071. function Particle() {
  16072. this.position = BABYLON.Vector3.Zero();
  16073. this.direction = BABYLON.Vector3.Zero();
  16074. this.color = new BABYLON.Color4(0, 0, 0, 0);
  16075. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  16076. this.lifeTime = 1.0;
  16077. this.age = 0;
  16078. this.size = 0;
  16079. this.angle = 0;
  16080. this.angularSpeed = 0;
  16081. }
  16082. Particle.prototype.copyTo = function (other) {
  16083. other.position.copyFrom(this.position);
  16084. other.direction.copyFrom(this.direction);
  16085. other.color.copyFrom(this.color);
  16086. other.colorStep.copyFrom(this.colorStep);
  16087. other.lifeTime = this.lifeTime;
  16088. other.age = this.age;
  16089. other.size = this.size;
  16090. other.angle = this.angle;
  16091. other.angularSpeed = this.angularSpeed;
  16092. };
  16093. return Particle;
  16094. })();
  16095. BABYLON.Particle = Particle;
  16096. })(BABYLON || (BABYLON = {}));
  16097. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  16098. (function (BABYLON) {
  16099. var randomNumber = function (min, max) {
  16100. if (min === max) {
  16101. return (min);
  16102. }
  16103. var random = Math.random();
  16104. return ((random * (max - min)) + min);
  16105. };
  16106. var ParticleSystem = (function () {
  16107. function ParticleSystem(name, capacity, scene, customEffect) {
  16108. var _this = this;
  16109. this.name = name;
  16110. this.renderingGroupId = 0;
  16111. this.emitter = null;
  16112. this.emitRate = 10;
  16113. this.manualEmitCount = -1;
  16114. this.updateSpeed = 0.01;
  16115. this.targetStopDuration = 0;
  16116. this.disposeOnStop = false;
  16117. this.minEmitPower = 1;
  16118. this.maxEmitPower = 1;
  16119. this.minLifeTime = 1;
  16120. this.maxLifeTime = 1;
  16121. this.minSize = 1;
  16122. this.maxSize = 1;
  16123. this.minAngularSpeed = 0;
  16124. this.maxAngularSpeed = 0;
  16125. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  16126. this.forceDepthWrite = false;
  16127. this.gravity = BABYLON.Vector3.Zero();
  16128. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  16129. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  16130. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  16131. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16132. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16133. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16134. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  16135. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16136. this.particles = new Array();
  16137. this._vertexDeclaration = [3, 4, 4];
  16138. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  16139. this._stockParticles = new Array();
  16140. this._newPartsExcess = 0;
  16141. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  16142. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  16143. this._scaledDirection = BABYLON.Vector3.Zero();
  16144. this._scaledGravity = BABYLON.Vector3.Zero();
  16145. this._currentRenderId = -1;
  16146. this._started = false;
  16147. this._stopped = false;
  16148. this._actualFrame = 0;
  16149. this.id = name;
  16150. this._capacity = capacity;
  16151. this._scene = scene;
  16152. this._customEffect = customEffect;
  16153. scene.particleSystems.push(this);
  16154. // VBO
  16155. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16156. var indices = [];
  16157. var index = 0;
  16158. for (var count = 0; count < capacity; count++) {
  16159. indices.push(index);
  16160. indices.push(index + 1);
  16161. indices.push(index + 2);
  16162. indices.push(index);
  16163. indices.push(index + 2);
  16164. indices.push(index + 3);
  16165. index += 4;
  16166. }
  16167. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16168. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16169. // Default behaviors
  16170. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  16171. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  16172. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  16173. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  16174. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  16175. };
  16176. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  16177. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  16178. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  16179. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  16180. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  16181. };
  16182. this.updateFunction = function (particles) {
  16183. for (var index = 0; index < particles.length; index++) {
  16184. var particle = particles[index];
  16185. particle.age += _this._scaledUpdateSpeed;
  16186. if (particle.age >= particle.lifeTime) {
  16187. _this.recycleParticle(particle);
  16188. index--;
  16189. continue;
  16190. }
  16191. else {
  16192. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  16193. particle.color.addInPlace(_this._scaledColorStep);
  16194. if (particle.color.a < 0)
  16195. particle.color.a = 0;
  16196. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  16197. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  16198. particle.position.addInPlace(_this._scaledDirection);
  16199. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  16200. particle.direction.addInPlace(_this._scaledGravity);
  16201. }
  16202. }
  16203. };
  16204. }
  16205. ParticleSystem.prototype.recycleParticle = function (particle) {
  16206. var lastParticle = this.particles.pop();
  16207. if (lastParticle !== particle) {
  16208. lastParticle.copyTo(particle);
  16209. this._stockParticles.push(lastParticle);
  16210. }
  16211. };
  16212. ParticleSystem.prototype.getCapacity = function () {
  16213. return this._capacity;
  16214. };
  16215. ParticleSystem.prototype.isAlive = function () {
  16216. return this._alive;
  16217. };
  16218. ParticleSystem.prototype.isStarted = function () {
  16219. return this._started;
  16220. };
  16221. ParticleSystem.prototype.start = function () {
  16222. this._started = true;
  16223. this._stopped = false;
  16224. this._actualFrame = 0;
  16225. };
  16226. ParticleSystem.prototype.stop = function () {
  16227. this._stopped = true;
  16228. };
  16229. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  16230. var offset = index * 11;
  16231. this._vertices[offset] = particle.position.x;
  16232. this._vertices[offset + 1] = particle.position.y;
  16233. this._vertices[offset + 2] = particle.position.z;
  16234. this._vertices[offset + 3] = particle.color.r;
  16235. this._vertices[offset + 4] = particle.color.g;
  16236. this._vertices[offset + 5] = particle.color.b;
  16237. this._vertices[offset + 6] = particle.color.a;
  16238. this._vertices[offset + 7] = particle.angle;
  16239. this._vertices[offset + 8] = particle.size;
  16240. this._vertices[offset + 9] = offsetX;
  16241. this._vertices[offset + 10] = offsetY;
  16242. };
  16243. ParticleSystem.prototype._update = function (newParticles) {
  16244. // Update current
  16245. this._alive = this.particles.length > 0;
  16246. this.updateFunction(this.particles);
  16247. // Add new ones
  16248. var worldMatrix;
  16249. if (this.emitter.position) {
  16250. worldMatrix = this.emitter.getWorldMatrix();
  16251. }
  16252. else {
  16253. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  16254. }
  16255. for (var index = 0; index < newParticles; index++) {
  16256. if (this.particles.length === this._capacity) {
  16257. break;
  16258. }
  16259. if (this._stockParticles.length !== 0) {
  16260. var particle = this._stockParticles.pop();
  16261. particle.age = 0;
  16262. }
  16263. else {
  16264. particle = new BABYLON.Particle();
  16265. }
  16266. this.particles.push(particle);
  16267. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  16268. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  16269. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  16270. particle.size = randomNumber(this.minSize, this.maxSize);
  16271. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  16272. this.startPositionFunction(worldMatrix, particle.position);
  16273. var step = randomNumber(0, 1.0);
  16274. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  16275. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  16276. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  16277. }
  16278. };
  16279. ParticleSystem.prototype._getEffect = function () {
  16280. if (this._customEffect) {
  16281. return this._customEffect;
  16282. }
  16283. ;
  16284. var defines = [];
  16285. if (this._scene.clipPlane) {
  16286. defines.push("#define CLIPPLANE");
  16287. }
  16288. // Effect
  16289. var join = defines.join("\n");
  16290. if (this._cachedDefines !== join) {
  16291. this._cachedDefines = join;
  16292. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16293. }
  16294. return this._effect;
  16295. };
  16296. ParticleSystem.prototype.animate = function () {
  16297. if (!this._started)
  16298. return;
  16299. var effect = this._getEffect();
  16300. // Check
  16301. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16302. return;
  16303. if (this._currentRenderId === this._scene.getRenderId()) {
  16304. return;
  16305. }
  16306. this._currentRenderId = this._scene.getRenderId();
  16307. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16308. // determine the number of particles we need to create
  16309. var emitCout;
  16310. if (this.manualEmitCount > -1) {
  16311. emitCout = this.manualEmitCount;
  16312. this.manualEmitCount = 0;
  16313. }
  16314. else {
  16315. emitCout = this.emitRate;
  16316. }
  16317. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16318. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16319. if (this._newPartsExcess > 1.0) {
  16320. newParticles += this._newPartsExcess >> 0;
  16321. this._newPartsExcess -= this._newPartsExcess >> 0;
  16322. }
  16323. this._alive = false;
  16324. if (!this._stopped) {
  16325. this._actualFrame += this._scaledUpdateSpeed;
  16326. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16327. this.stop();
  16328. }
  16329. else {
  16330. newParticles = 0;
  16331. }
  16332. this._update(newParticles);
  16333. // Stopped?
  16334. if (this._stopped) {
  16335. if (!this._alive) {
  16336. this._started = false;
  16337. if (this.disposeOnStop) {
  16338. this._scene._toBeDisposed.push(this);
  16339. }
  16340. }
  16341. }
  16342. // Update VBO
  16343. var offset = 0;
  16344. for (var index = 0; index < this.particles.length; index++) {
  16345. var particle = this.particles[index];
  16346. this._appendParticleVertex(offset++, particle, 0, 0);
  16347. this._appendParticleVertex(offset++, particle, 1, 0);
  16348. this._appendParticleVertex(offset++, particle, 1, 1);
  16349. this._appendParticleVertex(offset++, particle, 0, 1);
  16350. }
  16351. var engine = this._scene.getEngine();
  16352. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16353. };
  16354. ParticleSystem.prototype.render = function () {
  16355. var effect = this._getEffect();
  16356. // Check
  16357. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16358. return 0;
  16359. var engine = this._scene.getEngine();
  16360. // Render
  16361. engine.enableEffect(effect);
  16362. engine.setState(false);
  16363. var viewMatrix = this._scene.getViewMatrix();
  16364. effect.setTexture("diffuseSampler", this.particleTexture);
  16365. effect.setMatrix("view", viewMatrix);
  16366. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16367. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16368. if (this._scene.clipPlane) {
  16369. var clipPlane = this._scene.clipPlane;
  16370. var invView = viewMatrix.clone();
  16371. invView.invert();
  16372. effect.setMatrix("invView", invView);
  16373. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16374. }
  16375. // VBOs
  16376. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16377. // Draw order
  16378. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16379. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16380. }
  16381. else {
  16382. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16383. }
  16384. if (this.forceDepthWrite) {
  16385. engine.setDepthWrite(true);
  16386. }
  16387. engine.draw(true, 0, this.particles.length * 6);
  16388. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16389. return this.particles.length;
  16390. };
  16391. ParticleSystem.prototype.dispose = function () {
  16392. if (this._vertexBuffer) {
  16393. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16394. this._vertexBuffer = null;
  16395. }
  16396. if (this._indexBuffer) {
  16397. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16398. this._indexBuffer = null;
  16399. }
  16400. if (this.particleTexture) {
  16401. this.particleTexture.dispose();
  16402. this.particleTexture = null;
  16403. }
  16404. // Remove from scene
  16405. var index = this._scene.particleSystems.indexOf(this);
  16406. this._scene.particleSystems.splice(index, 1);
  16407. // Callback
  16408. if (this.onDispose) {
  16409. this.onDispose();
  16410. }
  16411. };
  16412. // Clone
  16413. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16414. var result = new ParticleSystem(name, this._capacity, this._scene);
  16415. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16416. if (newEmitter === undefined) {
  16417. newEmitter = this.emitter;
  16418. }
  16419. result.emitter = newEmitter;
  16420. if (this.particleTexture) {
  16421. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16422. }
  16423. result.start();
  16424. return result;
  16425. };
  16426. // Statics
  16427. ParticleSystem.BLENDMODE_ONEONE = 0;
  16428. ParticleSystem.BLENDMODE_STANDARD = 1;
  16429. return ParticleSystem;
  16430. })();
  16431. BABYLON.ParticleSystem = ParticleSystem;
  16432. })(BABYLON || (BABYLON = {}));
  16433. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16434. (function (BABYLON) {
  16435. var Animation = (function () {
  16436. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16437. this.name = name;
  16438. this.targetProperty = targetProperty;
  16439. this.framePerSecond = framePerSecond;
  16440. this.dataType = dataType;
  16441. this.loopMode = loopMode;
  16442. this._offsetsCache = {};
  16443. this._highLimitsCache = {};
  16444. this._stopped = false;
  16445. this.targetPropertyPath = targetProperty.split(".");
  16446. this.dataType = dataType;
  16447. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16448. }
  16449. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16450. var dataType = undefined;
  16451. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16452. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16453. }
  16454. else if (from instanceof BABYLON.Quaternion) {
  16455. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16456. }
  16457. else if (from instanceof BABYLON.Vector3) {
  16458. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16459. }
  16460. else if (from instanceof BABYLON.Vector2) {
  16461. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16462. }
  16463. else if (from instanceof BABYLON.Color3) {
  16464. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16465. }
  16466. if (dataType == undefined) {
  16467. return null;
  16468. }
  16469. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16470. var keys = [];
  16471. keys.push({ frame: 0, value: from });
  16472. keys.push({ frame: totalFrame, value: to });
  16473. animation.setKeys(keys);
  16474. mesh.animations.push(animation);
  16475. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16476. };
  16477. // Methods
  16478. Animation.prototype.isStopped = function () {
  16479. return this._stopped;
  16480. };
  16481. Animation.prototype.getKeys = function () {
  16482. return this._keys;
  16483. };
  16484. Animation.prototype.getEasingFunction = function () {
  16485. return this._easingFunction;
  16486. };
  16487. Animation.prototype.setEasingFunction = function (easingFunction) {
  16488. this._easingFunction = easingFunction;
  16489. };
  16490. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16491. return startValue + (endValue - startValue) * gradient;
  16492. };
  16493. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16494. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16495. };
  16496. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16497. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16498. };
  16499. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16500. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16501. };
  16502. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16503. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16504. };
  16505. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16506. var startScale = new BABYLON.Vector3(0, 0, 0);
  16507. var startRotation = new BABYLON.Quaternion();
  16508. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16509. startValue.decompose(startScale, startRotation, startTranslation);
  16510. var endScale = new BABYLON.Vector3(0, 0, 0);
  16511. var endRotation = new BABYLON.Quaternion();
  16512. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16513. endValue.decompose(endScale, endRotation, endTranslation);
  16514. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16515. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16516. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16517. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16518. return result;
  16519. };
  16520. Animation.prototype.clone = function () {
  16521. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16522. clone.setKeys(this._keys);
  16523. return clone;
  16524. };
  16525. Animation.prototype.setKeys = function (values) {
  16526. this._keys = values.slice(0);
  16527. this._offsetsCache = {};
  16528. this._highLimitsCache = {};
  16529. };
  16530. Animation.prototype._getKeyValue = function (value) {
  16531. if (typeof value === "function") {
  16532. return value();
  16533. }
  16534. return value;
  16535. };
  16536. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16537. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16538. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16539. }
  16540. this.currentFrame = currentFrame;
  16541. // Try to get a hash to find the right key
  16542. 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));
  16543. if (this._keys[startKey].frame >= currentFrame) {
  16544. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16545. startKey--;
  16546. }
  16547. }
  16548. for (var key = startKey; key < this._keys.length; key++) {
  16549. if (this._keys[key + 1].frame >= currentFrame) {
  16550. var startValue = this._getKeyValue(this._keys[key].value);
  16551. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16552. // gradient : percent of currentFrame between the frame inf and the frame sup
  16553. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16554. // check for easingFunction and correction of gradient
  16555. if (this._easingFunction != null) {
  16556. gradient = this._easingFunction.ease(gradient);
  16557. }
  16558. switch (this.dataType) {
  16559. case Animation.ANIMATIONTYPE_FLOAT:
  16560. switch (loopMode) {
  16561. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16562. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16563. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16564. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16565. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16566. }
  16567. break;
  16568. case Animation.ANIMATIONTYPE_QUATERNION:
  16569. var quaternion = null;
  16570. switch (loopMode) {
  16571. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16572. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16573. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16574. break;
  16575. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16576. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16577. break;
  16578. }
  16579. return quaternion;
  16580. case Animation.ANIMATIONTYPE_VECTOR3:
  16581. switch (loopMode) {
  16582. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16583. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16584. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16585. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16586. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16587. }
  16588. case Animation.ANIMATIONTYPE_VECTOR2:
  16589. switch (loopMode) {
  16590. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16591. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16592. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16593. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16594. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16595. }
  16596. case Animation.ANIMATIONTYPE_COLOR3:
  16597. switch (loopMode) {
  16598. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16599. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16600. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16601. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16602. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16603. }
  16604. case Animation.ANIMATIONTYPE_MATRIX:
  16605. switch (loopMode) {
  16606. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16607. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16608. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16609. return startValue;
  16610. }
  16611. default:
  16612. break;
  16613. }
  16614. break;
  16615. }
  16616. }
  16617. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16618. };
  16619. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16620. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16621. this._stopped = true;
  16622. return false;
  16623. }
  16624. var returnValue = true;
  16625. // Adding a start key at frame 0 if missing
  16626. if (this._keys[0].frame !== 0) {
  16627. var newKey = { frame: 0, value: this._keys[0].value };
  16628. this._keys.splice(0, 0, newKey);
  16629. }
  16630. // Check limits
  16631. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16632. from = this._keys[0].frame;
  16633. }
  16634. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16635. to = this._keys[this._keys.length - 1].frame;
  16636. }
  16637. // Compute ratio
  16638. var range = to - from;
  16639. var offsetValue;
  16640. // ratio represents the frame delta between from and to
  16641. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16642. var highLimitValue = 0;
  16643. if (ratio > range && !loop) {
  16644. returnValue = false;
  16645. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16646. }
  16647. else {
  16648. // Get max value if required
  16649. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16650. var keyOffset = to.toString() + from.toString();
  16651. if (!this._offsetsCache[keyOffset]) {
  16652. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16653. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16654. switch (this.dataType) {
  16655. case Animation.ANIMATIONTYPE_FLOAT:
  16656. this._offsetsCache[keyOffset] = toValue - fromValue;
  16657. break;
  16658. case Animation.ANIMATIONTYPE_QUATERNION:
  16659. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16660. break;
  16661. case Animation.ANIMATIONTYPE_VECTOR3:
  16662. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16663. case Animation.ANIMATIONTYPE_VECTOR2:
  16664. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16665. case Animation.ANIMATIONTYPE_COLOR3:
  16666. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16667. default:
  16668. break;
  16669. }
  16670. this._highLimitsCache[keyOffset] = toValue;
  16671. }
  16672. highLimitValue = this._highLimitsCache[keyOffset];
  16673. offsetValue = this._offsetsCache[keyOffset];
  16674. }
  16675. }
  16676. if (offsetValue === undefined) {
  16677. switch (this.dataType) {
  16678. case Animation.ANIMATIONTYPE_FLOAT:
  16679. offsetValue = 0;
  16680. break;
  16681. case Animation.ANIMATIONTYPE_QUATERNION:
  16682. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16683. break;
  16684. case Animation.ANIMATIONTYPE_VECTOR3:
  16685. offsetValue = BABYLON.Vector3.Zero();
  16686. break;
  16687. case Animation.ANIMATIONTYPE_VECTOR2:
  16688. offsetValue = BABYLON.Vector2.Zero();
  16689. break;
  16690. case Animation.ANIMATIONTYPE_COLOR3:
  16691. offsetValue = BABYLON.Color3.Black();
  16692. }
  16693. }
  16694. // Compute value
  16695. var repeatCount = (ratio / range) >> 0;
  16696. var currentFrame = returnValue ? from + ratio % range : to;
  16697. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16698. // Set value
  16699. if (this.targetPropertyPath.length > 1) {
  16700. var property = this._target[this.targetPropertyPath[0]];
  16701. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16702. property = property[this.targetPropertyPath[index]];
  16703. }
  16704. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16705. }
  16706. else {
  16707. this._target[this.targetPropertyPath[0]] = currentValue;
  16708. }
  16709. if (this._target.markAsDirty) {
  16710. this._target.markAsDirty(this.targetProperty);
  16711. }
  16712. if (!returnValue) {
  16713. this._stopped = true;
  16714. }
  16715. return returnValue;
  16716. };
  16717. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16718. get: function () {
  16719. return Animation._ANIMATIONTYPE_FLOAT;
  16720. },
  16721. enumerable: true,
  16722. configurable: true
  16723. });
  16724. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16725. get: function () {
  16726. return Animation._ANIMATIONTYPE_VECTOR3;
  16727. },
  16728. enumerable: true,
  16729. configurable: true
  16730. });
  16731. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16732. get: function () {
  16733. return Animation._ANIMATIONTYPE_VECTOR2;
  16734. },
  16735. enumerable: true,
  16736. configurable: true
  16737. });
  16738. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16739. get: function () {
  16740. return Animation._ANIMATIONTYPE_QUATERNION;
  16741. },
  16742. enumerable: true,
  16743. configurable: true
  16744. });
  16745. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16746. get: function () {
  16747. return Animation._ANIMATIONTYPE_MATRIX;
  16748. },
  16749. enumerable: true,
  16750. configurable: true
  16751. });
  16752. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16753. get: function () {
  16754. return Animation._ANIMATIONTYPE_COLOR3;
  16755. },
  16756. enumerable: true,
  16757. configurable: true
  16758. });
  16759. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16760. get: function () {
  16761. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16762. },
  16763. enumerable: true,
  16764. configurable: true
  16765. });
  16766. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16767. get: function () {
  16768. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16769. },
  16770. enumerable: true,
  16771. configurable: true
  16772. });
  16773. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16774. get: function () {
  16775. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16776. },
  16777. enumerable: true,
  16778. configurable: true
  16779. });
  16780. // Statics
  16781. Animation._ANIMATIONTYPE_FLOAT = 0;
  16782. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16783. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16784. Animation._ANIMATIONTYPE_MATRIX = 3;
  16785. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16786. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16787. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16788. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16789. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16790. return Animation;
  16791. })();
  16792. BABYLON.Animation = Animation;
  16793. })(BABYLON || (BABYLON = {}));
  16794. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16795. (function (BABYLON) {
  16796. var Animatable = (function () {
  16797. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16798. if (fromFrame === void 0) { fromFrame = 0; }
  16799. if (toFrame === void 0) { toFrame = 100; }
  16800. if (loopAnimation === void 0) { loopAnimation = false; }
  16801. if (speedRatio === void 0) { speedRatio = 1.0; }
  16802. this.target = target;
  16803. this.fromFrame = fromFrame;
  16804. this.toFrame = toFrame;
  16805. this.loopAnimation = loopAnimation;
  16806. this.speedRatio = speedRatio;
  16807. this.onAnimationEnd = onAnimationEnd;
  16808. this._animations = new Array();
  16809. this._paused = false;
  16810. this.animationStarted = false;
  16811. if (animations) {
  16812. this.appendAnimations(target, animations);
  16813. }
  16814. this._scene = scene;
  16815. scene._activeAnimatables.push(this);
  16816. }
  16817. // Methods
  16818. Animatable.prototype.appendAnimations = function (target, animations) {
  16819. for (var index = 0; index < animations.length; index++) {
  16820. var animation = animations[index];
  16821. animation._target = target;
  16822. this._animations.push(animation);
  16823. }
  16824. };
  16825. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16826. var animations = this._animations;
  16827. for (var index = 0; index < animations.length; index++) {
  16828. if (animations[index].targetProperty === property) {
  16829. return animations[index];
  16830. }
  16831. }
  16832. return null;
  16833. };
  16834. Animatable.prototype.pause = function () {
  16835. if (this._paused) {
  16836. return;
  16837. }
  16838. this._paused = true;
  16839. };
  16840. Animatable.prototype.restart = function () {
  16841. this._paused = false;
  16842. };
  16843. Animatable.prototype.stop = function () {
  16844. var index = this._scene._activeAnimatables.indexOf(this);
  16845. if (index > -1) {
  16846. this._scene._activeAnimatables.splice(index, 1);
  16847. }
  16848. if (this.onAnimationEnd) {
  16849. this.onAnimationEnd();
  16850. }
  16851. };
  16852. Animatable.prototype._animate = function (delay) {
  16853. if (this._paused) {
  16854. if (!this._pausedDelay) {
  16855. this._pausedDelay = delay;
  16856. }
  16857. return true;
  16858. }
  16859. if (!this._localDelayOffset) {
  16860. this._localDelayOffset = delay;
  16861. }
  16862. else if (this._pausedDelay) {
  16863. this._localDelayOffset += delay - this._pausedDelay;
  16864. this._pausedDelay = null;
  16865. }
  16866. // Animating
  16867. var running = false;
  16868. var animations = this._animations;
  16869. for (var index = 0; index < animations.length; index++) {
  16870. var animation = animations[index];
  16871. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16872. running = running || isRunning;
  16873. }
  16874. if (!running) {
  16875. // Remove from active animatables
  16876. index = this._scene._activeAnimatables.indexOf(this);
  16877. this._scene._activeAnimatables.splice(index, 1);
  16878. }
  16879. if (!running && this.onAnimationEnd) {
  16880. this.onAnimationEnd();
  16881. }
  16882. return running;
  16883. };
  16884. return Animatable;
  16885. })();
  16886. BABYLON.Animatable = Animatable;
  16887. })(BABYLON || (BABYLON = {}));
  16888. //# sourceMappingURL=babylon.animatable.js.map
  16889. var BABYLON;
  16890. (function (BABYLON) {
  16891. var EasingFunction = (function () {
  16892. function EasingFunction() {
  16893. // Properties
  16894. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16895. }
  16896. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16897. get: function () {
  16898. return EasingFunction._EASINGMODE_EASEIN;
  16899. },
  16900. enumerable: true,
  16901. configurable: true
  16902. });
  16903. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16904. get: function () {
  16905. return EasingFunction._EASINGMODE_EASEOUT;
  16906. },
  16907. enumerable: true,
  16908. configurable: true
  16909. });
  16910. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16911. get: function () {
  16912. return EasingFunction._EASINGMODE_EASEINOUT;
  16913. },
  16914. enumerable: true,
  16915. configurable: true
  16916. });
  16917. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16918. var n = Math.min(Math.max(easingMode, 0), 2);
  16919. this._easingMode = n;
  16920. };
  16921. EasingFunction.prototype.getEasingMode = function () {
  16922. return this._easingMode;
  16923. };
  16924. EasingFunction.prototype.easeInCore = function (gradient) {
  16925. throw new Error('You must implement this method');
  16926. };
  16927. EasingFunction.prototype.ease = function (gradient) {
  16928. switch (this._easingMode) {
  16929. case EasingFunction.EASINGMODE_EASEIN:
  16930. return this.easeInCore(gradient);
  16931. case EasingFunction.EASINGMODE_EASEOUT:
  16932. return (1 - this.easeInCore(1 - gradient));
  16933. }
  16934. if (gradient >= 0.5) {
  16935. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16936. }
  16937. return (this.easeInCore(gradient * 2) * 0.5);
  16938. };
  16939. //Statics
  16940. EasingFunction._EASINGMODE_EASEIN = 0;
  16941. EasingFunction._EASINGMODE_EASEOUT = 1;
  16942. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16943. return EasingFunction;
  16944. })();
  16945. BABYLON.EasingFunction = EasingFunction;
  16946. var CircleEase = (function (_super) {
  16947. __extends(CircleEase, _super);
  16948. function CircleEase() {
  16949. _super.apply(this, arguments);
  16950. }
  16951. CircleEase.prototype.easeInCore = function (gradient) {
  16952. gradient = Math.max(0, Math.min(1, gradient));
  16953. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16954. };
  16955. return CircleEase;
  16956. })(EasingFunction);
  16957. BABYLON.CircleEase = CircleEase;
  16958. var BackEase = (function (_super) {
  16959. __extends(BackEase, _super);
  16960. function BackEase(amplitude) {
  16961. if (amplitude === void 0) { amplitude = 1; }
  16962. _super.call(this);
  16963. this.amplitude = amplitude;
  16964. }
  16965. BackEase.prototype.easeInCore = function (gradient) {
  16966. var num = Math.max(0, this.amplitude);
  16967. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16968. };
  16969. return BackEase;
  16970. })(EasingFunction);
  16971. BABYLON.BackEase = BackEase;
  16972. var BounceEase = (function (_super) {
  16973. __extends(BounceEase, _super);
  16974. function BounceEase(bounces, bounciness) {
  16975. if (bounces === void 0) { bounces = 3; }
  16976. if (bounciness === void 0) { bounciness = 2; }
  16977. _super.call(this);
  16978. this.bounces = bounces;
  16979. this.bounciness = bounciness;
  16980. }
  16981. BounceEase.prototype.easeInCore = function (gradient) {
  16982. var y = Math.max(0.0, this.bounces);
  16983. var bounciness = this.bounciness;
  16984. if (bounciness <= 1.0) {
  16985. bounciness = 1.001;
  16986. }
  16987. var num9 = Math.pow(bounciness, y);
  16988. var num5 = 1.0 - bounciness;
  16989. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16990. var num15 = gradient * num4;
  16991. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16992. var num3 = Math.floor(num65);
  16993. var num13 = num3 + 1.0;
  16994. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16995. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16996. var num7 = (num8 + num12) * 0.5;
  16997. var num6 = gradient - num7;
  16998. var num2 = num7 - num8;
  16999. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  17000. };
  17001. return BounceEase;
  17002. })(EasingFunction);
  17003. BABYLON.BounceEase = BounceEase;
  17004. var CubicEase = (function (_super) {
  17005. __extends(CubicEase, _super);
  17006. function CubicEase() {
  17007. _super.apply(this, arguments);
  17008. }
  17009. CubicEase.prototype.easeInCore = function (gradient) {
  17010. return (gradient * gradient * gradient);
  17011. };
  17012. return CubicEase;
  17013. })(EasingFunction);
  17014. BABYLON.CubicEase = CubicEase;
  17015. var ElasticEase = (function (_super) {
  17016. __extends(ElasticEase, _super);
  17017. function ElasticEase(oscillations, springiness) {
  17018. if (oscillations === void 0) { oscillations = 3; }
  17019. if (springiness === void 0) { springiness = 3; }
  17020. _super.call(this);
  17021. this.oscillations = oscillations;
  17022. this.springiness = springiness;
  17023. }
  17024. ElasticEase.prototype.easeInCore = function (gradient) {
  17025. var num2;
  17026. var num3 = Math.max(0.0, this.oscillations);
  17027. var num = Math.max(0.0, this.springiness);
  17028. if (num == 0) {
  17029. num2 = gradient;
  17030. }
  17031. else {
  17032. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  17033. }
  17034. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  17035. };
  17036. return ElasticEase;
  17037. })(EasingFunction);
  17038. BABYLON.ElasticEase = ElasticEase;
  17039. var ExponentialEase = (function (_super) {
  17040. __extends(ExponentialEase, _super);
  17041. function ExponentialEase(exponent) {
  17042. if (exponent === void 0) { exponent = 2; }
  17043. _super.call(this);
  17044. this.exponent = exponent;
  17045. }
  17046. ExponentialEase.prototype.easeInCore = function (gradient) {
  17047. if (this.exponent <= 0) {
  17048. return gradient;
  17049. }
  17050. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  17051. };
  17052. return ExponentialEase;
  17053. })(EasingFunction);
  17054. BABYLON.ExponentialEase = ExponentialEase;
  17055. var PowerEase = (function (_super) {
  17056. __extends(PowerEase, _super);
  17057. function PowerEase(power) {
  17058. if (power === void 0) { power = 2; }
  17059. _super.call(this);
  17060. this.power = power;
  17061. }
  17062. PowerEase.prototype.easeInCore = function (gradient) {
  17063. var y = Math.max(0.0, this.power);
  17064. return Math.pow(gradient, y);
  17065. };
  17066. return PowerEase;
  17067. })(EasingFunction);
  17068. BABYLON.PowerEase = PowerEase;
  17069. var QuadraticEase = (function (_super) {
  17070. __extends(QuadraticEase, _super);
  17071. function QuadraticEase() {
  17072. _super.apply(this, arguments);
  17073. }
  17074. QuadraticEase.prototype.easeInCore = function (gradient) {
  17075. return (gradient * gradient);
  17076. };
  17077. return QuadraticEase;
  17078. })(EasingFunction);
  17079. BABYLON.QuadraticEase = QuadraticEase;
  17080. var QuarticEase = (function (_super) {
  17081. __extends(QuarticEase, _super);
  17082. function QuarticEase() {
  17083. _super.apply(this, arguments);
  17084. }
  17085. QuarticEase.prototype.easeInCore = function (gradient) {
  17086. return (gradient * gradient * gradient * gradient);
  17087. };
  17088. return QuarticEase;
  17089. })(EasingFunction);
  17090. BABYLON.QuarticEase = QuarticEase;
  17091. var QuinticEase = (function (_super) {
  17092. __extends(QuinticEase, _super);
  17093. function QuinticEase() {
  17094. _super.apply(this, arguments);
  17095. }
  17096. QuinticEase.prototype.easeInCore = function (gradient) {
  17097. return (gradient * gradient * gradient * gradient * gradient);
  17098. };
  17099. return QuinticEase;
  17100. })(EasingFunction);
  17101. BABYLON.QuinticEase = QuinticEase;
  17102. var SineEase = (function (_super) {
  17103. __extends(SineEase, _super);
  17104. function SineEase() {
  17105. _super.apply(this, arguments);
  17106. }
  17107. SineEase.prototype.easeInCore = function (gradient) {
  17108. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  17109. };
  17110. return SineEase;
  17111. })(EasingFunction);
  17112. BABYLON.SineEase = SineEase;
  17113. var BezierCurveEase = (function (_super) {
  17114. __extends(BezierCurveEase, _super);
  17115. function BezierCurveEase(x1, y1, x2, y2) {
  17116. if (x1 === void 0) { x1 = 0; }
  17117. if (y1 === void 0) { y1 = 0; }
  17118. if (x2 === void 0) { x2 = 1; }
  17119. if (y2 === void 0) { y2 = 1; }
  17120. _super.call(this);
  17121. this.x1 = x1;
  17122. this.y1 = y1;
  17123. this.x2 = x2;
  17124. this.y2 = y2;
  17125. }
  17126. BezierCurveEase.prototype.easeInCore = function (gradient) {
  17127. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  17128. };
  17129. return BezierCurveEase;
  17130. })(EasingFunction);
  17131. BABYLON.BezierCurveEase = BezierCurveEase;
  17132. })(BABYLON || (BABYLON = {}));
  17133. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  17134. (function (BABYLON) {
  17135. var Octree = (function () {
  17136. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  17137. if (maxDepth === void 0) { maxDepth = 2; }
  17138. this.maxDepth = maxDepth;
  17139. this.dynamicContent = new Array();
  17140. this._maxBlockCapacity = maxBlockCapacity || 64;
  17141. this._selectionContent = new BABYLON.SmartArray(1024);
  17142. this._creationFunc = creationFunc;
  17143. }
  17144. // Methods
  17145. Octree.prototype.update = function (worldMin, worldMax, entries) {
  17146. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  17147. };
  17148. Octree.prototype.addMesh = function (entry) {
  17149. for (var index = 0; index < this.blocks.length; index++) {
  17150. var block = this.blocks[index];
  17151. block.addEntry(entry);
  17152. }
  17153. };
  17154. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  17155. this._selectionContent.reset();
  17156. for (var index = 0; index < this.blocks.length; index++) {
  17157. var block = this.blocks[index];
  17158. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  17159. }
  17160. if (allowDuplicate) {
  17161. this._selectionContent.concat(this.dynamicContent);
  17162. }
  17163. else {
  17164. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17165. }
  17166. return this._selectionContent;
  17167. };
  17168. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  17169. this._selectionContent.reset();
  17170. for (var index = 0; index < this.blocks.length; index++) {
  17171. var block = this.blocks[index];
  17172. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  17173. }
  17174. if (allowDuplicate) {
  17175. this._selectionContent.concat(this.dynamicContent);
  17176. }
  17177. else {
  17178. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17179. }
  17180. return this._selectionContent;
  17181. };
  17182. Octree.prototype.intersectsRay = function (ray) {
  17183. this._selectionContent.reset();
  17184. for (var index = 0; index < this.blocks.length; index++) {
  17185. var block = this.blocks[index];
  17186. block.intersectsRay(ray, this._selectionContent);
  17187. }
  17188. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17189. return this._selectionContent;
  17190. };
  17191. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  17192. target.blocks = new Array();
  17193. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  17194. for (var x = 0; x < 2; x++) {
  17195. for (var y = 0; y < 2; y++) {
  17196. for (var z = 0; z < 2; z++) {
  17197. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  17198. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  17199. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  17200. block.addEntries(entries);
  17201. target.blocks.push(block);
  17202. }
  17203. }
  17204. }
  17205. };
  17206. Octree.CreationFuncForMeshes = function (entry, block) {
  17207. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17208. block.entries.push(entry);
  17209. }
  17210. };
  17211. Octree.CreationFuncForSubMeshes = function (entry, block) {
  17212. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17213. block.entries.push(entry);
  17214. }
  17215. };
  17216. return Octree;
  17217. })();
  17218. BABYLON.Octree = Octree;
  17219. })(BABYLON || (BABYLON = {}));
  17220. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  17221. (function (BABYLON) {
  17222. var OctreeBlock = (function () {
  17223. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  17224. this.entries = new Array();
  17225. this._boundingVectors = new Array();
  17226. this._capacity = capacity;
  17227. this._depth = depth;
  17228. this._maxDepth = maxDepth;
  17229. this._creationFunc = creationFunc;
  17230. this._minPoint = minPoint;
  17231. this._maxPoint = maxPoint;
  17232. this._boundingVectors.push(minPoint.clone());
  17233. this._boundingVectors.push(maxPoint.clone());
  17234. this._boundingVectors.push(minPoint.clone());
  17235. this._boundingVectors[2].x = maxPoint.x;
  17236. this._boundingVectors.push(minPoint.clone());
  17237. this._boundingVectors[3].y = maxPoint.y;
  17238. this._boundingVectors.push(minPoint.clone());
  17239. this._boundingVectors[4].z = maxPoint.z;
  17240. this._boundingVectors.push(maxPoint.clone());
  17241. this._boundingVectors[5].z = minPoint.z;
  17242. this._boundingVectors.push(maxPoint.clone());
  17243. this._boundingVectors[6].x = minPoint.x;
  17244. this._boundingVectors.push(maxPoint.clone());
  17245. this._boundingVectors[7].y = minPoint.y;
  17246. }
  17247. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  17248. // Property
  17249. get: function () {
  17250. return this._capacity;
  17251. },
  17252. enumerable: true,
  17253. configurable: true
  17254. });
  17255. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  17256. get: function () {
  17257. return this._minPoint;
  17258. },
  17259. enumerable: true,
  17260. configurable: true
  17261. });
  17262. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  17263. get: function () {
  17264. return this._maxPoint;
  17265. },
  17266. enumerable: true,
  17267. configurable: true
  17268. });
  17269. // Methods
  17270. OctreeBlock.prototype.addEntry = function (entry) {
  17271. if (this.blocks) {
  17272. for (var index = 0; index < this.blocks.length; index++) {
  17273. var block = this.blocks[index];
  17274. block.addEntry(entry);
  17275. }
  17276. return;
  17277. }
  17278. this._creationFunc(entry, this);
  17279. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  17280. this.createInnerBlocks();
  17281. }
  17282. };
  17283. OctreeBlock.prototype.addEntries = function (entries) {
  17284. for (var index = 0; index < entries.length; index++) {
  17285. var mesh = entries[index];
  17286. this.addEntry(mesh);
  17287. }
  17288. };
  17289. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17290. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17291. if (this.blocks) {
  17292. for (var index = 0; index < this.blocks.length; index++) {
  17293. var block = this.blocks[index];
  17294. block.select(frustumPlanes, selection, allowDuplicate);
  17295. }
  17296. return;
  17297. }
  17298. if (allowDuplicate) {
  17299. selection.concat(this.entries);
  17300. }
  17301. else {
  17302. selection.concatWithNoDuplicate(this.entries);
  17303. }
  17304. }
  17305. };
  17306. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17307. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17308. if (this.blocks) {
  17309. for (var index = 0; index < this.blocks.length; index++) {
  17310. var block = this.blocks[index];
  17311. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17312. }
  17313. return;
  17314. }
  17315. if (allowDuplicate) {
  17316. selection.concat(this.entries);
  17317. }
  17318. else {
  17319. selection.concatWithNoDuplicate(this.entries);
  17320. }
  17321. }
  17322. };
  17323. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17324. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17325. if (this.blocks) {
  17326. for (var index = 0; index < this.blocks.length; index++) {
  17327. var block = this.blocks[index];
  17328. block.intersectsRay(ray, selection);
  17329. }
  17330. return;
  17331. }
  17332. selection.concatWithNoDuplicate(this.entries);
  17333. }
  17334. };
  17335. OctreeBlock.prototype.createInnerBlocks = function () {
  17336. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17337. };
  17338. return OctreeBlock;
  17339. })();
  17340. BABYLON.OctreeBlock = OctreeBlock;
  17341. })(BABYLON || (BABYLON = {}));
  17342. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17343. (function (BABYLON) {
  17344. var Bone = (function () {
  17345. function Bone(name, skeleton, parentBone, matrix) {
  17346. this.name = name;
  17347. this.children = new Array();
  17348. this.animations = new Array();
  17349. this._worldTransform = new BABYLON.Matrix();
  17350. this._absoluteTransform = new BABYLON.Matrix();
  17351. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17352. this._skeleton = skeleton;
  17353. this._matrix = matrix;
  17354. this._baseMatrix = matrix;
  17355. skeleton.bones.push(this);
  17356. if (parentBone) {
  17357. this._parent = parentBone;
  17358. parentBone.children.push(this);
  17359. }
  17360. else {
  17361. this._parent = null;
  17362. }
  17363. this._updateDifferenceMatrix();
  17364. }
  17365. // Members
  17366. Bone.prototype.getParent = function () {
  17367. return this._parent;
  17368. };
  17369. Bone.prototype.getLocalMatrix = function () {
  17370. return this._matrix;
  17371. };
  17372. Bone.prototype.getBaseMatrix = function () {
  17373. return this._baseMatrix;
  17374. };
  17375. Bone.prototype.getWorldMatrix = function () {
  17376. return this._worldTransform;
  17377. };
  17378. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17379. return this._invertedAbsoluteTransform;
  17380. };
  17381. Bone.prototype.getAbsoluteMatrix = function () {
  17382. var matrix = this._matrix.clone();
  17383. var parent = this._parent;
  17384. while (parent) {
  17385. matrix = matrix.multiply(parent.getLocalMatrix());
  17386. parent = parent.getParent();
  17387. }
  17388. return matrix;
  17389. };
  17390. // Methods
  17391. Bone.prototype.updateMatrix = function (matrix) {
  17392. this._matrix = matrix;
  17393. this._skeleton._markAsDirty();
  17394. this._updateDifferenceMatrix();
  17395. };
  17396. Bone.prototype._updateDifferenceMatrix = function () {
  17397. if (this._parent) {
  17398. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17399. }
  17400. else {
  17401. this._absoluteTransform.copyFrom(this._matrix);
  17402. }
  17403. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17404. for (var index = 0; index < this.children.length; index++) {
  17405. this.children[index]._updateDifferenceMatrix();
  17406. }
  17407. };
  17408. Bone.prototype.markAsDirty = function () {
  17409. this._skeleton._markAsDirty();
  17410. };
  17411. return Bone;
  17412. })();
  17413. BABYLON.Bone = Bone;
  17414. })(BABYLON || (BABYLON = {}));
  17415. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17416. (function (BABYLON) {
  17417. var Skeleton = (function () {
  17418. function Skeleton(name, id, scene) {
  17419. this.name = name;
  17420. this.id = id;
  17421. this.bones = new Array();
  17422. this._isDirty = true;
  17423. this._identity = BABYLON.Matrix.Identity();
  17424. this.bones = [];
  17425. this._scene = scene;
  17426. scene.skeletons.push(this);
  17427. this.prepare();
  17428. //make sure it will recalculate the matrix next time prepare is called.
  17429. this._isDirty = true;
  17430. }
  17431. // Members
  17432. Skeleton.prototype.getTransformMatrices = function () {
  17433. return this._transformMatrices;
  17434. };
  17435. // Methods
  17436. Skeleton.prototype._markAsDirty = function () {
  17437. this._isDirty = true;
  17438. };
  17439. Skeleton.prototype.prepare = function () {
  17440. if (!this._isDirty) {
  17441. return;
  17442. }
  17443. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17444. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17445. }
  17446. for (var index = 0; index < this.bones.length; index++) {
  17447. var bone = this.bones[index];
  17448. var parentBone = bone.getParent();
  17449. if (parentBone) {
  17450. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17451. }
  17452. else {
  17453. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17454. }
  17455. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17456. }
  17457. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17458. this._isDirty = false;
  17459. this._scene._activeBones += this.bones.length;
  17460. };
  17461. Skeleton.prototype.getAnimatables = function () {
  17462. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17463. this._animatables = [];
  17464. for (var index = 0; index < this.bones.length; index++) {
  17465. this._animatables.push(this.bones[index]);
  17466. }
  17467. }
  17468. return this._animatables;
  17469. };
  17470. Skeleton.prototype.clone = function (name, id) {
  17471. var result = new Skeleton(name, id || name, this._scene);
  17472. for (var index = 0; index < this.bones.length; index++) {
  17473. var source = this.bones[index];
  17474. var parentBone = null;
  17475. if (source.getParent()) {
  17476. var parentIndex = this.bones.indexOf(source.getParent());
  17477. parentBone = result.bones[parentIndex];
  17478. }
  17479. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17480. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17481. }
  17482. return result;
  17483. };
  17484. return Skeleton;
  17485. })();
  17486. BABYLON.Skeleton = Skeleton;
  17487. })(BABYLON || (BABYLON = {}));
  17488. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17489. (function (BABYLON) {
  17490. var PostProcess = (function () {
  17491. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17493. this.name = name;
  17494. this.width = -1;
  17495. this.height = -1;
  17496. this._reusable = false;
  17497. this._textures = new BABYLON.SmartArray(2);
  17498. this._currentRenderTextureInd = 0;
  17499. if (camera != null) {
  17500. this._camera = camera;
  17501. this._scene = camera.getScene();
  17502. camera.attachPostProcess(this);
  17503. this._engine = this._scene.getEngine();
  17504. }
  17505. else {
  17506. this._engine = engine;
  17507. }
  17508. this._renderRatio = ratio;
  17509. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17510. this._reusable = reusable || false;
  17511. samplers = samplers || [];
  17512. samplers.push("textureSampler");
  17513. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17514. }
  17515. PostProcess.prototype.isReusable = function () {
  17516. return this._reusable;
  17517. };
  17518. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17519. camera = camera || this._camera;
  17520. var scene = camera.getScene();
  17521. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17522. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17523. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17524. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17525. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17526. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17527. if (this._textures.length > 0) {
  17528. for (var i = 0; i < this._textures.length; i++) {
  17529. this._engine._releaseTexture(this._textures.data[i]);
  17530. }
  17531. this._textures.reset();
  17532. }
  17533. this.width = desiredWidth;
  17534. this.height = desiredHeight;
  17535. 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 }));
  17536. if (this._reusable) {
  17537. 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 }));
  17538. }
  17539. if (this.onSizeChanged) {
  17540. this.onSizeChanged();
  17541. }
  17542. }
  17543. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17544. if (this.onActivate) {
  17545. this.onActivate(camera);
  17546. }
  17547. // Clear
  17548. if (this.clearColor) {
  17549. this._engine.clear(this.clearColor, true, true);
  17550. }
  17551. else {
  17552. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17553. }
  17554. if (this._reusable) {
  17555. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17556. }
  17557. };
  17558. PostProcess.prototype.apply = function () {
  17559. // Check
  17560. if (!this._effect.isReady())
  17561. return null;
  17562. // States
  17563. this._engine.enableEffect(this._effect);
  17564. this._engine.setState(false);
  17565. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17566. this._engine.setDepthBuffer(false);
  17567. this._engine.setDepthWrite(false);
  17568. // Texture
  17569. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17570. // Parameters
  17571. if (this.onApply) {
  17572. this.onApply(this._effect);
  17573. }
  17574. return this._effect;
  17575. };
  17576. PostProcess.prototype.dispose = function (camera) {
  17577. camera = camera || this._camera;
  17578. if (this._textures.length > 0) {
  17579. for (var i = 0; i < this._textures.length; i++) {
  17580. this._engine._releaseTexture(this._textures.data[i]);
  17581. }
  17582. this._textures.reset();
  17583. }
  17584. if (!camera) {
  17585. return;
  17586. }
  17587. camera.detachPostProcess(this);
  17588. var index = camera._postProcesses.indexOf(this);
  17589. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17590. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17591. }
  17592. };
  17593. return PostProcess;
  17594. })();
  17595. BABYLON.PostProcess = PostProcess;
  17596. })(BABYLON || (BABYLON = {}));
  17597. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17598. (function (BABYLON) {
  17599. var PostProcessManager = (function () {
  17600. function PostProcessManager(scene) {
  17601. this._vertexDeclaration = [2];
  17602. this._vertexStrideSize = 2 * 4;
  17603. this._scene = scene;
  17604. }
  17605. PostProcessManager.prototype._prepareBuffers = function () {
  17606. if (this._vertexBuffer) {
  17607. return;
  17608. }
  17609. // VBO
  17610. var vertices = [];
  17611. vertices.push(1, 1);
  17612. vertices.push(-1, 1);
  17613. vertices.push(-1, -1);
  17614. vertices.push(1, -1);
  17615. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  17616. // Indices
  17617. var indices = [];
  17618. indices.push(0);
  17619. indices.push(1);
  17620. indices.push(2);
  17621. indices.push(0);
  17622. indices.push(2);
  17623. indices.push(3);
  17624. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  17625. };
  17626. // Methods
  17627. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17628. var postProcesses = this._scene.activeCamera._postProcesses;
  17629. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17630. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17631. return false;
  17632. }
  17633. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17634. return true;
  17635. };
  17636. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17637. var engine = this._scene.getEngine();
  17638. for (var index = 0; index < postProcesses.length; index++) {
  17639. if (index < postProcesses.length - 1) {
  17640. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17641. }
  17642. else {
  17643. if (targetTexture) {
  17644. engine.bindFramebuffer(targetTexture);
  17645. }
  17646. else {
  17647. engine.restoreDefaultFramebuffer();
  17648. }
  17649. }
  17650. var pp = postProcesses[index];
  17651. var effect = pp.apply();
  17652. if (effect) {
  17653. if (pp.onBeforeRender) {
  17654. pp.onBeforeRender(effect);
  17655. }
  17656. // VBOs
  17657. this._prepareBuffers();
  17658. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17659. // Draw order
  17660. engine.draw(true, 0, 6);
  17661. }
  17662. }
  17663. // Restore depth buffer
  17664. engine.setDepthBuffer(true);
  17665. engine.setDepthWrite(true);
  17666. };
  17667. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17668. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17669. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17670. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17671. return;
  17672. }
  17673. var engine = this._scene.getEngine();
  17674. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17675. if (index < postProcessesTakenIndices.length - 1) {
  17676. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17677. }
  17678. else {
  17679. if (targetTexture) {
  17680. engine.bindFramebuffer(targetTexture);
  17681. }
  17682. else {
  17683. engine.restoreDefaultFramebuffer();
  17684. }
  17685. }
  17686. if (doNotPresent) {
  17687. break;
  17688. }
  17689. var pp = postProcesses[postProcessesTakenIndices[index]];
  17690. var effect = pp.apply();
  17691. if (effect) {
  17692. if (pp.onBeforeRender) {
  17693. pp.onBeforeRender(effect);
  17694. }
  17695. // VBOs
  17696. this._prepareBuffers();
  17697. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17698. // Draw order
  17699. engine.draw(true, 0, 6);
  17700. }
  17701. }
  17702. // Restore depth buffer
  17703. engine.setDepthBuffer(true);
  17704. engine.setDepthWrite(true);
  17705. };
  17706. PostProcessManager.prototype.dispose = function () {
  17707. if (this._vertexBuffer) {
  17708. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17709. this._vertexBuffer = null;
  17710. }
  17711. if (this._indexBuffer) {
  17712. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17713. this._indexBuffer = null;
  17714. }
  17715. };
  17716. return PostProcessManager;
  17717. })();
  17718. BABYLON.PostProcessManager = PostProcessManager;
  17719. })(BABYLON || (BABYLON = {}));
  17720. //# sourceMappingURL=babylon.postProcessManager.js.map
  17721. var BABYLON;
  17722. (function (BABYLON) {
  17723. var PassPostProcess = (function (_super) {
  17724. __extends(PassPostProcess, _super);
  17725. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17726. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17727. }
  17728. return PassPostProcess;
  17729. })(BABYLON.PostProcess);
  17730. BABYLON.PassPostProcess = PassPostProcess;
  17731. })(BABYLON || (BABYLON = {}));
  17732. //# sourceMappingURL=babylon.passPostProcess.js.map
  17733. var BABYLON;
  17734. (function (BABYLON) {
  17735. var BlurPostProcess = (function (_super) {
  17736. __extends(BlurPostProcess, _super);
  17737. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17738. var _this = this;
  17739. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17740. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17741. this.direction = direction;
  17742. this.blurWidth = blurWidth;
  17743. this.onApply = function (effect) {
  17744. effect.setFloat2("screenSize", _this.width, _this.height);
  17745. effect.setVector2("direction", _this.direction);
  17746. effect.setFloat("blurWidth", _this.blurWidth);
  17747. };
  17748. }
  17749. return BlurPostProcess;
  17750. })(BABYLON.PostProcess);
  17751. BABYLON.BlurPostProcess = BlurPostProcess;
  17752. })(BABYLON || (BABYLON = {}));
  17753. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17754. var BABYLON;
  17755. (function (BABYLON) {
  17756. var FilterPostProcess = (function (_super) {
  17757. __extends(FilterPostProcess, _super);
  17758. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17759. var _this = this;
  17760. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17761. this.kernelMatrix = kernelMatrix;
  17762. this.onApply = function (effect) {
  17763. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17764. };
  17765. }
  17766. return FilterPostProcess;
  17767. })(BABYLON.PostProcess);
  17768. BABYLON.FilterPostProcess = FilterPostProcess;
  17769. })(BABYLON || (BABYLON = {}));
  17770. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17771. var BABYLON;
  17772. (function (BABYLON) {
  17773. var RefractionPostProcess = (function (_super) {
  17774. __extends(RefractionPostProcess, _super);
  17775. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17776. var _this = this;
  17777. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17778. this.color = color;
  17779. this.depth = depth;
  17780. this.colorLevel = colorLevel;
  17781. this.onActivate = function (cam) {
  17782. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17783. };
  17784. this.onApply = function (effect) {
  17785. effect.setColor3("baseColor", _this.color);
  17786. effect.setFloat("depth", _this.depth);
  17787. effect.setFloat("colorLevel", _this.colorLevel);
  17788. effect.setTexture("refractionSampler", _this._refRexture);
  17789. };
  17790. }
  17791. // Methods
  17792. RefractionPostProcess.prototype.dispose = function (camera) {
  17793. if (this._refRexture) {
  17794. this._refRexture.dispose();
  17795. }
  17796. _super.prototype.dispose.call(this, camera);
  17797. };
  17798. return RefractionPostProcess;
  17799. })(BABYLON.PostProcess);
  17800. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17801. })(BABYLON || (BABYLON = {}));
  17802. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17803. var BABYLON;
  17804. (function (BABYLON) {
  17805. var BlackAndWhitePostProcess = (function (_super) {
  17806. __extends(BlackAndWhitePostProcess, _super);
  17807. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17808. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17809. }
  17810. return BlackAndWhitePostProcess;
  17811. })(BABYLON.PostProcess);
  17812. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17813. })(BABYLON || (BABYLON = {}));
  17814. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17815. var BABYLON;
  17816. (function (BABYLON) {
  17817. var ConvolutionPostProcess = (function (_super) {
  17818. __extends(ConvolutionPostProcess, _super);
  17819. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17820. var _this = this;
  17821. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17822. this.kernel = kernel;
  17823. this.onApply = function (effect) {
  17824. effect.setFloat2("screenSize", _this.width, _this.height);
  17825. effect.setArray("kernel", _this.kernel);
  17826. };
  17827. }
  17828. // Statics
  17829. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17830. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17831. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17832. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17833. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17834. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17835. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17836. return ConvolutionPostProcess;
  17837. })(BABYLON.PostProcess);
  17838. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17839. })(BABYLON || (BABYLON = {}));
  17840. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17841. var BABYLON;
  17842. (function (BABYLON) {
  17843. var FxaaPostProcess = (function (_super) {
  17844. __extends(FxaaPostProcess, _super);
  17845. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17846. var _this = this;
  17847. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17848. this.onSizeChanged = function () {
  17849. _this.texelWidth = 1.0 / _this.width;
  17850. _this.texelHeight = 1.0 / _this.height;
  17851. };
  17852. this.onApply = function (effect) {
  17853. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17854. };
  17855. }
  17856. return FxaaPostProcess;
  17857. })(BABYLON.PostProcess);
  17858. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17859. })(BABYLON || (BABYLON = {}));
  17860. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17861. (function (BABYLON) {
  17862. var LensFlare = (function () {
  17863. function LensFlare(size, position, color, imgUrl, system) {
  17864. this.size = size;
  17865. this.position = position;
  17866. this.dispose = function () {
  17867. if (this.texture) {
  17868. this.texture.dispose();
  17869. }
  17870. // Remove from scene
  17871. var index = this._system.lensFlares.indexOf(this);
  17872. this._system.lensFlares.splice(index, 1);
  17873. };
  17874. this.color = color || new BABYLON.Color3(1, 1, 1);
  17875. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17876. this._system = system;
  17877. system.lensFlares.push(this);
  17878. }
  17879. return LensFlare;
  17880. })();
  17881. BABYLON.LensFlare = LensFlare;
  17882. })(BABYLON || (BABYLON = {}));
  17883. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17884. (function (BABYLON) {
  17885. var LensFlareSystem = (function () {
  17886. function LensFlareSystem(name, emitter, scene) {
  17887. this.name = name;
  17888. this.lensFlares = new Array();
  17889. this.borderLimit = 300;
  17890. this._vertexDeclaration = [2];
  17891. this._vertexStrideSize = 2 * 4;
  17892. this._isEnabled = true;
  17893. this._scene = scene;
  17894. this._emitter = emitter;
  17895. scene.lensFlareSystems.push(this);
  17896. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17897. // VBO
  17898. var vertices = [];
  17899. vertices.push(1, 1);
  17900. vertices.push(-1, 1);
  17901. vertices.push(-1, -1);
  17902. vertices.push(1, -1);
  17903. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17904. // Indices
  17905. var indices = [];
  17906. indices.push(0);
  17907. indices.push(1);
  17908. indices.push(2);
  17909. indices.push(0);
  17910. indices.push(2);
  17911. indices.push(3);
  17912. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17913. // Effects
  17914. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17915. }
  17916. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17917. get: function () {
  17918. return this._isEnabled;
  17919. },
  17920. set: function (value) {
  17921. this._isEnabled = value;
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. LensFlareSystem.prototype.getScene = function () {
  17927. return this._scene;
  17928. };
  17929. LensFlareSystem.prototype.getEmitter = function () {
  17930. return this._emitter;
  17931. };
  17932. LensFlareSystem.prototype.getEmitterPosition = function () {
  17933. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17934. };
  17935. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17936. var position = this.getEmitterPosition();
  17937. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17938. this._positionX = position.x;
  17939. this._positionY = position.y;
  17940. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17941. if (position.z > 0) {
  17942. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17943. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17944. return true;
  17945. }
  17946. }
  17947. return false;
  17948. };
  17949. LensFlareSystem.prototype._isVisible = function () {
  17950. if (!this._isEnabled) {
  17951. return false;
  17952. }
  17953. var emitterPosition = this.getEmitterPosition();
  17954. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17955. var distance = direction.length();
  17956. direction.normalize();
  17957. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17958. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17959. return !pickInfo.hit || pickInfo.distance > distance;
  17960. };
  17961. LensFlareSystem.prototype.render = function () {
  17962. if (!this._effect.isReady())
  17963. return false;
  17964. var engine = this._scene.getEngine();
  17965. var viewport = this._scene.activeCamera.viewport;
  17966. var globalViewport = viewport.toGlobal(engine);
  17967. // Position
  17968. if (!this.computeEffectivePosition(globalViewport)) {
  17969. return false;
  17970. }
  17971. // Visibility
  17972. if (!this._isVisible()) {
  17973. return false;
  17974. }
  17975. // Intensity
  17976. var awayX;
  17977. var awayY;
  17978. if (this._positionX < this.borderLimit + globalViewport.x) {
  17979. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17980. }
  17981. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17982. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17983. }
  17984. else {
  17985. awayX = 0;
  17986. }
  17987. if (this._positionY < this.borderLimit + globalViewport.y) {
  17988. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17989. }
  17990. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17991. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17992. }
  17993. else {
  17994. awayY = 0;
  17995. }
  17996. var away = (awayX > awayY) ? awayX : awayY;
  17997. if (away > this.borderLimit) {
  17998. away = this.borderLimit;
  17999. }
  18000. var intensity = 1.0 - (away / this.borderLimit);
  18001. if (intensity < 0) {
  18002. return false;
  18003. }
  18004. if (intensity > 1.0) {
  18005. intensity = 1.0;
  18006. }
  18007. // Position
  18008. var centerX = globalViewport.x + globalViewport.width / 2;
  18009. var centerY = globalViewport.y + globalViewport.height / 2;
  18010. var distX = centerX - this._positionX;
  18011. var distY = centerY - this._positionY;
  18012. // Effects
  18013. engine.enableEffect(this._effect);
  18014. engine.setState(false);
  18015. engine.setDepthBuffer(false);
  18016. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  18017. // VBOs
  18018. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18019. for (var index = 0; index < this.lensFlares.length; index++) {
  18020. var flare = this.lensFlares[index];
  18021. var x = centerX - (distX * flare.position);
  18022. var y = centerY - (distY * flare.position);
  18023. var cw = flare.size;
  18024. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  18025. var cx = 2 * (x / globalViewport.width) - 1.0;
  18026. var cy = 1.0 - 2 * (y / globalViewport.height);
  18027. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  18028. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  18029. // Texture
  18030. this._effect.setTexture("textureSampler", flare.texture);
  18031. // Color
  18032. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  18033. // Draw order
  18034. engine.draw(true, 0, 6);
  18035. }
  18036. engine.setDepthBuffer(true);
  18037. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18038. return true;
  18039. };
  18040. LensFlareSystem.prototype.dispose = function () {
  18041. if (this._vertexBuffer) {
  18042. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18043. this._vertexBuffer = null;
  18044. }
  18045. if (this._indexBuffer) {
  18046. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18047. this._indexBuffer = null;
  18048. }
  18049. while (this.lensFlares.length) {
  18050. this.lensFlares[0].dispose();
  18051. }
  18052. // Remove from scene
  18053. var index = this._scene.lensFlareSystems.indexOf(this);
  18054. this._scene.lensFlareSystems.splice(index, 1);
  18055. };
  18056. return LensFlareSystem;
  18057. })();
  18058. BABYLON.LensFlareSystem = LensFlareSystem;
  18059. })(BABYLON || (BABYLON = {}));
  18060. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  18061. (function (BABYLON) {
  18062. var IntersectionInfo = (function () {
  18063. function IntersectionInfo(bu, bv, distance) {
  18064. this.bu = bu;
  18065. this.bv = bv;
  18066. this.distance = distance;
  18067. this.faceId = 0;
  18068. this.subMeshId = 0;
  18069. }
  18070. return IntersectionInfo;
  18071. })();
  18072. BABYLON.IntersectionInfo = IntersectionInfo;
  18073. var PickingInfo = (function () {
  18074. function PickingInfo() {
  18075. this.hit = false;
  18076. this.distance = 0;
  18077. this.pickedPoint = null;
  18078. this.pickedMesh = null;
  18079. this.bu = 0;
  18080. this.bv = 0;
  18081. this.faceId = -1;
  18082. this.subMeshId = 0;
  18083. }
  18084. // Methods
  18085. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  18086. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  18087. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18088. return null;
  18089. }
  18090. var indices = this.pickedMesh.getIndices();
  18091. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18092. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  18093. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  18094. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  18095. normal0 = normal0.scale(this.bu);
  18096. normal1 = normal1.scale(this.bv);
  18097. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  18098. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  18099. if (useWorldCoordinates) {
  18100. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  18101. }
  18102. return result;
  18103. };
  18104. PickingInfo.prototype.getTextureCoordinates = function () {
  18105. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18106. return null;
  18107. }
  18108. var indices = this.pickedMesh.getIndices();
  18109. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18110. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  18111. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  18112. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  18113. uv0 = uv0.scale(this.bu);
  18114. uv1 = uv1.scale(this.bv);
  18115. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  18116. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  18117. };
  18118. return PickingInfo;
  18119. })();
  18120. BABYLON.PickingInfo = PickingInfo;
  18121. })(BABYLON || (BABYLON = {}));
  18122. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  18123. (function (BABYLON) {
  18124. var FilesInput = (function () {
  18125. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  18126. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  18127. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  18128. this._engine = p_engine;
  18129. this._canvas = p_canvas;
  18130. this._currentScene = p_scene;
  18131. this._sceneLoadedCallback = p_sceneLoadedCallback;
  18132. this._progressCallback = p_progressCallback;
  18133. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  18134. this._textureLoadingCallback = p_textureLoadingCallback;
  18135. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  18136. }
  18137. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  18138. var _this = this;
  18139. if (p_elementToMonitor) {
  18140. this._elementToMonitor = p_elementToMonitor;
  18141. this._elementToMonitor.addEventListener("dragenter", function (e) {
  18142. _this.drag(e);
  18143. }, false);
  18144. this._elementToMonitor.addEventListener("dragover", function (e) {
  18145. _this.drag(e);
  18146. }, false);
  18147. this._elementToMonitor.addEventListener("drop", function (e) {
  18148. _this.drop(e);
  18149. }, false);
  18150. }
  18151. };
  18152. FilesInput.prototype.renderFunction = function () {
  18153. if (this._additionnalRenderLoopLogicCallback) {
  18154. this._additionnalRenderLoopLogicCallback();
  18155. }
  18156. if (this._currentScene) {
  18157. if (this._textureLoadingCallback) {
  18158. var remaining = this._currentScene.getWaitingItemsCount();
  18159. if (remaining > 0) {
  18160. this._textureLoadingCallback(remaining);
  18161. }
  18162. }
  18163. this._currentScene.render();
  18164. }
  18165. };
  18166. FilesInput.prototype.drag = function (e) {
  18167. e.stopPropagation();
  18168. e.preventDefault();
  18169. };
  18170. FilesInput.prototype.drop = function (eventDrop) {
  18171. eventDrop.stopPropagation();
  18172. eventDrop.preventDefault();
  18173. this.loadFiles(eventDrop);
  18174. };
  18175. FilesInput.prototype.loadFiles = function (event) {
  18176. if (this._startingProcessingFilesCallback)
  18177. this._startingProcessingFilesCallback();
  18178. // Handling data transfer via drag'n'drop
  18179. if (event && event.dataTransfer && event.dataTransfer.files) {
  18180. this._filesToLoad = event.dataTransfer.files;
  18181. }
  18182. // Handling files from input files
  18183. if (event && event.target && event.target.files) {
  18184. this._filesToLoad = event.target.files;
  18185. }
  18186. if (this._filesToLoad && this._filesToLoad.length > 0) {
  18187. for (var i = 0; i < this._filesToLoad.length; i++) {
  18188. switch (this._filesToLoad[i].type) {
  18189. case "image/jpeg":
  18190. case "image/png":
  18191. case "image/bmp":
  18192. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  18193. break;
  18194. case "image/targa":
  18195. case "image/vnd.ms-dds":
  18196. case "audio/wav":
  18197. case "audio/x-wav":
  18198. case "audio/mp3":
  18199. case "audio/mpeg":
  18200. case "audio/mpeg3":
  18201. case "audio/x-mpeg-3":
  18202. case "audio/ogg":
  18203. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  18204. break;
  18205. default:
  18206. 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) {
  18207. this._sceneFileToLoad = this._filesToLoad[i];
  18208. }
  18209. break;
  18210. }
  18211. }
  18212. this.reload();
  18213. }
  18214. };
  18215. FilesInput.prototype.reload = function () {
  18216. var _this = this;
  18217. var that = this;
  18218. // If a ".babylon" file has been provided
  18219. if (this._sceneFileToLoad) {
  18220. if (this._currentScene) {
  18221. this._engine.stopRenderLoop();
  18222. this._currentScene.dispose();
  18223. }
  18224. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  18225. that._currentScene = newScene;
  18226. // Wait for textures and shaders to be ready
  18227. that._currentScene.executeWhenReady(function () {
  18228. // Attach camera to canvas inputs
  18229. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  18230. that._currentScene.createDefaultCameraOrLight();
  18231. }
  18232. that._currentScene.activeCamera.attachControl(that._canvas);
  18233. if (that._sceneLoadedCallback) {
  18234. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  18235. }
  18236. that._engine.runRenderLoop(function () {
  18237. that.renderFunction();
  18238. });
  18239. });
  18240. }, function (progress) {
  18241. if (_this._progressCallback) {
  18242. _this._progressCallback(progress);
  18243. }
  18244. });
  18245. }
  18246. else {
  18247. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  18248. }
  18249. };
  18250. FilesInput.FilesTextures = new Array();
  18251. FilesInput.FilesToLoad = new Array();
  18252. return FilesInput;
  18253. })();
  18254. BABYLON.FilesInput = FilesInput;
  18255. })(BABYLON || (BABYLON = {}));
  18256. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  18257. (function (BABYLON) {
  18258. var OimoJSPlugin = (function () {
  18259. function OimoJSPlugin() {
  18260. this._registeredMeshes = [];
  18261. /**
  18262. * Update the body position according to the mesh position
  18263. * @param mesh
  18264. */
  18265. this.updateBodyPosition = function (mesh) {
  18266. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18267. var registeredMesh = this._registeredMeshes[index];
  18268. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18269. var body = registeredMesh.body.body;
  18270. mesh.computeWorldMatrix(true);
  18271. var center = mesh.getBoundingInfo().boundingBox.center;
  18272. body.setPosition(center.x, center.y, center.z);
  18273. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  18274. return;
  18275. }
  18276. // Case where the parent has been updated
  18277. if (registeredMesh.mesh.parent === mesh) {
  18278. mesh.computeWorldMatrix(true);
  18279. registeredMesh.mesh.computeWorldMatrix(true);
  18280. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  18281. var absoluteRotation = mesh.rotation;
  18282. body = registeredMesh.body.body;
  18283. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  18284. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  18285. return;
  18286. }
  18287. }
  18288. };
  18289. }
  18290. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  18291. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18292. };
  18293. OimoJSPlugin.prototype.initialize = function (iterations) {
  18294. this._world = new OIMO.World();
  18295. this._world.clear();
  18296. };
  18297. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18298. this._world.gravity = gravity;
  18299. };
  18300. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18301. var body = null;
  18302. this.unregisterMesh(mesh);
  18303. mesh.computeWorldMatrix(true);
  18304. var initialRotation = null;
  18305. if (mesh.rotationQuaternion) {
  18306. initialRotation = mesh.rotationQuaternion.clone();
  18307. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18308. mesh.computeWorldMatrix(true);
  18309. }
  18310. var bbox = mesh.getBoundingInfo().boundingBox;
  18311. // The delta between the mesh position and the mesh bounding box center
  18312. var deltaPosition = mesh.position.subtract(bbox.center);
  18313. // Transform delta position with the rotation
  18314. if (initialRotation) {
  18315. var m = new BABYLON.Matrix();
  18316. initialRotation.toRotationMatrix(m);
  18317. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18318. }
  18319. switch (impostor) {
  18320. case BABYLON.PhysicsEngine.SphereImpostor:
  18321. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18322. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18323. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18324. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18325. body = new OIMO.Body({
  18326. type: 'sphere',
  18327. size: [size],
  18328. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18329. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18330. move: options.mass != 0,
  18331. config: [options.mass, options.friction, options.restitution],
  18332. world: this._world
  18333. });
  18334. break;
  18335. case BABYLON.PhysicsEngine.PlaneImpostor:
  18336. case BABYLON.PhysicsEngine.CylinderImpostor:
  18337. case BABYLON.PhysicsEngine.BoxImpostor:
  18338. var min = bbox.minimumWorld;
  18339. var max = bbox.maximumWorld;
  18340. var box = max.subtract(min);
  18341. var sizeX = this._checkWithEpsilon(box.x);
  18342. var sizeY = this._checkWithEpsilon(box.y);
  18343. var sizeZ = this._checkWithEpsilon(box.z);
  18344. body = new OIMO.Body({
  18345. type: 'box',
  18346. size: [sizeX, sizeY, sizeZ],
  18347. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18348. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18349. move: options.mass != 0,
  18350. config: [options.mass, options.friction, options.restitution],
  18351. world: this._world
  18352. });
  18353. break;
  18354. }
  18355. //If quaternion was set as the rotation of the object
  18356. if (initialRotation) {
  18357. //We have to access the rigid body's properties to set the quaternion.
  18358. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18359. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18360. //update the internal rotation matrix
  18361. body.body.syncShapes();
  18362. }
  18363. this._registeredMeshes.push({
  18364. mesh: mesh,
  18365. body: body,
  18366. delta: deltaPosition
  18367. });
  18368. return body;
  18369. };
  18370. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18371. var types = [], sizes = [], positions = [], rotations = [];
  18372. var initialMesh = parts[0].mesh;
  18373. for (var index = 0; index < parts.length; index++) {
  18374. var part = parts[index];
  18375. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18376. types.push(bodyParameters.type);
  18377. sizes.push.apply(sizes, bodyParameters.size);
  18378. positions.push.apply(positions, bodyParameters.pos);
  18379. rotations.push.apply(rotations, bodyParameters.rot);
  18380. }
  18381. var body = new OIMO.Body({
  18382. type: types,
  18383. size: sizes,
  18384. pos: positions,
  18385. rot: rotations,
  18386. move: options.mass != 0,
  18387. config: [options.mass, options.friction, options.restitution],
  18388. world: this._world
  18389. });
  18390. this._registeredMeshes.push({
  18391. mesh: initialMesh,
  18392. body: body
  18393. });
  18394. return body;
  18395. };
  18396. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18397. var bodyParameters = null;
  18398. var mesh = part.mesh;
  18399. // We need the bounding box/sphere info to compute the physics body
  18400. mesh.computeWorldMatrix();
  18401. switch (part.impostor) {
  18402. case BABYLON.PhysicsEngine.SphereImpostor:
  18403. var bbox = mesh.getBoundingInfo().boundingBox;
  18404. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18405. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18406. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18407. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18408. bodyParameters = {
  18409. type: 'sphere',
  18410. /* bug with oimo : sphere needs 3 sizes in this case */
  18411. size: [size, -1, -1],
  18412. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18413. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18414. };
  18415. break;
  18416. case BABYLON.PhysicsEngine.PlaneImpostor:
  18417. case BABYLON.PhysicsEngine.BoxImpostor:
  18418. bbox = mesh.getBoundingInfo().boundingBox;
  18419. var min = bbox.minimumWorld;
  18420. var max = bbox.maximumWorld;
  18421. var box = max.subtract(min);
  18422. var sizeX = this._checkWithEpsilon(box.x);
  18423. var sizeY = this._checkWithEpsilon(box.y);
  18424. var sizeZ = this._checkWithEpsilon(box.z);
  18425. var relativePosition = mesh.position;
  18426. bodyParameters = {
  18427. type: 'box',
  18428. size: [sizeX, sizeY, sizeZ],
  18429. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18430. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18431. };
  18432. break;
  18433. }
  18434. return bodyParameters;
  18435. };
  18436. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18437. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18438. var registeredMesh = this._registeredMeshes[index];
  18439. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18440. if (registeredMesh.body) {
  18441. this._world.removeRigidBody(registeredMesh.body.body);
  18442. this._unbindBody(registeredMesh.body);
  18443. }
  18444. this._registeredMeshes.splice(index, 1);
  18445. return;
  18446. }
  18447. }
  18448. };
  18449. OimoJSPlugin.prototype._unbindBody = function (body) {
  18450. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18451. var registeredMesh = this._registeredMeshes[index];
  18452. if (registeredMesh.body === body) {
  18453. registeredMesh.body = null;
  18454. }
  18455. }
  18456. };
  18457. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18458. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18459. var registeredMesh = this._registeredMeshes[index];
  18460. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18461. // Get object mass to have a behaviour similar to cannon.js
  18462. var mass = registeredMesh.body.body.massInfo.mass;
  18463. // The force is scaled with the mass of object
  18464. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18465. return;
  18466. }
  18467. }
  18468. };
  18469. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18470. var body1 = null, body2 = null;
  18471. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18472. var registeredMesh = this._registeredMeshes[index];
  18473. if (registeredMesh.mesh === mesh1) {
  18474. body1 = registeredMesh.body.body;
  18475. }
  18476. else if (registeredMesh.mesh === mesh2) {
  18477. body2 = registeredMesh.body.body;
  18478. }
  18479. }
  18480. if (!body1 || !body2) {
  18481. return false;
  18482. }
  18483. if (!options) {
  18484. options = {};
  18485. }
  18486. new OIMO.Link({
  18487. type: options.type,
  18488. body1: body1,
  18489. body2: body2,
  18490. min: options.min,
  18491. max: options.max,
  18492. axe1: options.axe1,
  18493. axe2: options.axe2,
  18494. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18495. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18496. collision: options.collision,
  18497. spring: options.spring,
  18498. world: this._world
  18499. });
  18500. return true;
  18501. };
  18502. OimoJSPlugin.prototype.dispose = function () {
  18503. this._world.clear();
  18504. while (this._registeredMeshes.length) {
  18505. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18506. }
  18507. };
  18508. OimoJSPlugin.prototype.isSupported = function () {
  18509. return OIMO !== undefined;
  18510. };
  18511. OimoJSPlugin.prototype._getLastShape = function (body) {
  18512. var lastShape = body.shapes;
  18513. while (lastShape.next) {
  18514. lastShape = lastShape.next;
  18515. }
  18516. return lastShape;
  18517. };
  18518. OimoJSPlugin.prototype.runOneStep = function (time) {
  18519. this._world.step();
  18520. // Update the position of all registered meshes
  18521. var i = this._registeredMeshes.length;
  18522. var m;
  18523. while (i--) {
  18524. var body = this._registeredMeshes[i].body.body;
  18525. var mesh = this._registeredMeshes[i].mesh;
  18526. var delta = this._registeredMeshes[i].delta;
  18527. if (!body.sleeping) {
  18528. if (body.shapes.next) {
  18529. var parentShape = this._getLastShape(body);
  18530. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18531. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18532. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18533. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18534. if (!mesh.rotationQuaternion) {
  18535. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18536. }
  18537. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18538. mesh.computeWorldMatrix();
  18539. }
  18540. else {
  18541. m = body.getMatrix();
  18542. mtx = BABYLON.Matrix.FromArray(m);
  18543. // Body position
  18544. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18545. if (!delta) {
  18546. mesh.position.x = bodyX;
  18547. mesh.position.y = bodyY;
  18548. mesh.position.z = bodyZ;
  18549. }
  18550. else {
  18551. mesh.position.x = bodyX + delta.x;
  18552. mesh.position.y = bodyY + delta.y;
  18553. mesh.position.z = bodyZ + delta.z;
  18554. }
  18555. if (!mesh.rotationQuaternion) {
  18556. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18557. }
  18558. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18559. mesh.computeWorldMatrix();
  18560. }
  18561. }
  18562. }
  18563. };
  18564. return OimoJSPlugin;
  18565. })();
  18566. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18567. })(BABYLON || (BABYLON = {}));
  18568. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18569. (function (BABYLON) {
  18570. var PhysicsEngine = (function () {
  18571. function PhysicsEngine(plugin) {
  18572. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18573. }
  18574. PhysicsEngine.prototype._initialize = function (gravity) {
  18575. this._currentPlugin.initialize();
  18576. this._setGravity(gravity);
  18577. };
  18578. PhysicsEngine.prototype._runOneStep = function (delta) {
  18579. if (delta > 0.1) {
  18580. delta = 0.1;
  18581. }
  18582. else if (delta <= 0) {
  18583. delta = 1.0 / 60.0;
  18584. }
  18585. this._currentPlugin.runOneStep(delta);
  18586. };
  18587. PhysicsEngine.prototype._setGravity = function (gravity) {
  18588. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18589. this._currentPlugin.setGravity(this.gravity);
  18590. };
  18591. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18592. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18593. };
  18594. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18595. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18596. };
  18597. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18598. this._currentPlugin.unregisterMesh(mesh);
  18599. };
  18600. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18601. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18602. };
  18603. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18604. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18605. };
  18606. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18607. this._currentPlugin.updateBodyPosition(mesh);
  18608. };
  18609. PhysicsEngine.prototype.dispose = function () {
  18610. this._currentPlugin.dispose();
  18611. };
  18612. PhysicsEngine.prototype.isSupported = function () {
  18613. return this._currentPlugin.isSupported();
  18614. };
  18615. // Statics
  18616. PhysicsEngine.NoImpostor = 0;
  18617. PhysicsEngine.SphereImpostor = 1;
  18618. PhysicsEngine.BoxImpostor = 2;
  18619. PhysicsEngine.PlaneImpostor = 3;
  18620. PhysicsEngine.MeshImpostor = 4;
  18621. PhysicsEngine.CapsuleImpostor = 5;
  18622. PhysicsEngine.ConeImpostor = 6;
  18623. PhysicsEngine.CylinderImpostor = 7;
  18624. PhysicsEngine.ConvexHullImpostor = 8;
  18625. PhysicsEngine.Epsilon = 0.001;
  18626. return PhysicsEngine;
  18627. })();
  18628. BABYLON.PhysicsEngine = PhysicsEngine;
  18629. })(BABYLON || (BABYLON = {}));
  18630. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18631. (function (BABYLON) {
  18632. var serializeLight = function (light) {
  18633. var serializationObject = {};
  18634. serializationObject.name = light.name;
  18635. serializationObject.id = light.id;
  18636. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18637. if (light instanceof BABYLON.PointLight) {
  18638. serializationObject.type = 0;
  18639. serializationObject.position = light.position.asArray();
  18640. }
  18641. else if (light instanceof BABYLON.DirectionalLight) {
  18642. serializationObject.type = 1;
  18643. var directionalLight = light;
  18644. serializationObject.position = directionalLight.position.asArray();
  18645. serializationObject.direction = directionalLight.direction.asArray();
  18646. }
  18647. else if (light instanceof BABYLON.SpotLight) {
  18648. serializationObject.type = 2;
  18649. var spotLight = light;
  18650. serializationObject.position = spotLight.position.asArray();
  18651. serializationObject.direction = spotLight.position.asArray();
  18652. serializationObject.angle = spotLight.angle;
  18653. serializationObject.exponent = spotLight.exponent;
  18654. }
  18655. else if (light instanceof BABYLON.HemisphericLight) {
  18656. serializationObject.type = 3;
  18657. var hemisphericLight = light;
  18658. serializationObject.direction = hemisphericLight.direction.asArray();
  18659. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18660. }
  18661. if (light.intensity) {
  18662. serializationObject.intensity = light.intensity;
  18663. }
  18664. serializationObject.range = light.range;
  18665. serializationObject.diffuse = light.diffuse.asArray();
  18666. serializationObject.specular = light.specular.asArray();
  18667. return serializationObject;
  18668. };
  18669. var serializeFresnelParameter = function (fresnelParameter) {
  18670. var serializationObject = {};
  18671. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18672. serializationObject.leftColor = fresnelParameter.leftColor;
  18673. serializationObject.rightColor = fresnelParameter.rightColor;
  18674. serializationObject.bias = fresnelParameter.bias;
  18675. serializationObject.power = fresnelParameter.power;
  18676. return serializationObject;
  18677. };
  18678. var appendAnimations = function (source, destination) {
  18679. if (source.animations) {
  18680. destination.animations = [];
  18681. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18682. var animation = source.animations[animationIndex];
  18683. destination.animations.push(serializeAnimation(animation));
  18684. }
  18685. }
  18686. };
  18687. var serializeCamera = function (camera) {
  18688. var serializationObject = {};
  18689. serializationObject.name = camera.name;
  18690. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18691. serializationObject.id = camera.id;
  18692. serializationObject.position = camera.position.asArray();
  18693. // Parent
  18694. if (camera.parent) {
  18695. serializationObject.parentId = camera.parent.id;
  18696. }
  18697. serializationObject.fov = camera.fov;
  18698. serializationObject.minZ = camera.minZ;
  18699. serializationObject.maxZ = camera.maxZ;
  18700. serializationObject.inertia = camera.inertia;
  18701. //setting the type
  18702. if (camera instanceof BABYLON.FreeCamera) {
  18703. serializationObject.type = "FreeCamera";
  18704. }
  18705. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18706. serializationObject.type = "ArcRotateCamera";
  18707. }
  18708. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18709. serializationObject.type = "AnaglyphArcRotateCamera";
  18710. }
  18711. else if (camera instanceof BABYLON.GamepadCamera) {
  18712. serializationObject.type = "GamepadCamera";
  18713. }
  18714. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18715. serializationObject.type = "AnaglyphFreeCamera";
  18716. }
  18717. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18718. serializationObject.type = "DeviceOrientationCamera";
  18719. }
  18720. else if (camera instanceof BABYLON.FollowCamera) {
  18721. serializationObject.type = "FollowCamera";
  18722. }
  18723. else if (camera instanceof BABYLON.OculusCamera) {
  18724. serializationObject.type = "OculusCamera";
  18725. }
  18726. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18727. serializationObject.type = "OculusGamepadCamera";
  18728. }
  18729. else if (camera instanceof BABYLON.TouchCamera) {
  18730. serializationObject.type = "TouchCamera";
  18731. }
  18732. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18733. serializationObject.type = "VirtualJoysticksCamera";
  18734. }
  18735. else if (camera instanceof BABYLON.WebVRCamera) {
  18736. serializationObject.type = "WebVRCamera";
  18737. }
  18738. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18739. serializationObject.type = "VRDeviceOrientationCamera";
  18740. }
  18741. //special properties of specific cameras
  18742. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18743. var arcCamera = camera;
  18744. serializationObject.alpha = arcCamera.alpha;
  18745. serializationObject.beta = arcCamera.beta;
  18746. serializationObject.radius = arcCamera.radius;
  18747. if (arcCamera.target && arcCamera.target.id) {
  18748. serializationObject.lockedTargetId = arcCamera.target.id;
  18749. }
  18750. }
  18751. else if (camera instanceof BABYLON.FollowCamera) {
  18752. var followCam = camera;
  18753. serializationObject.radius = followCam.radius;
  18754. serializationObject.heightOffset = followCam.heightOffset;
  18755. serializationObject.rotationOffset = followCam.rotationOffset;
  18756. }
  18757. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18758. //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.
  18759. if (camera['_eyeSpace'] !== undefined) {
  18760. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18761. }
  18762. }
  18763. //general properties that not all cameras have. The [] is due to typescript's type safety
  18764. if (camera['speed'] !== undefined) {
  18765. serializationObject.speed = camera['speed'];
  18766. }
  18767. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18768. serializationObject.target = camera['target'].asArray();
  18769. }
  18770. // Target
  18771. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18772. serializationObject.rotation = camera['rotation'].asArray();
  18773. }
  18774. // Locked target
  18775. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18776. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18777. }
  18778. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18779. serializationObject.applyGravity = camera['applyGravity'] || false;
  18780. if (camera['ellipsoid']) {
  18781. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18782. }
  18783. // Animations
  18784. appendAnimations(camera, serializationObject);
  18785. // Layer mask
  18786. serializationObject.layerMask = camera.layerMask;
  18787. return serializationObject;
  18788. };
  18789. var serializeAnimation = function (animation) {
  18790. var serializationObject = {};
  18791. serializationObject.name = animation.name;
  18792. serializationObject.property = animation.targetProperty;
  18793. serializationObject.framePerSecond = animation.framePerSecond;
  18794. serializationObject.dataType = animation.dataType;
  18795. serializationObject.loopBehavior = animation.loopMode;
  18796. var dataType = animation.dataType;
  18797. serializationObject.keys = [];
  18798. var keys = animation.getKeys();
  18799. for (var index = 0; index < keys.length; index++) {
  18800. var animationKey = keys[index];
  18801. var key = {};
  18802. key.frame = animationKey.frame;
  18803. switch (dataType) {
  18804. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18805. key.values = [animationKey.value];
  18806. break;
  18807. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18808. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18809. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18810. key.values = animationKey.value.asArray();
  18811. break;
  18812. }
  18813. serializationObject.keys.push(key);
  18814. }
  18815. return serializationObject;
  18816. };
  18817. var serializeMultiMaterial = function (material) {
  18818. var serializationObject = {};
  18819. serializationObject.name = material.name;
  18820. serializationObject.id = material.id;
  18821. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18822. serializationObject.materials = [];
  18823. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18824. var subMat = material.subMaterials[matIndex];
  18825. if (subMat) {
  18826. serializationObject.materials.push(subMat.id);
  18827. }
  18828. else {
  18829. serializationObject.materials.push(null);
  18830. }
  18831. }
  18832. return serializationObject;
  18833. };
  18834. var serializeMaterial = function (material) {
  18835. var serializationObject = {};
  18836. serializationObject.name = material.name;
  18837. serializationObject.ambient = material.ambientColor.asArray();
  18838. serializationObject.diffuse = material.diffuseColor.asArray();
  18839. serializationObject.specular = material.specularColor.asArray();
  18840. serializationObject.specularPower = material.specularPower;
  18841. serializationObject.emissive = material.emissiveColor.asArray();
  18842. serializationObject.alpha = material.alpha;
  18843. serializationObject.id = material.id;
  18844. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18845. serializationObject.backFaceCulling = material.backFaceCulling;
  18846. if (material.diffuseTexture) {
  18847. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18848. }
  18849. if (material.diffuseFresnelParameters) {
  18850. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18851. }
  18852. if (material.ambientTexture) {
  18853. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18854. }
  18855. if (material.opacityTexture) {
  18856. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18857. }
  18858. if (material.opacityFresnelParameters) {
  18859. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18860. }
  18861. if (material.reflectionTexture) {
  18862. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18863. }
  18864. if (material.reflectionFresnelParameters) {
  18865. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18866. }
  18867. if (material.emissiveTexture) {
  18868. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18869. }
  18870. if (material.emissiveFresnelParameters) {
  18871. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18872. }
  18873. if (material.specularTexture) {
  18874. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18875. }
  18876. if (material.bumpTexture) {
  18877. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18878. }
  18879. return serializationObject;
  18880. };
  18881. var serializeTexture = function (texture) {
  18882. var serializationObject = {};
  18883. if (!texture.name) {
  18884. return null;
  18885. }
  18886. if (texture instanceof BABYLON.CubeTexture) {
  18887. serializationObject.name = texture.name;
  18888. serializationObject.hasAlpha = texture.hasAlpha;
  18889. serializationObject.level = texture.level;
  18890. serializationObject.coordinatesMode = texture.coordinatesMode;
  18891. return serializationObject;
  18892. }
  18893. if (texture instanceof BABYLON.MirrorTexture) {
  18894. var mirrorTexture = texture;
  18895. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18896. serializationObject.renderList = [];
  18897. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18898. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18899. }
  18900. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18901. }
  18902. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18903. var renderTargetTexture = texture;
  18904. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18905. serializationObject.renderList = [];
  18906. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18907. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18908. }
  18909. }
  18910. var regularTexture = texture;
  18911. serializationObject.name = texture.name;
  18912. serializationObject.hasAlpha = texture.hasAlpha;
  18913. serializationObject.level = texture.level;
  18914. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18915. serializationObject.coordinatesMode = texture.coordinatesMode;
  18916. serializationObject.uOffset = regularTexture.uOffset;
  18917. serializationObject.vOffset = regularTexture.vOffset;
  18918. serializationObject.uScale = regularTexture.uScale;
  18919. serializationObject.vScale = regularTexture.vScale;
  18920. serializationObject.uAng = regularTexture.uAng;
  18921. serializationObject.vAng = regularTexture.vAng;
  18922. serializationObject.wAng = regularTexture.wAng;
  18923. serializationObject.wrapU = texture.wrapU;
  18924. serializationObject.wrapV = texture.wrapV;
  18925. // Animations
  18926. appendAnimations(texture, serializationObject);
  18927. return serializationObject;
  18928. };
  18929. var serializeSkeleton = function (skeleton) {
  18930. var serializationObject = {};
  18931. serializationObject.name = skeleton.name;
  18932. serializationObject.id = skeleton.id;
  18933. serializationObject.bones = [];
  18934. for (var index = 0; index < skeleton.bones.length; index++) {
  18935. var bone = skeleton.bones[index];
  18936. var serializedBone = {
  18937. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18938. name: bone.name,
  18939. matrix: bone.getLocalMatrix().toArray()
  18940. };
  18941. serializationObject.bones.push(serializedBone);
  18942. if (bone.animations && bone.animations.length > 0) {
  18943. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18944. }
  18945. }
  18946. return serializationObject;
  18947. };
  18948. var serializeParticleSystem = function (particleSystem) {
  18949. var serializationObject = {};
  18950. serializationObject.emitterId = particleSystem.emitter.id;
  18951. serializationObject.capacity = particleSystem.getCapacity();
  18952. if (particleSystem.particleTexture) {
  18953. serializationObject.textureName = particleSystem.particleTexture.name;
  18954. }
  18955. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18956. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18957. serializationObject.minSize = particleSystem.minSize;
  18958. serializationObject.maxSize = particleSystem.maxSize;
  18959. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18960. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18961. serializationObject.emitRate = particleSystem.emitRate;
  18962. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18963. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18964. serializationObject.gravity = particleSystem.gravity.asArray();
  18965. serializationObject.direction1 = particleSystem.direction1.asArray();
  18966. serializationObject.direction2 = particleSystem.direction2.asArray();
  18967. serializationObject.color1 = particleSystem.color1.asArray();
  18968. serializationObject.color2 = particleSystem.color2.asArray();
  18969. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18970. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18971. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18972. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18973. serializationObject.blendMode = particleSystem.blendMode;
  18974. return serializationObject;
  18975. };
  18976. var serializeLensFlareSystem = function (lensFlareSystem) {
  18977. var serializationObject = {};
  18978. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18979. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18980. serializationObject.flares = [];
  18981. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18982. var flare = lensFlareSystem.lensFlares[index];
  18983. serializationObject.flares.push({
  18984. size: flare.size,
  18985. position: flare.position,
  18986. color: flare.color.asArray(),
  18987. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18988. });
  18989. }
  18990. return serializationObject;
  18991. };
  18992. var serializeShadowGenerator = function (light) {
  18993. var serializationObject = {};
  18994. var shadowGenerator = light.getShadowGenerator();
  18995. serializationObject.lightId = light.id;
  18996. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18997. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18998. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18999. serializationObject.renderList = [];
  19000. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  19001. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  19002. serializationObject.renderList.push(mesh.id);
  19003. }
  19004. return serializationObject;
  19005. };
  19006. var serializedGeometries = [];
  19007. var serializeGeometry = function (geometry, serializationGeometries) {
  19008. if (serializedGeometries[geometry.id]) {
  19009. return;
  19010. }
  19011. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  19012. serializationGeometries.boxes.push(serializeBox(geometry));
  19013. }
  19014. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  19015. serializationGeometries.spheres.push(serializeSphere(geometry));
  19016. }
  19017. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  19018. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  19019. }
  19020. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  19021. serializationGeometries.toruses.push(serializeTorus(geometry));
  19022. }
  19023. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  19024. serializationGeometries.grounds.push(serializeGround(geometry));
  19025. }
  19026. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  19027. serializationGeometries.planes.push(serializePlane(geometry));
  19028. }
  19029. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  19030. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  19031. }
  19032. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  19033. throw new Error("Unknow primitive type");
  19034. }
  19035. else {
  19036. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  19037. }
  19038. serializedGeometries[geometry.id] = true;
  19039. };
  19040. var serializeGeometryBase = function (geometry) {
  19041. var serializationObject = {};
  19042. serializationObject.id = geometry.id;
  19043. if (BABYLON.Tags.HasTags(geometry)) {
  19044. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  19045. }
  19046. return serializationObject;
  19047. };
  19048. var serializeVertexData = function (vertexData) {
  19049. var serializationObject = serializeGeometryBase(vertexData);
  19050. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19051. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19052. }
  19053. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19054. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19055. }
  19056. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19057. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19058. }
  19059. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19060. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19061. }
  19062. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19063. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19064. }
  19065. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19066. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19067. serializationObject.matricesIndices._isExpanded = true;
  19068. }
  19069. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19070. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19071. }
  19072. serializationObject.indices = vertexData.getIndices();
  19073. return serializationObject;
  19074. };
  19075. var serializePrimitive = function (primitive) {
  19076. var serializationObject = serializeGeometryBase(primitive);
  19077. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  19078. return serializationObject;
  19079. };
  19080. var serializeBox = function (box) {
  19081. var serializationObject = serializePrimitive(box);
  19082. serializationObject.size = box.size;
  19083. return serializationObject;
  19084. };
  19085. var serializeSphere = function (sphere) {
  19086. var serializationObject = serializePrimitive(sphere);
  19087. serializationObject.segments = sphere.segments;
  19088. serializationObject.diameter = sphere.diameter;
  19089. return serializationObject;
  19090. };
  19091. var serializeCylinder = function (cylinder) {
  19092. var serializationObject = serializePrimitive(cylinder);
  19093. serializationObject.height = cylinder.height;
  19094. serializationObject.diameterTop = cylinder.diameterTop;
  19095. serializationObject.diameterBottom = cylinder.diameterBottom;
  19096. serializationObject.tessellation = cylinder.tessellation;
  19097. return serializationObject;
  19098. };
  19099. var serializeTorus = function (torus) {
  19100. var serializationObject = serializePrimitive(torus);
  19101. serializationObject.diameter = torus.diameter;
  19102. serializationObject.thickness = torus.thickness;
  19103. serializationObject.tessellation = torus.tessellation;
  19104. return serializationObject;
  19105. };
  19106. var serializeGround = function (ground) {
  19107. var serializationObject = serializePrimitive(ground);
  19108. serializationObject.width = ground.width;
  19109. serializationObject.height = ground.height;
  19110. serializationObject.subdivisions = ground.subdivisions;
  19111. return serializationObject;
  19112. };
  19113. var serializePlane = function (plane) {
  19114. var serializationObject = serializePrimitive(plane);
  19115. serializationObject.size = plane.size;
  19116. return serializationObject;
  19117. };
  19118. var serializeTorusKnot = function (torusKnot) {
  19119. var serializationObject = serializePrimitive(torusKnot);
  19120. serializationObject.radius = torusKnot.radius;
  19121. serializationObject.tube = torusKnot.tube;
  19122. serializationObject.radialSegments = torusKnot.radialSegments;
  19123. serializationObject.tubularSegments = torusKnot.tubularSegments;
  19124. serializationObject.p = torusKnot.p;
  19125. serializationObject.q = torusKnot.q;
  19126. return serializationObject;
  19127. };
  19128. var serializeMesh = function (mesh, serializationScene) {
  19129. var serializationObject = {};
  19130. serializationObject.name = mesh.name;
  19131. serializationObject.id = mesh.id;
  19132. if (BABYLON.Tags.HasTags(mesh)) {
  19133. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  19134. }
  19135. serializationObject.position = mesh.position.asArray();
  19136. if (mesh.rotationQuaternion) {
  19137. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  19138. }
  19139. else if (mesh.rotation) {
  19140. serializationObject.rotation = mesh.rotation.asArray();
  19141. }
  19142. serializationObject.scaling = mesh.scaling.asArray();
  19143. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  19144. serializationObject.isEnabled = mesh.isEnabled();
  19145. serializationObject.isVisible = mesh.isVisible;
  19146. serializationObject.infiniteDistance = mesh.infiniteDistance;
  19147. serializationObject.pickable = mesh.isPickable;
  19148. serializationObject.receiveShadows = mesh.receiveShadows;
  19149. serializationObject.billboardMode = mesh.billboardMode;
  19150. serializationObject.visibility = mesh.visibility;
  19151. serializationObject.checkCollisions = mesh.checkCollisions;
  19152. // Parent
  19153. if (mesh.parent) {
  19154. serializationObject.parentId = mesh.parent.id;
  19155. }
  19156. // Geometry
  19157. var geometry = mesh._geometry;
  19158. if (geometry) {
  19159. var geometryId = geometry.id;
  19160. serializationObject.geometryId = geometryId;
  19161. if (!mesh.getScene().getGeometryByID(geometryId)) {
  19162. // 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
  19163. serializeGeometry(geometry, serializationScene.geometries);
  19164. }
  19165. // SubMeshes
  19166. serializationObject.subMeshes = [];
  19167. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19168. var subMesh = mesh.subMeshes[subIndex];
  19169. serializationObject.subMeshes.push({
  19170. materialIndex: subMesh.materialIndex,
  19171. verticesStart: subMesh.verticesStart,
  19172. verticesCount: subMesh.verticesCount,
  19173. indexStart: subMesh.indexStart,
  19174. indexCount: subMesh.indexCount
  19175. });
  19176. }
  19177. }
  19178. // Material
  19179. if (mesh.material) {
  19180. serializationObject.materialId = mesh.material.id;
  19181. }
  19182. else {
  19183. mesh.material = null;
  19184. }
  19185. // Skeleton
  19186. if (mesh.skeleton) {
  19187. serializationObject.skeletonId = mesh.skeleton.id;
  19188. }
  19189. // Physics
  19190. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  19191. serializationObject.physicsMass = mesh.getPhysicsMass();
  19192. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  19193. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  19194. switch (mesh.getPhysicsImpostor()) {
  19195. case BABYLON.PhysicsEngine.BoxImpostor:
  19196. serializationObject.physicsImpostor = 1;
  19197. break;
  19198. case BABYLON.PhysicsEngine.SphereImpostor:
  19199. serializationObject.physicsImpostor = 2;
  19200. break;
  19201. }
  19202. }
  19203. // Instances
  19204. serializationObject.instances = [];
  19205. for (var index = 0; index < mesh.instances.length; index++) {
  19206. var instance = mesh.instances[index];
  19207. var serializationInstance = {
  19208. name: instance.name,
  19209. position: instance.position,
  19210. rotation: instance.rotation,
  19211. rotationQuaternion: instance.rotationQuaternion,
  19212. scaling: instance.scaling
  19213. };
  19214. serializationObject.instances.push(serializationInstance);
  19215. // Animations
  19216. appendAnimations(instance, serializationInstance);
  19217. }
  19218. // Animations
  19219. appendAnimations(mesh, serializationObject);
  19220. // Layer mask
  19221. serializationObject.layerMask = mesh.layerMask;
  19222. return serializationObject;
  19223. };
  19224. var SceneSerializer = (function () {
  19225. function SceneSerializer() {
  19226. }
  19227. SceneSerializer.Serialize = function (scene) {
  19228. var serializationObject = {};
  19229. // Scene
  19230. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  19231. serializationObject.autoClear = scene.autoClear;
  19232. serializationObject.clearColor = scene.clearColor.asArray();
  19233. serializationObject.ambientColor = scene.ambientColor.asArray();
  19234. serializationObject.gravity = scene.gravity.asArray();
  19235. // Fog
  19236. if (scene.fogMode && scene.fogMode !== 0) {
  19237. serializationObject.fogMode = scene.fogMode;
  19238. serializationObject.fogColor = scene.fogColor.asArray();
  19239. serializationObject.fogStart = scene.fogStart;
  19240. serializationObject.fogEnd = scene.fogEnd;
  19241. serializationObject.fogDensity = scene.fogDensity;
  19242. }
  19243. // Lights
  19244. serializationObject.lights = [];
  19245. for (var index = 0; index < scene.lights.length; index++) {
  19246. var light = scene.lights[index];
  19247. serializationObject.lights.push(serializeLight(light));
  19248. }
  19249. // Cameras
  19250. serializationObject.cameras = [];
  19251. for (index = 0; index < scene.cameras.length; index++) {
  19252. var camera = scene.cameras[index];
  19253. serializationObject.cameras.push(serializeCamera(camera));
  19254. }
  19255. if (scene.activeCamera) {
  19256. serializationObject.activeCameraID = scene.activeCamera.id;
  19257. }
  19258. // Materials
  19259. serializationObject.materials = [];
  19260. serializationObject.multiMaterials = [];
  19261. for (index = 0; index < scene.materials.length; index++) {
  19262. var material = scene.materials[index];
  19263. if (material instanceof BABYLON.StandardMaterial) {
  19264. serializationObject.materials.push(serializeMaterial(material));
  19265. }
  19266. else if (material instanceof BABYLON.MultiMaterial) {
  19267. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  19268. }
  19269. }
  19270. // Skeletons
  19271. serializationObject.skeletons = [];
  19272. for (index = 0; index < scene.skeletons.length; index++) {
  19273. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  19274. }
  19275. // Geometries
  19276. serializationObject.geometries = {};
  19277. serializationObject.geometries.boxes = [];
  19278. serializationObject.geometries.spheres = [];
  19279. serializationObject.geometries.cylinders = [];
  19280. serializationObject.geometries.toruses = [];
  19281. serializationObject.geometries.grounds = [];
  19282. serializationObject.geometries.planes = [];
  19283. serializationObject.geometries.torusKnots = [];
  19284. serializationObject.geometries.vertexData = [];
  19285. serializedGeometries = [];
  19286. var geometries = scene.getGeometries();
  19287. for (index = 0; index < geometries.length; index++) {
  19288. var geometry = geometries[index];
  19289. if (geometry.isReady()) {
  19290. serializeGeometry(geometry, serializationObject.geometries);
  19291. }
  19292. }
  19293. // Meshes
  19294. serializationObject.meshes = [];
  19295. for (index = 0; index < scene.meshes.length; index++) {
  19296. var abstractMesh = scene.meshes[index];
  19297. if (abstractMesh instanceof BABYLON.Mesh) {
  19298. var mesh = abstractMesh;
  19299. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19300. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19301. }
  19302. }
  19303. }
  19304. // Particles Systems
  19305. serializationObject.particleSystems = [];
  19306. for (index = 0; index < scene.particleSystems.length; index++) {
  19307. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19308. }
  19309. // Lens flares
  19310. serializationObject.lensFlareSystems = [];
  19311. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19312. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19313. }
  19314. // Shadows
  19315. serializationObject.shadowGenerators = [];
  19316. for (index = 0; index < scene.lights.length; index++) {
  19317. light = scene.lights[index];
  19318. if (light.getShadowGenerator()) {
  19319. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19320. }
  19321. }
  19322. return serializationObject;
  19323. };
  19324. return SceneSerializer;
  19325. })();
  19326. BABYLON.SceneSerializer = SceneSerializer;
  19327. })(BABYLON || (BABYLON = {}));
  19328. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19329. (function (BABYLON) {
  19330. var SceneLoader = (function () {
  19331. function SceneLoader() {
  19332. }
  19333. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19334. get: function () {
  19335. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19336. },
  19337. set: function (value) {
  19338. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19339. },
  19340. enumerable: true,
  19341. configurable: true
  19342. });
  19343. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19344. get: function () {
  19345. return SceneLoader._ShowLoadingScreen;
  19346. },
  19347. set: function (value) {
  19348. SceneLoader._ShowLoadingScreen = value;
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19354. var dotPosition = sceneFilename.lastIndexOf(".");
  19355. var queryStringPosition = sceneFilename.indexOf("?");
  19356. if (queryStringPosition === -1) {
  19357. queryStringPosition = sceneFilename.length;
  19358. }
  19359. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19360. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19361. var plugin = this._registeredPlugins[index];
  19362. if (plugin.extensions.indexOf(extension) !== -1) {
  19363. return plugin;
  19364. }
  19365. }
  19366. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19367. };
  19368. // Public functions
  19369. SceneLoader.RegisterPlugin = function (plugin) {
  19370. plugin.extensions = plugin.extensions.toLowerCase();
  19371. SceneLoader._registeredPlugins.push(plugin);
  19372. };
  19373. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19374. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19375. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19376. return;
  19377. }
  19378. var manifestChecked = function (success) {
  19379. scene.database = database;
  19380. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19381. var importMeshFromData = function (data) {
  19382. var meshes = [];
  19383. var particleSystems = [];
  19384. var skeletons = [];
  19385. try {
  19386. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19387. if (onerror) {
  19388. onerror(scene, 'unable to load the scene');
  19389. }
  19390. return;
  19391. }
  19392. }
  19393. catch (e) {
  19394. if (onerror) {
  19395. onerror(scene, e);
  19396. }
  19397. return;
  19398. }
  19399. if (onsuccess) {
  19400. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19401. onsuccess(meshes, particleSystems, skeletons);
  19402. }
  19403. };
  19404. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19405. // Direct load
  19406. importMeshFromData(sceneFilename.substr(5));
  19407. return;
  19408. }
  19409. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19410. importMeshFromData(data);
  19411. }, progressCallBack, database);
  19412. };
  19413. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19414. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19415. };
  19416. /**
  19417. * Load a scene
  19418. * @param rootUrl a string that defines the root url for scene and resources
  19419. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19420. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19421. */
  19422. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19423. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19424. };
  19425. /**
  19426. * Append a scene
  19427. * @param rootUrl a string that defines the root url for scene and resources
  19428. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19429. * @param scene is the instance of BABYLON.Scene to append to
  19430. */
  19431. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19432. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19433. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19434. return;
  19435. }
  19436. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19437. var database;
  19438. if (SceneLoader.ShowLoadingScreen) {
  19439. scene.getEngine().displayLoadingUI();
  19440. }
  19441. var loadSceneFromData = function (data) {
  19442. scene.database = database;
  19443. if (!plugin.load(scene, data, rootUrl)) {
  19444. if (onerror) {
  19445. onerror(scene);
  19446. }
  19447. scene.getEngine().hideLoadingUI();
  19448. return;
  19449. }
  19450. if (onsuccess) {
  19451. onsuccess(scene);
  19452. }
  19453. if (SceneLoader.ShowLoadingScreen) {
  19454. scene.executeWhenReady(function () {
  19455. scene.getEngine().hideLoadingUI();
  19456. });
  19457. }
  19458. };
  19459. var manifestChecked = function (success) {
  19460. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19461. };
  19462. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19463. // Direct load
  19464. loadSceneFromData(sceneFilename.substr(5));
  19465. return;
  19466. }
  19467. if (rootUrl.indexOf("file:") === -1) {
  19468. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19469. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19470. }
  19471. else {
  19472. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19473. }
  19474. };
  19475. // Flags
  19476. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19477. SceneLoader._ShowLoadingScreen = true;
  19478. // Members
  19479. SceneLoader._registeredPlugins = new Array();
  19480. return SceneLoader;
  19481. })();
  19482. BABYLON.SceneLoader = SceneLoader;
  19483. ;
  19484. })(BABYLON || (BABYLON = {}));
  19485. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19486. (function (BABYLON) {
  19487. var Internals;
  19488. (function (Internals) {
  19489. var checkColors4 = function (colors, count) {
  19490. // Check if color3 was used
  19491. if (colors.length === count * 3) {
  19492. var colors4 = [];
  19493. for (var index = 0; index < colors.length; index += 3) {
  19494. var newIndex = (index / 3) * 4;
  19495. colors4[newIndex] = colors[index];
  19496. colors4[newIndex + 1] = colors[index + 1];
  19497. colors4[newIndex + 2] = colors[index + 2];
  19498. colors4[newIndex + 3] = 1.0;
  19499. }
  19500. return colors4;
  19501. }
  19502. return colors;
  19503. };
  19504. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19505. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19506. texture.name = parsedTexture.name;
  19507. texture.hasAlpha = parsedTexture.hasAlpha;
  19508. texture.level = parsedTexture.level;
  19509. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19510. return texture;
  19511. };
  19512. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19513. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19514. return null;
  19515. }
  19516. if (parsedTexture.isCube) {
  19517. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19518. }
  19519. var texture;
  19520. if (parsedTexture.mirrorPlane) {
  19521. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19522. texture._waitingRenderList = parsedTexture.renderList;
  19523. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19524. }
  19525. else if (parsedTexture.isRenderTarget) {
  19526. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19527. texture._waitingRenderList = parsedTexture.renderList;
  19528. }
  19529. else {
  19530. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19531. }
  19532. texture.name = parsedTexture.name;
  19533. texture.hasAlpha = parsedTexture.hasAlpha;
  19534. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19535. texture.level = parsedTexture.level;
  19536. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19537. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19538. texture.uOffset = parsedTexture.uOffset;
  19539. texture.vOffset = parsedTexture.vOffset;
  19540. texture.uScale = parsedTexture.uScale;
  19541. texture.vScale = parsedTexture.vScale;
  19542. texture.uAng = parsedTexture.uAng;
  19543. texture.vAng = parsedTexture.vAng;
  19544. texture.wAng = parsedTexture.wAng;
  19545. texture.wrapU = parsedTexture.wrapU;
  19546. texture.wrapV = parsedTexture.wrapV;
  19547. // Animations
  19548. if (parsedTexture.animations) {
  19549. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19550. var parsedAnimation = parsedTexture.animations[animationIndex];
  19551. texture.animations.push(parseAnimation(parsedAnimation));
  19552. }
  19553. }
  19554. return texture;
  19555. };
  19556. var parseSkeleton = function (parsedSkeleton, scene) {
  19557. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19558. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19559. var parsedBone = parsedSkeleton.bones[index];
  19560. var parentBone = null;
  19561. if (parsedBone.parentBoneIndex > -1) {
  19562. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19563. }
  19564. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19565. if (parsedBone.animation) {
  19566. bone.animations.push(parseAnimation(parsedBone.animation));
  19567. }
  19568. }
  19569. return skeleton;
  19570. };
  19571. var parseFresnelParameters = function (parsedFresnelParameters) {
  19572. var fresnelParameters = new BABYLON.FresnelParameters();
  19573. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19574. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19575. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19576. fresnelParameters.bias = parsedFresnelParameters.bias;
  19577. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19578. return fresnelParameters;
  19579. };
  19580. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19581. var material;
  19582. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19583. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19584. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19585. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19586. material.specularPower = parsedMaterial.specularPower;
  19587. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19588. material.alpha = parsedMaterial.alpha;
  19589. material.id = parsedMaterial.id;
  19590. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19591. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19592. material.wireframe = parsedMaterial.wireframe;
  19593. if (parsedMaterial.diffuseTexture) {
  19594. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19595. }
  19596. if (parsedMaterial.diffuseFresnelParameters) {
  19597. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19598. }
  19599. if (parsedMaterial.ambientTexture) {
  19600. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19601. }
  19602. if (parsedMaterial.opacityTexture) {
  19603. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19604. }
  19605. if (parsedMaterial.opacityFresnelParameters) {
  19606. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19607. }
  19608. if (parsedMaterial.reflectionTexture) {
  19609. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19610. }
  19611. if (parsedMaterial.reflectionFresnelParameters) {
  19612. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19613. }
  19614. if (parsedMaterial.emissiveTexture) {
  19615. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19616. }
  19617. if (parsedMaterial.emissiveFresnelParameters) {
  19618. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19619. }
  19620. if (parsedMaterial.specularTexture) {
  19621. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19622. }
  19623. if (parsedMaterial.bumpTexture) {
  19624. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19625. }
  19626. return material;
  19627. };
  19628. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19629. for (var index = 0; index < parsedData.materials.length; index++) {
  19630. var parsedMaterial = parsedData.materials[index];
  19631. if (parsedMaterial.id === id) {
  19632. return parseMaterial(parsedMaterial, scene, rootUrl);
  19633. }
  19634. }
  19635. return null;
  19636. };
  19637. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19638. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19639. multiMaterial.id = parsedMultiMaterial.id;
  19640. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19641. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19642. var subMatId = parsedMultiMaterial.materials[matIndex];
  19643. if (subMatId) {
  19644. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19645. }
  19646. else {
  19647. multiMaterial.subMaterials.push(null);
  19648. }
  19649. }
  19650. return multiMaterial;
  19651. };
  19652. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19653. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19654. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19655. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19656. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19657. var parsedFlare = parsedLensFlareSystem.flares[index];
  19658. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19659. }
  19660. return lensFlareSystem;
  19661. };
  19662. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19663. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19664. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19665. if (parsedParticleSystem.textureName) {
  19666. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19667. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19668. }
  19669. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19670. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19671. particleSystem.minSize = parsedParticleSystem.minSize;
  19672. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19673. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19674. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19675. particleSystem.emitter = emitter;
  19676. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19677. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19678. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19679. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19680. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19681. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19682. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19683. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19684. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19685. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19686. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19687. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19688. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19689. particleSystem.start();
  19690. return particleSystem;
  19691. };
  19692. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19693. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19694. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19695. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19696. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19697. shadowGenerator.getShadowMap().renderList.push(mesh);
  19698. }
  19699. if (parsedShadowGenerator.usePoissonSampling) {
  19700. shadowGenerator.usePoissonSampling = true;
  19701. }
  19702. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19703. shadowGenerator.useVarianceShadowMap = true;
  19704. }
  19705. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19706. shadowGenerator.useBlurVarianceShadowMap = true;
  19707. if (parsedShadowGenerator.blurScale) {
  19708. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19709. }
  19710. if (parsedShadowGenerator.blurBoxOffset) {
  19711. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19712. }
  19713. }
  19714. if (parsedShadowGenerator.bias !== undefined) {
  19715. shadowGenerator.bias = parsedShadowGenerator.bias;
  19716. }
  19717. return shadowGenerator;
  19718. };
  19719. var parseAnimation = function (parsedAnimation) {
  19720. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19721. var dataType = parsedAnimation.dataType;
  19722. var keys = [];
  19723. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19724. var key = parsedAnimation.keys[index];
  19725. var data;
  19726. switch (dataType) {
  19727. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19728. data = key.values[0];
  19729. break;
  19730. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19731. data = BABYLON.Quaternion.FromArray(key.values);
  19732. break;
  19733. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19734. data = BABYLON.Matrix.FromArray(key.values);
  19735. break;
  19736. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19737. default:
  19738. data = BABYLON.Vector3.FromArray(key.values);
  19739. break;
  19740. }
  19741. keys.push({
  19742. frame: key.frame,
  19743. value: data
  19744. });
  19745. }
  19746. animation.setKeys(keys);
  19747. return animation;
  19748. };
  19749. var parseLight = function (parsedLight, scene) {
  19750. var light;
  19751. switch (parsedLight.type) {
  19752. case 0:
  19753. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19754. break;
  19755. case 1:
  19756. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19757. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19758. break;
  19759. case 2:
  19760. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19761. break;
  19762. case 3:
  19763. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19764. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19765. break;
  19766. }
  19767. light.id = parsedLight.id;
  19768. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19769. if (parsedLight.intensity !== undefined) {
  19770. light.intensity = parsedLight.intensity;
  19771. }
  19772. if (parsedLight.range) {
  19773. light.range = parsedLight.range;
  19774. }
  19775. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19776. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19777. if (parsedLight.excludedMeshesIds) {
  19778. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19779. }
  19780. // Parent
  19781. if (parsedLight.parentId) {
  19782. light._waitingParentId = parsedLight.parentId;
  19783. }
  19784. if (parsedLight.includedOnlyMeshesIds) {
  19785. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19786. }
  19787. // Animations
  19788. if (parsedLight.animations) {
  19789. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19790. var parsedAnimation = parsedLight.animations[animationIndex];
  19791. light.animations.push(parseAnimation(parsedAnimation));
  19792. }
  19793. }
  19794. if (parsedLight.autoAnimate) {
  19795. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19796. }
  19797. };
  19798. var parseCamera = function (parsedCamera, scene) {
  19799. var camera;
  19800. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19801. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19802. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19803. var alpha = parsedCamera.alpha;
  19804. var beta = parsedCamera.beta;
  19805. var radius = parsedCamera.radius;
  19806. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19807. var eye_space = parsedCamera.eye_space;
  19808. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19809. }
  19810. else {
  19811. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19812. }
  19813. }
  19814. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19815. eye_space = parsedCamera.eye_space;
  19816. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19817. }
  19818. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19819. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19820. }
  19821. else if (parsedCamera.type === "FollowCamera") {
  19822. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19823. camera.heightOffset = parsedCamera.heightOffset;
  19824. camera.radius = parsedCamera.radius;
  19825. camera.rotationOffset = parsedCamera.rotationOffset;
  19826. if (lockedTargetMesh)
  19827. camera.target = lockedTargetMesh;
  19828. }
  19829. else if (parsedCamera.type === "GamepadCamera") {
  19830. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19831. }
  19832. else if (parsedCamera.type === "OculusCamera") {
  19833. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19834. }
  19835. else if (parsedCamera.type === "OculusGamepadCamera") {
  19836. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19837. }
  19838. else if (parsedCamera.type === "TouchCamera") {
  19839. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19840. }
  19841. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19842. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19843. }
  19844. else if (parsedCamera.type === "WebVRCamera") {
  19845. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19846. }
  19847. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19848. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19849. }
  19850. else {
  19851. // Free Camera is the default value
  19852. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19853. }
  19854. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19855. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19856. camera.lockedTarget = lockedTargetMesh;
  19857. }
  19858. camera.id = parsedCamera.id;
  19859. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19860. // Parent
  19861. if (parsedCamera.parentId) {
  19862. camera._waitingParentId = parsedCamera.parentId;
  19863. }
  19864. // Target
  19865. if (parsedCamera.target) {
  19866. if (camera.setTarget) {
  19867. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19868. }
  19869. else {
  19870. //For ArcRotate
  19871. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19872. }
  19873. }
  19874. else {
  19875. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19876. }
  19877. camera.fov = parsedCamera.fov;
  19878. camera.minZ = parsedCamera.minZ;
  19879. camera.maxZ = parsedCamera.maxZ;
  19880. camera.speed = parsedCamera.speed;
  19881. camera.inertia = parsedCamera.inertia;
  19882. camera.checkCollisions = parsedCamera.checkCollisions;
  19883. camera.applyGravity = parsedCamera.applyGravity;
  19884. if (parsedCamera.ellipsoid) {
  19885. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19886. }
  19887. // Animations
  19888. if (parsedCamera.animations) {
  19889. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19890. var parsedAnimation = parsedCamera.animations[animationIndex];
  19891. camera.animations.push(parseAnimation(parsedAnimation));
  19892. }
  19893. }
  19894. if (parsedCamera.autoAnimate) {
  19895. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19896. }
  19897. // Layer Mask
  19898. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19899. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19900. }
  19901. else {
  19902. camera.layerMask = 0xFFFFFFFF;
  19903. }
  19904. return camera;
  19905. };
  19906. var parseGeometry = function (parsedGeometry, scene) {
  19907. var id = parsedGeometry.id;
  19908. return scene.getGeometryByID(id);
  19909. };
  19910. var parseBox = function (parsedBox, scene) {
  19911. if (parseGeometry(parsedBox, scene)) {
  19912. return null; // null since geometry could be something else than a box...
  19913. }
  19914. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19915. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19916. scene.pushGeometry(box, true);
  19917. return box;
  19918. };
  19919. var parseSphere = function (parsedSphere, scene) {
  19920. if (parseGeometry(parsedSphere, scene)) {
  19921. return null; // null since geometry could be something else than a sphere...
  19922. }
  19923. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19924. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19925. scene.pushGeometry(sphere, true);
  19926. return sphere;
  19927. };
  19928. var parseCylinder = function (parsedCylinder, scene) {
  19929. if (parseGeometry(parsedCylinder, scene)) {
  19930. return null; // null since geometry could be something else than a cylinder...
  19931. }
  19932. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19933. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19934. scene.pushGeometry(cylinder, true);
  19935. return cylinder;
  19936. };
  19937. var parseTorus = function (parsedTorus, scene) {
  19938. if (parseGeometry(parsedTorus, scene)) {
  19939. return null; // null since geometry could be something else than a torus...
  19940. }
  19941. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19942. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19943. scene.pushGeometry(torus, true);
  19944. return torus;
  19945. };
  19946. var parseGround = function (parsedGround, scene) {
  19947. if (parseGeometry(parsedGround, scene)) {
  19948. return null; // null since geometry could be something else than a ground...
  19949. }
  19950. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19951. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19952. scene.pushGeometry(ground, true);
  19953. return ground;
  19954. };
  19955. var parsePlane = function (parsedPlane, scene) {
  19956. if (parseGeometry(parsedPlane, scene)) {
  19957. return null; // null since geometry could be something else than a plane...
  19958. }
  19959. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19960. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19961. scene.pushGeometry(plane, true);
  19962. return plane;
  19963. };
  19964. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19965. if (parseGeometry(parsedTorusKnot, scene)) {
  19966. return null; // null since geometry could be something else than a torusKnot...
  19967. }
  19968. 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);
  19969. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19970. scene.pushGeometry(torusKnot, true);
  19971. return torusKnot;
  19972. };
  19973. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19974. if (parseGeometry(parsedVertexData, scene)) {
  19975. return null; // null since geometry could be a primitive
  19976. }
  19977. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19978. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19979. if (parsedVertexData.delayLoadingFile) {
  19980. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19981. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19982. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19983. geometry._delayInfo = [];
  19984. if (parsedVertexData.hasUVs) {
  19985. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19986. }
  19987. if (parsedVertexData.hasUVs2) {
  19988. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19989. }
  19990. if (parsedVertexData.hasColors) {
  19991. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19992. }
  19993. if (parsedVertexData.hasMatricesIndices) {
  19994. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19995. }
  19996. if (parsedVertexData.hasMatricesWeights) {
  19997. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19998. }
  19999. geometry._delayLoadingFunction = importVertexData;
  20000. }
  20001. else {
  20002. importVertexData(parsedVertexData, geometry);
  20003. }
  20004. scene.pushGeometry(geometry, true);
  20005. return geometry;
  20006. };
  20007. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20008. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20009. mesh.id = parsedMesh.id;
  20010. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20011. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20012. if (parsedMesh.rotationQuaternion) {
  20013. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20014. }
  20015. else if (parsedMesh.rotation) {
  20016. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20017. }
  20018. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20019. if (parsedMesh.localMatrix) {
  20020. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20021. }
  20022. else if (parsedMesh.pivotMatrix) {
  20023. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20024. }
  20025. mesh.setEnabled(parsedMesh.isEnabled);
  20026. mesh.isVisible = parsedMesh.isVisible;
  20027. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20028. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20029. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20030. if (parsedMesh.applyFog !== undefined) {
  20031. mesh.applyFog = parsedMesh.applyFog;
  20032. }
  20033. if (parsedMesh.pickable !== undefined) {
  20034. mesh.isPickable = parsedMesh.pickable;
  20035. }
  20036. if (parsedMesh.alphaIndex !== undefined) {
  20037. mesh.alphaIndex = parsedMesh.alphaIndex;
  20038. }
  20039. mesh.receiveShadows = parsedMesh.receiveShadows;
  20040. mesh.billboardMode = parsedMesh.billboardMode;
  20041. if (parsedMesh.visibility !== undefined) {
  20042. mesh.visibility = parsedMesh.visibility;
  20043. }
  20044. mesh.checkCollisions = parsedMesh.checkCollisions;
  20045. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20046. // Parent
  20047. if (parsedMesh.parentId) {
  20048. mesh._waitingParentId = parsedMesh.parentId;
  20049. }
  20050. // Actions
  20051. if (parsedMesh.actions !== undefined) {
  20052. mesh._waitingActions = parsedMesh.actions;
  20053. }
  20054. // Geometry
  20055. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20056. if (parsedMesh.delayLoadingFile) {
  20057. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20058. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20059. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20060. if (parsedMesh._binaryInfo) {
  20061. mesh._binaryInfo = parsedMesh._binaryInfo;
  20062. }
  20063. mesh._delayInfo = [];
  20064. if (parsedMesh.hasUVs) {
  20065. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20066. }
  20067. if (parsedMesh.hasUVs2) {
  20068. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20069. }
  20070. if (parsedMesh.hasColors) {
  20071. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20072. }
  20073. if (parsedMesh.hasMatricesIndices) {
  20074. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20075. }
  20076. if (parsedMesh.hasMatricesWeights) {
  20077. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20078. }
  20079. mesh._delayLoadingFunction = importGeometry;
  20080. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20081. mesh._checkDelayState();
  20082. }
  20083. }
  20084. else {
  20085. importGeometry(parsedMesh, mesh);
  20086. }
  20087. // Material
  20088. if (parsedMesh.materialId) {
  20089. mesh.setMaterialByID(parsedMesh.materialId);
  20090. }
  20091. else {
  20092. mesh.material = null;
  20093. }
  20094. // Skeleton
  20095. if (parsedMesh.skeletonId > -1) {
  20096. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20097. }
  20098. // Physics
  20099. if (parsedMesh.physicsImpostor) {
  20100. if (!scene.isPhysicsEnabled()) {
  20101. scene.enablePhysics();
  20102. }
  20103. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20104. }
  20105. // Animations
  20106. if (parsedMesh.animations) {
  20107. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20108. var parsedAnimation = parsedMesh.animations[animationIndex];
  20109. mesh.animations.push(parseAnimation(parsedAnimation));
  20110. }
  20111. }
  20112. if (parsedMesh.autoAnimate) {
  20113. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20114. }
  20115. // Layer Mask
  20116. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20117. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20118. }
  20119. else {
  20120. mesh.layerMask = 0xFFFFFFFF;
  20121. }
  20122. // Instances
  20123. if (parsedMesh.instances) {
  20124. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20125. var parsedInstance = parsedMesh.instances[index];
  20126. var instance = mesh.createInstance(parsedInstance.name);
  20127. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20128. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20129. if (parsedInstance.rotationQuaternion) {
  20130. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20131. }
  20132. else if (parsedInstance.rotation) {
  20133. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20134. }
  20135. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20136. instance.checkCollisions = mesh.checkCollisions;
  20137. if (parsedMesh.animations) {
  20138. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20139. parsedAnimation = parsedMesh.animations[animationIndex];
  20140. instance.animations.push(parseAnimation(parsedAnimation));
  20141. }
  20142. }
  20143. }
  20144. }
  20145. return mesh;
  20146. };
  20147. var parseActions = function (parsedActions, object, scene) {
  20148. var actionManager = new BABYLON.ActionManager(scene);
  20149. if (object === null)
  20150. scene.actionManager = actionManager;
  20151. else
  20152. object.actionManager = actionManager;
  20153. // instanciate a new object
  20154. var instanciate = function (name, params) {
  20155. var newInstance = Object.create(BABYLON[name].prototype);
  20156. newInstance.constructor.apply(newInstance, params);
  20157. return newInstance;
  20158. };
  20159. var parseParameter = function (name, value, target, propertyPath) {
  20160. if (propertyPath === null) {
  20161. // String, boolean or float
  20162. var floatValue = parseFloat(value);
  20163. if (value === "true" || value === "false")
  20164. return value === "true";
  20165. else
  20166. return isNaN(floatValue) ? value : floatValue;
  20167. }
  20168. var effectiveTarget = propertyPath.split(".");
  20169. var values = value.split(",");
  20170. for (var i = 0; i < effectiveTarget.length; i++) {
  20171. target = target[effectiveTarget[i]];
  20172. }
  20173. // Return appropriate value with its type
  20174. if (target instanceof Boolean)
  20175. return values[0] === "true";
  20176. if (target instanceof String)
  20177. return values[0];
  20178. // Parameters with multiple values such as Vector3 etc.
  20179. var split = new Array();
  20180. for (var i = 0; i < values.length; i++)
  20181. split.push(parseFloat(values[i]));
  20182. if (target instanceof BABYLON.Vector3)
  20183. return BABYLON.Vector3.FromArray(split);
  20184. if (target instanceof BABYLON.Vector4)
  20185. return BABYLON.Vector4.FromArray(split);
  20186. if (target instanceof BABYLON.Color3)
  20187. return BABYLON.Color3.FromArray(split);
  20188. if (target instanceof BABYLON.Color4)
  20189. return BABYLON.Color4.FromArray(split);
  20190. return parseFloat(values[0]);
  20191. };
  20192. // traverse graph per trigger
  20193. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20194. if (combineArray === void 0) { combineArray = null; }
  20195. if (parsedAction.detached)
  20196. return;
  20197. var parameters = new Array();
  20198. var target = null;
  20199. var propertyPath = null;
  20200. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20201. // Parameters
  20202. if (parsedAction.type === 2)
  20203. parameters.push(actionManager);
  20204. else
  20205. parameters.push(trigger);
  20206. if (combine) {
  20207. var actions = new Array();
  20208. for (var j = 0; j < parsedAction.combine.length; j++) {
  20209. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20210. }
  20211. parameters.push(actions);
  20212. }
  20213. else {
  20214. for (var i = 0; i < parsedAction.properties.length; i++) {
  20215. var value = parsedAction.properties[i].value;
  20216. var name = parsedAction.properties[i].name;
  20217. if (name === "target")
  20218. value = target = scene.getNodeByName(value);
  20219. else if (name === "parent")
  20220. value = scene.getNodeByName(value);
  20221. else if (name === "sound")
  20222. value = scene.getSoundByName(value);
  20223. else if (name !== "propertyPath") {
  20224. if (parsedAction.type === 2 && name === "operator")
  20225. value = BABYLON.ValueCondition[value];
  20226. else
  20227. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20228. }
  20229. else {
  20230. propertyPath = value;
  20231. }
  20232. parameters.push(value);
  20233. }
  20234. }
  20235. parameters.push(condition);
  20236. // If interpolate value action
  20237. if (parsedAction.name === "InterpolateValueAction") {
  20238. var param = parameters[parameters.length - 2];
  20239. parameters[parameters.length - 1] = param;
  20240. parameters[parameters.length - 2] = condition;
  20241. }
  20242. // Action or condition(s) and not CombineAction
  20243. var newAction = instanciate(parsedAction.name, parameters);
  20244. if (combineArray === null) {
  20245. if (newAction instanceof BABYLON.Condition) {
  20246. condition = newAction;
  20247. newAction = action;
  20248. }
  20249. else {
  20250. condition = null;
  20251. if (action)
  20252. action.then(newAction);
  20253. else
  20254. actionManager.registerAction(newAction);
  20255. }
  20256. }
  20257. else {
  20258. combineArray.push(newAction);
  20259. }
  20260. for (var i = 0; i < parsedAction.children.length; i++)
  20261. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20262. };
  20263. for (var i = 0; i < parsedActions.children.length; i++) {
  20264. var triggerParams;
  20265. var trigger = parsedActions.children[i];
  20266. if (trigger.properties.length > 0) {
  20267. var param = trigger.properties[0].value;
  20268. var value = trigger.properties[0].targetType == null ? param : scene.getMeshByName(param);
  20269. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20270. }
  20271. else
  20272. triggerParams = BABYLON.ActionManager[trigger.name];
  20273. for (var j = 0; j < trigger.children.length; j++) {
  20274. if (!trigger.detached)
  20275. traverse(trigger.children[j], triggerParams, null, null);
  20276. }
  20277. }
  20278. };
  20279. var parseSound = function (parsedSound, scene, rootUrl) {
  20280. var soundName = parsedSound.name;
  20281. var soundUrl = rootUrl + soundName;
  20282. var options = {
  20283. autoplay: parsedSound.autoplay,
  20284. loop: parsedSound.loop,
  20285. volume: parsedSound.volume,
  20286. spatialSound: parsedSound.spatialSound,
  20287. maxDistance: parsedSound.maxDistance,
  20288. rolloffFactor: parsedSound.rolloffFactor,
  20289. refDistance: parsedSound.refDistance,
  20290. distanceModel: parsedSound.distanceModel,
  20291. playbackRate: parsedSound.playbackRate
  20292. };
  20293. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  20294. scene._removePendingData(newSound);
  20295. }, options);
  20296. scene._addPendingData(newSound);
  20297. if (parsedSound.position) {
  20298. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20299. newSound.setPosition(soundPosition);
  20300. }
  20301. if (parsedSound.isDirectional) {
  20302. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20303. if (parsedSound.localDirectionToMesh) {
  20304. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20305. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20306. }
  20307. }
  20308. if (parsedSound.connectedMeshId) {
  20309. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20310. if (connectedMesh) {
  20311. newSound.attachToMesh(connectedMesh);
  20312. }
  20313. }
  20314. };
  20315. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20316. names = (names instanceof Array) ? names : [names];
  20317. for (var i in names) {
  20318. if (mesh.name === names[i]) {
  20319. hierarchyIds.push(mesh.id);
  20320. return true;
  20321. }
  20322. }
  20323. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20324. hierarchyIds.push(mesh.id);
  20325. return true;
  20326. }
  20327. return false;
  20328. };
  20329. var importVertexData = function (parsedVertexData, geometry) {
  20330. var vertexData = new BABYLON.VertexData();
  20331. // positions
  20332. var positions = parsedVertexData.positions;
  20333. if (positions) {
  20334. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20335. }
  20336. // normals
  20337. var normals = parsedVertexData.normals;
  20338. if (normals) {
  20339. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20340. }
  20341. // uvs
  20342. var uvs = parsedVertexData.uvs;
  20343. if (uvs) {
  20344. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20345. }
  20346. // uv2s
  20347. var uv2s = parsedVertexData.uv2s;
  20348. if (uv2s) {
  20349. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20350. }
  20351. // colors
  20352. var colors = parsedVertexData.colors;
  20353. if (colors) {
  20354. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20355. }
  20356. // matricesIndices
  20357. var matricesIndices = parsedVertexData.matricesIndices;
  20358. if (matricesIndices) {
  20359. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20360. }
  20361. // matricesWeights
  20362. var matricesWeights = parsedVertexData.matricesWeights;
  20363. if (matricesWeights) {
  20364. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20365. }
  20366. // indices
  20367. var indices = parsedVertexData.indices;
  20368. if (indices) {
  20369. vertexData.indices = indices;
  20370. }
  20371. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20372. };
  20373. var importGeometry = function (parsedGeometry, mesh) {
  20374. var scene = mesh.getScene();
  20375. // Geometry
  20376. var geometryId = parsedGeometry.geometryId;
  20377. if (geometryId) {
  20378. var geometry = scene.getGeometryByID(geometryId);
  20379. if (geometry) {
  20380. geometry.applyToMesh(mesh);
  20381. }
  20382. }
  20383. else if (parsedGeometry instanceof ArrayBuffer) {
  20384. var binaryInfo = mesh._binaryInfo;
  20385. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20386. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20387. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20388. }
  20389. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20390. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20391. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20392. }
  20393. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20394. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20395. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20396. }
  20397. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20398. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20399. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20400. }
  20401. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20402. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20403. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20404. }
  20405. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20406. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20407. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20408. }
  20409. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20410. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20411. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20412. }
  20413. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20414. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20415. mesh.setIndices(indicesData);
  20416. }
  20417. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20418. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20419. mesh.subMeshes = [];
  20420. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20421. var materialIndex = subMeshesData[(i * 5) + 0];
  20422. var verticesStart = subMeshesData[(i * 5) + 1];
  20423. var verticesCount = subMeshesData[(i * 5) + 2];
  20424. var indexStart = subMeshesData[(i * 5) + 3];
  20425. var indexCount = subMeshesData[(i * 5) + 4];
  20426. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20427. }
  20428. }
  20429. }
  20430. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20431. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20432. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20433. if (parsedGeometry.uvs) {
  20434. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20435. }
  20436. if (parsedGeometry.uvs2) {
  20437. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20438. }
  20439. if (parsedGeometry.colors) {
  20440. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20441. }
  20442. if (parsedGeometry.matricesIndices) {
  20443. if (!parsedGeometry.matricesIndices._isExpanded) {
  20444. var floatIndices = [];
  20445. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20446. var matricesIndex = parsedGeometry.matricesIndices[i];
  20447. floatIndices.push(matricesIndex & 0x000000FF);
  20448. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20449. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20450. floatIndices.push(matricesIndex >> 24);
  20451. }
  20452. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20453. }
  20454. else {
  20455. delete parsedGeometry.matricesIndices._isExpanded;
  20456. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20457. }
  20458. }
  20459. if (parsedGeometry.matricesWeights) {
  20460. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20461. }
  20462. mesh.setIndices(parsedGeometry.indices);
  20463. // SubMeshes
  20464. if (parsedGeometry.subMeshes) {
  20465. mesh.subMeshes = [];
  20466. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20467. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20468. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20469. }
  20470. }
  20471. }
  20472. // Flat shading
  20473. if (mesh._shouldGenerateFlatShading) {
  20474. mesh.convertToFlatShadedMesh();
  20475. delete mesh._shouldGenerateFlatShading;
  20476. }
  20477. // Update
  20478. mesh.computeWorldMatrix(true);
  20479. // Octree
  20480. if (scene._selectionOctree) {
  20481. scene._selectionOctree.addMesh(mesh);
  20482. }
  20483. };
  20484. BABYLON.SceneLoader.RegisterPlugin({
  20485. extensions: ".babylon",
  20486. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20487. var parsedData = JSON.parse(data);
  20488. var loadedSkeletonsIds = [];
  20489. var loadedMaterialsIds = [];
  20490. var hierarchyIds = [];
  20491. for (var index = 0; index < parsedData.meshes.length; index++) {
  20492. var parsedMesh = parsedData.meshes[index];
  20493. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20494. if (meshesNames instanceof Array) {
  20495. // Remove found mesh name from list.
  20496. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20497. }
  20498. // Material ?
  20499. if (parsedMesh.materialId) {
  20500. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20501. if (!materialFound) {
  20502. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20503. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20504. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20505. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20506. var subMatId = parsedMultiMaterial.materials[matIndex];
  20507. loadedMaterialsIds.push(subMatId);
  20508. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20509. }
  20510. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20511. parseMultiMaterial(parsedMultiMaterial, scene);
  20512. materialFound = true;
  20513. break;
  20514. }
  20515. }
  20516. }
  20517. if (!materialFound) {
  20518. loadedMaterialsIds.push(parsedMesh.materialId);
  20519. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20520. }
  20521. }
  20522. // Skeleton ?
  20523. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20524. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20525. if (!skeletonAlreadyLoaded) {
  20526. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20527. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20528. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20529. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20530. loadedSkeletonsIds.push(parsedSkeleton.id);
  20531. }
  20532. }
  20533. }
  20534. }
  20535. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20536. meshes.push(mesh);
  20537. }
  20538. }
  20539. for (index = 0; index < scene.meshes.length; index++) {
  20540. var currentMesh = scene.meshes[index];
  20541. if (currentMesh._waitingParentId) {
  20542. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20543. currentMesh._waitingParentId = undefined;
  20544. }
  20545. }
  20546. // Particles
  20547. if (parsedData.particleSystems) {
  20548. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20549. var parsedParticleSystem = parsedData.particleSystems[index];
  20550. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20551. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20552. }
  20553. }
  20554. }
  20555. return true;
  20556. },
  20557. load: function (scene, data, rootUrl) {
  20558. var parsedData = JSON.parse(data);
  20559. // Scene
  20560. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20561. scene.autoClear = parsedData.autoClear;
  20562. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20563. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20564. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20565. // Fog
  20566. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20567. scene.fogMode = parsedData.fogMode;
  20568. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20569. scene.fogStart = parsedData.fogStart;
  20570. scene.fogEnd = parsedData.fogEnd;
  20571. scene.fogDensity = parsedData.fogDensity;
  20572. }
  20573. for (var index = 0; index < parsedData.lights.length; index++) {
  20574. var parsedLight = parsedData.lights[index];
  20575. parseLight(parsedLight, scene);
  20576. }
  20577. // Materials
  20578. if (parsedData.materials) {
  20579. for (index = 0; index < parsedData.materials.length; index++) {
  20580. var parsedMaterial = parsedData.materials[index];
  20581. parseMaterial(parsedMaterial, scene, rootUrl);
  20582. }
  20583. }
  20584. if (parsedData.multiMaterials) {
  20585. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20586. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20587. parseMultiMaterial(parsedMultiMaterial, scene);
  20588. }
  20589. }
  20590. // Skeletons
  20591. if (parsedData.skeletons) {
  20592. for (index = 0; index < parsedData.skeletons.length; index++) {
  20593. var parsedSkeleton = parsedData.skeletons[index];
  20594. parseSkeleton(parsedSkeleton, scene);
  20595. }
  20596. }
  20597. // Geometries
  20598. var geometries = parsedData.geometries;
  20599. if (geometries) {
  20600. // Boxes
  20601. var boxes = geometries.boxes;
  20602. if (boxes) {
  20603. for (index = 0; index < boxes.length; index++) {
  20604. var parsedBox = boxes[index];
  20605. parseBox(parsedBox, scene);
  20606. }
  20607. }
  20608. // Spheres
  20609. var spheres = geometries.spheres;
  20610. if (spheres) {
  20611. for (index = 0; index < spheres.length; index++) {
  20612. var parsedSphere = spheres[index];
  20613. parseSphere(parsedSphere, scene);
  20614. }
  20615. }
  20616. // Cylinders
  20617. var cylinders = geometries.cylinders;
  20618. if (cylinders) {
  20619. for (index = 0; index < cylinders.length; index++) {
  20620. var parsedCylinder = cylinders[index];
  20621. parseCylinder(parsedCylinder, scene);
  20622. }
  20623. }
  20624. // Toruses
  20625. var toruses = geometries.toruses;
  20626. if (toruses) {
  20627. for (index = 0; index < toruses.length; index++) {
  20628. var parsedTorus = toruses[index];
  20629. parseTorus(parsedTorus, scene);
  20630. }
  20631. }
  20632. // Grounds
  20633. var grounds = geometries.grounds;
  20634. if (grounds) {
  20635. for (index = 0; index < grounds.length; index++) {
  20636. var parsedGround = grounds[index];
  20637. parseGround(parsedGround, scene);
  20638. }
  20639. }
  20640. // Planes
  20641. var planes = geometries.planes;
  20642. if (planes) {
  20643. for (index = 0; index < planes.length; index++) {
  20644. var parsedPlane = planes[index];
  20645. parsePlane(parsedPlane, scene);
  20646. }
  20647. }
  20648. // TorusKnots
  20649. var torusKnots = geometries.torusKnots;
  20650. if (torusKnots) {
  20651. for (index = 0; index < torusKnots.length; index++) {
  20652. var parsedTorusKnot = torusKnots[index];
  20653. parseTorusKnot(parsedTorusKnot, scene);
  20654. }
  20655. }
  20656. // VertexData
  20657. var vertexData = geometries.vertexData;
  20658. if (vertexData) {
  20659. for (index = 0; index < vertexData.length; index++) {
  20660. var parsedVertexData = vertexData[index];
  20661. parseVertexData(parsedVertexData, scene, rootUrl);
  20662. }
  20663. }
  20664. }
  20665. for (index = 0; index < parsedData.meshes.length; index++) {
  20666. var parsedMesh = parsedData.meshes[index];
  20667. parseMesh(parsedMesh, scene, rootUrl);
  20668. }
  20669. for (index = 0; index < parsedData.cameras.length; index++) {
  20670. var parsedCamera = parsedData.cameras[index];
  20671. parseCamera(parsedCamera, scene);
  20672. }
  20673. if (parsedData.activeCameraID) {
  20674. scene.setActiveCameraByID(parsedData.activeCameraID);
  20675. }
  20676. for (index = 0; index < scene.cameras.length; index++) {
  20677. var camera = scene.cameras[index];
  20678. if (camera._waitingParentId) {
  20679. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20680. camera._waitingParentId = undefined;
  20681. }
  20682. }
  20683. for (index = 0; index < scene.lights.length; index++) {
  20684. var light = scene.lights[index];
  20685. if (light._waitingParentId) {
  20686. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20687. light._waitingParentId = undefined;
  20688. }
  20689. }
  20690. // Sounds
  20691. if (parsedData.sounds) {
  20692. for (index = 0; index < parsedData.sounds.length; index++) {
  20693. var parsedSound = parsedData.sounds[index];
  20694. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20695. parseSound(parsedSound, scene, rootUrl);
  20696. }
  20697. else {
  20698. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20699. }
  20700. }
  20701. }
  20702. for (index = 0; index < scene.meshes.length; index++) {
  20703. var mesh = scene.meshes[index];
  20704. if (mesh._waitingParentId) {
  20705. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20706. mesh._waitingParentId = undefined;
  20707. }
  20708. if (mesh._waitingActions) {
  20709. parseActions(mesh._waitingActions, mesh, scene);
  20710. mesh._waitingActions = undefined;
  20711. }
  20712. }
  20713. // Particles Systems
  20714. if (parsedData.particleSystems) {
  20715. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20716. var parsedParticleSystem = parsedData.particleSystems[index];
  20717. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20718. }
  20719. }
  20720. // Lens flares
  20721. if (parsedData.lensFlareSystems) {
  20722. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20723. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20724. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20725. }
  20726. }
  20727. // Shadows
  20728. if (parsedData.shadowGenerators) {
  20729. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20730. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20731. parseShadowGenerator(parsedShadowGenerator, scene);
  20732. }
  20733. }
  20734. // Actions (scene)
  20735. if (parsedData.actions) {
  20736. parseActions(parsedData.actions, null, scene);
  20737. }
  20738. // Finish
  20739. return true;
  20740. }
  20741. });
  20742. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20743. })(BABYLON || (BABYLON = {}));
  20744. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20745. (function (BABYLON) {
  20746. // Unique ID when we import meshes from Babylon to CSG
  20747. var currentCSGMeshId = 0;
  20748. // # class Vertex
  20749. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20750. // one to provide additional features like texture coordinates and vertex
  20751. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20752. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20753. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20754. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20755. // is not used anywhere else.
  20756. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20757. var Vertex = (function () {
  20758. function Vertex(pos, normal, uv) {
  20759. this.pos = pos;
  20760. this.normal = normal;
  20761. this.uv = uv;
  20762. }
  20763. Vertex.prototype.clone = function () {
  20764. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20765. };
  20766. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20767. // orientation of a polygon is flipped.
  20768. Vertex.prototype.flip = function () {
  20769. this.normal = this.normal.scale(-1);
  20770. };
  20771. // Create a new vertex between this vertex and `other` by linearly
  20772. // interpolating all properties using a parameter of `t`. Subclasses should
  20773. // override this to interpolate additional properties.
  20774. Vertex.prototype.interpolate = function (other, t) {
  20775. 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));
  20776. };
  20777. return Vertex;
  20778. })();
  20779. // # class Plane
  20780. // Represents a plane in 3D space.
  20781. var Plane = (function () {
  20782. function Plane(normal, w) {
  20783. this.normal = normal;
  20784. this.w = w;
  20785. }
  20786. Plane.FromPoints = function (a, b, c) {
  20787. var v0 = c.subtract(a);
  20788. var v1 = b.subtract(a);
  20789. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20790. return null;
  20791. }
  20792. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20793. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20794. };
  20795. Plane.prototype.clone = function () {
  20796. return new Plane(this.normal.clone(), this.w);
  20797. };
  20798. Plane.prototype.flip = function () {
  20799. this.normal.scaleInPlace(-1);
  20800. this.w = -this.w;
  20801. };
  20802. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20803. // fragments in the appropriate lists. Coplanar polygons go into either
  20804. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20805. // respect to this plane. Polygons in front or in back of this plane go into
  20806. // either `front` or `back`.
  20807. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20808. var COPLANAR = 0;
  20809. var FRONT = 1;
  20810. var BACK = 2;
  20811. var SPANNING = 3;
  20812. // Classify each point as well as the entire polygon into one of the above
  20813. // four classes.
  20814. var polygonType = 0;
  20815. var types = [];
  20816. for (var i = 0; i < polygon.vertices.length; i++) {
  20817. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20818. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20819. polygonType |= type;
  20820. types.push(type);
  20821. }
  20822. switch (polygonType) {
  20823. case COPLANAR:
  20824. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20825. break;
  20826. case FRONT:
  20827. front.push(polygon);
  20828. break;
  20829. case BACK:
  20830. back.push(polygon);
  20831. break;
  20832. case SPANNING:
  20833. var f = [], b = [];
  20834. for (i = 0; i < polygon.vertices.length; i++) {
  20835. var j = (i + 1) % polygon.vertices.length;
  20836. var ti = types[i], tj = types[j];
  20837. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20838. if (ti != BACK)
  20839. f.push(vi);
  20840. if (ti != FRONT)
  20841. b.push(ti != BACK ? vi.clone() : vi);
  20842. if ((ti | tj) == SPANNING) {
  20843. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20844. var v = vi.interpolate(vj, t);
  20845. f.push(v);
  20846. b.push(v.clone());
  20847. }
  20848. }
  20849. if (f.length >= 3) {
  20850. var poly = new Polygon(f, polygon.shared);
  20851. if (poly.plane)
  20852. front.push(poly);
  20853. }
  20854. if (b.length >= 3) {
  20855. poly = new Polygon(b, polygon.shared);
  20856. if (poly.plane)
  20857. back.push(poly);
  20858. }
  20859. break;
  20860. }
  20861. };
  20862. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20863. // point is on the plane.
  20864. Plane.EPSILON = 1e-5;
  20865. return Plane;
  20866. })();
  20867. // # class Polygon
  20868. // Represents a convex polygon. The vertices used to initialize a polygon must
  20869. // be coplanar and form a convex loop.
  20870. //
  20871. // Each convex polygon has a `shared` property, which is shared between all
  20872. // polygons that are clones of each other or were split from the same polygon.
  20873. // This can be used to define per-polygon properties (such as surface color).
  20874. var Polygon = (function () {
  20875. function Polygon(vertices, shared) {
  20876. this.vertices = vertices;
  20877. this.shared = shared;
  20878. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20879. }
  20880. Polygon.prototype.clone = function () {
  20881. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20882. return new Polygon(vertices, this.shared);
  20883. };
  20884. Polygon.prototype.flip = function () {
  20885. this.vertices.reverse().map(function (v) {
  20886. v.flip();
  20887. });
  20888. this.plane.flip();
  20889. };
  20890. return Polygon;
  20891. })();
  20892. // # class Node
  20893. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20894. // by picking a polygon to split along. That polygon (and all other coplanar
  20895. // polygons) are added directly to that node and the other polygons are added to
  20896. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20897. // no distinction between internal and leaf nodes.
  20898. var Node = (function () {
  20899. function Node(polygons) {
  20900. this.plane = null;
  20901. this.front = null;
  20902. this.back = null;
  20903. this.polygons = [];
  20904. if (polygons) {
  20905. this.build(polygons);
  20906. }
  20907. }
  20908. Node.prototype.clone = function () {
  20909. var node = new Node();
  20910. node.plane = this.plane && this.plane.clone();
  20911. node.front = this.front && this.front.clone();
  20912. node.back = this.back && this.back.clone();
  20913. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20914. return node;
  20915. };
  20916. // Convert solid space to empty space and empty space to solid space.
  20917. Node.prototype.invert = function () {
  20918. for (var i = 0; i < this.polygons.length; i++) {
  20919. this.polygons[i].flip();
  20920. }
  20921. if (this.plane) {
  20922. this.plane.flip();
  20923. }
  20924. if (this.front) {
  20925. this.front.invert();
  20926. }
  20927. if (this.back) {
  20928. this.back.invert();
  20929. }
  20930. var temp = this.front;
  20931. this.front = this.back;
  20932. this.back = temp;
  20933. };
  20934. // Recursively remove all polygons in `polygons` that are inside this BSP
  20935. // tree.
  20936. Node.prototype.clipPolygons = function (polygons) {
  20937. if (!this.plane)
  20938. return polygons.slice();
  20939. var front = [], back = [];
  20940. for (var i = 0; i < polygons.length; i++) {
  20941. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20942. }
  20943. if (this.front) {
  20944. front = this.front.clipPolygons(front);
  20945. }
  20946. if (this.back) {
  20947. back = this.back.clipPolygons(back);
  20948. }
  20949. else {
  20950. back = [];
  20951. }
  20952. return front.concat(back);
  20953. };
  20954. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20955. // `bsp`.
  20956. Node.prototype.clipTo = function (bsp) {
  20957. this.polygons = bsp.clipPolygons(this.polygons);
  20958. if (this.front)
  20959. this.front.clipTo(bsp);
  20960. if (this.back)
  20961. this.back.clipTo(bsp);
  20962. };
  20963. // Return a list of all polygons in this BSP tree.
  20964. Node.prototype.allPolygons = function () {
  20965. var polygons = this.polygons.slice();
  20966. if (this.front)
  20967. polygons = polygons.concat(this.front.allPolygons());
  20968. if (this.back)
  20969. polygons = polygons.concat(this.back.allPolygons());
  20970. return polygons;
  20971. };
  20972. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20973. // new polygons are filtered down to the bottom of the tree and become new
  20974. // nodes there. Each set of polygons is partitioned using the first polygon
  20975. // (no heuristic is used to pick a good split).
  20976. Node.prototype.build = function (polygons) {
  20977. if (!polygons.length)
  20978. return;
  20979. if (!this.plane)
  20980. this.plane = polygons[0].plane.clone();
  20981. var front = [], back = [];
  20982. for (var i = 0; i < polygons.length; i++) {
  20983. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20984. }
  20985. if (front.length) {
  20986. if (!this.front)
  20987. this.front = new Node();
  20988. this.front.build(front);
  20989. }
  20990. if (back.length) {
  20991. if (!this.back)
  20992. this.back = new Node();
  20993. this.back.build(back);
  20994. }
  20995. };
  20996. return Node;
  20997. })();
  20998. var CSG = (function () {
  20999. function CSG() {
  21000. this.polygons = new Array();
  21001. }
  21002. // Convert BABYLON.Mesh to BABYLON.CSG
  21003. CSG.FromMesh = function (mesh) {
  21004. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  21005. if (mesh instanceof BABYLON.Mesh) {
  21006. mesh.computeWorldMatrix(true);
  21007. var matrix = mesh.getWorldMatrix();
  21008. var meshPosition = mesh.position.clone();
  21009. var meshRotation = mesh.rotation.clone();
  21010. var meshScaling = mesh.scaling.clone();
  21011. }
  21012. else {
  21013. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  21014. }
  21015. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21016. var subMeshes = mesh.subMeshes;
  21017. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  21018. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  21019. vertices = [];
  21020. for (var j = 0; j < 3; j++) {
  21021. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  21022. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  21023. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  21024. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  21025. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  21026. vertex = new Vertex(position, normal, uv);
  21027. vertices.push(vertex);
  21028. }
  21029. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  21030. // To handle the case of degenerated triangle
  21031. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  21032. if (polygon.plane)
  21033. polygons.push(polygon);
  21034. }
  21035. }
  21036. var csg = CSG.FromPolygons(polygons);
  21037. csg.matrix = matrix;
  21038. csg.position = meshPosition;
  21039. csg.rotation = meshRotation;
  21040. csg.scaling = meshScaling;
  21041. currentCSGMeshId++;
  21042. return csg;
  21043. };
  21044. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  21045. CSG.FromPolygons = function (polygons) {
  21046. var csg = new BABYLON.CSG();
  21047. csg.polygons = polygons;
  21048. return csg;
  21049. };
  21050. CSG.prototype.clone = function () {
  21051. var csg = new BABYLON.CSG();
  21052. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  21053. csg.copyTransformAttributes(this);
  21054. return csg;
  21055. };
  21056. CSG.prototype.toPolygons = function () {
  21057. return this.polygons;
  21058. };
  21059. CSG.prototype.union = function (csg) {
  21060. var a = new Node(this.clone().polygons);
  21061. var b = new Node(csg.clone().polygons);
  21062. a.clipTo(b);
  21063. b.clipTo(a);
  21064. b.invert();
  21065. b.clipTo(a);
  21066. b.invert();
  21067. a.build(b.allPolygons());
  21068. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21069. };
  21070. CSG.prototype.unionInPlace = function (csg) {
  21071. var a = new Node(this.polygons);
  21072. var b = new Node(csg.polygons);
  21073. a.clipTo(b);
  21074. b.clipTo(a);
  21075. b.invert();
  21076. b.clipTo(a);
  21077. b.invert();
  21078. a.build(b.allPolygons());
  21079. this.polygons = a.allPolygons();
  21080. };
  21081. CSG.prototype.subtract = function (csg) {
  21082. var a = new Node(this.clone().polygons);
  21083. var b = new Node(csg.clone().polygons);
  21084. a.invert();
  21085. a.clipTo(b);
  21086. b.clipTo(a);
  21087. b.invert();
  21088. b.clipTo(a);
  21089. b.invert();
  21090. a.build(b.allPolygons());
  21091. a.invert();
  21092. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21093. };
  21094. CSG.prototype.subtractInPlace = function (csg) {
  21095. var a = new Node(this.polygons);
  21096. var b = new Node(csg.polygons);
  21097. a.invert();
  21098. a.clipTo(b);
  21099. b.clipTo(a);
  21100. b.invert();
  21101. b.clipTo(a);
  21102. b.invert();
  21103. a.build(b.allPolygons());
  21104. a.invert();
  21105. this.polygons = a.allPolygons();
  21106. };
  21107. CSG.prototype.intersect = function (csg) {
  21108. var a = new Node(this.clone().polygons);
  21109. var b = new Node(csg.clone().polygons);
  21110. a.invert();
  21111. b.clipTo(a);
  21112. b.invert();
  21113. a.clipTo(b);
  21114. b.clipTo(a);
  21115. a.build(b.allPolygons());
  21116. a.invert();
  21117. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21118. };
  21119. CSG.prototype.intersectInPlace = function (csg) {
  21120. var a = new Node(this.polygons);
  21121. var b = new Node(csg.polygons);
  21122. a.invert();
  21123. b.clipTo(a);
  21124. b.invert();
  21125. a.clipTo(b);
  21126. b.clipTo(a);
  21127. a.build(b.allPolygons());
  21128. a.invert();
  21129. this.polygons = a.allPolygons();
  21130. };
  21131. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  21132. // not modified.
  21133. CSG.prototype.inverse = function () {
  21134. var csg = this.clone();
  21135. csg.inverseInPlace();
  21136. return csg;
  21137. };
  21138. CSG.prototype.inverseInPlace = function () {
  21139. this.polygons.map(function (p) {
  21140. p.flip();
  21141. });
  21142. };
  21143. // This is used to keep meshes transformations so they can be restored
  21144. // when we build back a Babylon Mesh
  21145. // NB : All CSG operations are performed in world coordinates
  21146. CSG.prototype.copyTransformAttributes = function (csg) {
  21147. this.matrix = csg.matrix;
  21148. this.position = csg.position;
  21149. this.rotation = csg.rotation;
  21150. this.scaling = csg.scaling;
  21151. return this;
  21152. };
  21153. // Build Raw mesh from CSG
  21154. // Coordinates here are in world space
  21155. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  21156. var matrix = this.matrix.clone();
  21157. matrix.invert();
  21158. 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;
  21159. if (keepSubMeshes) {
  21160. // Sort Polygons, since subMeshes are indices range
  21161. polygons.sort(function (a, b) {
  21162. if (a.shared.meshId === b.shared.meshId) {
  21163. return a.shared.subMeshId - b.shared.subMeshId;
  21164. }
  21165. else {
  21166. return a.shared.meshId - b.shared.meshId;
  21167. }
  21168. });
  21169. }
  21170. for (var i = 0, il = polygons.length; i < il; i++) {
  21171. polygon = polygons[i];
  21172. // Building SubMeshes
  21173. if (!subMesh_dict[polygon.shared.meshId]) {
  21174. subMesh_dict[polygon.shared.meshId] = {};
  21175. }
  21176. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  21177. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  21178. indexStart: +Infinity,
  21179. indexEnd: -Infinity,
  21180. materialIndex: polygon.shared.materialIndex
  21181. };
  21182. }
  21183. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  21184. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  21185. polygonIndices[0] = 0;
  21186. polygonIndices[1] = j - 1;
  21187. polygonIndices[2] = j;
  21188. for (var k = 0; k < 3; k++) {
  21189. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  21190. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  21191. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  21192. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  21193. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  21194. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  21195. // Check if 2 points can be merged
  21196. 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)) {
  21197. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  21198. uvs.push(uv.x, uv.y);
  21199. normals.push(normal.x, normal.y, normal.z);
  21200. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  21201. }
  21202. indices.push(vertex_idx);
  21203. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  21204. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  21205. currentIndex++;
  21206. }
  21207. }
  21208. }
  21209. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  21210. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21211. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  21212. mesh.setIndices(indices);
  21213. if (keepSubMeshes) {
  21214. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  21215. var materialIndexOffset = 0, materialMaxIndex;
  21216. mesh.subMeshes.length = 0;
  21217. for (var m in subMesh_dict) {
  21218. materialMaxIndex = -1;
  21219. for (var sm in subMesh_dict[m]) {
  21220. subMesh_obj = subMesh_dict[m][sm];
  21221. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  21222. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  21223. }
  21224. materialIndexOffset += ++materialMaxIndex;
  21225. }
  21226. }
  21227. return mesh;
  21228. };
  21229. // Build Mesh from CSG taking material and transforms into account
  21230. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  21231. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  21232. mesh.material = material;
  21233. mesh.position.copyFrom(this.position);
  21234. mesh.rotation.copyFrom(this.rotation);
  21235. mesh.scaling.copyFrom(this.scaling);
  21236. mesh.computeWorldMatrix(true);
  21237. return mesh;
  21238. };
  21239. return CSG;
  21240. })();
  21241. BABYLON.CSG = CSG;
  21242. })(BABYLON || (BABYLON = {}));
  21243. //# sourceMappingURL=babylon.csg.js.map
  21244. var BABYLON;
  21245. (function (BABYLON) {
  21246. var OculusDistortionCorrectionPostProcess = (function (_super) {
  21247. __extends(OculusDistortionCorrectionPostProcess, _super);
  21248. //ANY
  21249. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  21250. var _this = this;
  21251. _super.call(this, name, "oculusDistortionCorrection", [
  21252. 'LensCenter',
  21253. 'Scale',
  21254. 'ScaleIn',
  21255. 'HmdWarpParam'
  21256. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  21257. this._isRightEye = isRightEye;
  21258. this._distortionFactors = cameraSettings.DistortionK;
  21259. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  21260. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  21261. this.onSizeChanged = function () {
  21262. _this.aspectRatio = _this.width * .5 / _this.height;
  21263. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  21264. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  21265. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  21266. };
  21267. this.onApply = function (effect) {
  21268. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  21269. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  21270. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  21271. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  21272. };
  21273. }
  21274. return OculusDistortionCorrectionPostProcess;
  21275. })(BABYLON.PostProcess);
  21276. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  21277. })(BABYLON || (BABYLON = {}));
  21278. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  21279. // 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
  21280. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  21281. var BABYLON;
  21282. (function (BABYLON) {
  21283. (function (JoystickAxis) {
  21284. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  21285. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  21286. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  21287. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  21288. var JoystickAxis = BABYLON.JoystickAxis;
  21289. var VirtualJoystick = (function () {
  21290. function VirtualJoystick(leftJoystick) {
  21291. var _this = this;
  21292. if (leftJoystick) {
  21293. this._leftJoystick = true;
  21294. }
  21295. else {
  21296. this._leftJoystick = false;
  21297. }
  21298. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21299. VirtualJoystick._globalJoystickIndex++;
  21300. // By default left & right arrow keys are moving the X
  21301. // and up & down keys are moving the Y
  21302. this._axisTargetedByLeftAndRight = 0 /* X */;
  21303. this._axisTargetedByUpAndDown = 1 /* Y */;
  21304. this.reverseLeftRight = false;
  21305. this.reverseUpDown = false;
  21306. // collections of pointers
  21307. this._touches = new BABYLON.VirtualJoystick.Collection();
  21308. this.deltaPosition = BABYLON.Vector3.Zero();
  21309. this._joystickSensibility = 25;
  21310. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21311. this._rotationSpeed = 25;
  21312. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21313. this._rotateOnAxisRelativeToMesh = false;
  21314. // injecting a canvas element on top of the canvas 3D game
  21315. if (!VirtualJoystick.vjCanvas) {
  21316. window.addEventListener("resize", function () {
  21317. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21318. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21319. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21320. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21321. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21322. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21323. }, false);
  21324. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21325. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21326. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21327. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21328. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21329. VirtualJoystick.vjCanvas.style.width = "100%";
  21330. VirtualJoystick.vjCanvas.style.height = "100%";
  21331. VirtualJoystick.vjCanvas.style.position = "absolute";
  21332. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21333. VirtualJoystick.vjCanvas.style.top = "0px";
  21334. VirtualJoystick.vjCanvas.style.left = "0px";
  21335. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21336. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21337. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21338. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21339. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21340. document.body.appendChild(VirtualJoystick.vjCanvas);
  21341. }
  21342. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21343. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21344. this.pressed = false;
  21345. // default joystick color
  21346. this._joystickColor = "cyan";
  21347. this._joystickPointerID = -1;
  21348. // current joystick position
  21349. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21350. // origin joystick position
  21351. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21352. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21353. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21354. _this._onPointerDown(evt);
  21355. }, false);
  21356. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21357. _this._onPointerMove(evt);
  21358. }, false);
  21359. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21360. _this._onPointerUp(evt);
  21361. }, false);
  21362. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21363. _this._onPointerUp(evt);
  21364. }, false);
  21365. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21366. evt.preventDefault(); // Disables system menu
  21367. }, false);
  21368. requestAnimationFrame(function () {
  21369. _this._drawVirtualJoystick();
  21370. });
  21371. }
  21372. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21373. this._joystickSensibility = newJoystickSensibility;
  21374. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21375. };
  21376. VirtualJoystick.prototype._onPointerDown = function (e) {
  21377. var positionOnScreenCondition;
  21378. e.preventDefault();
  21379. if (this._leftJoystick === true) {
  21380. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21381. }
  21382. else {
  21383. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21384. }
  21385. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21386. // First contact will be dedicated to the virtual joystick
  21387. this._joystickPointerID = e.pointerId;
  21388. this._joystickPointerStartPos.x = e.clientX;
  21389. this._joystickPointerStartPos.y = e.clientY;
  21390. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21391. this._deltaJoystickVector.x = 0;
  21392. this._deltaJoystickVector.y = 0;
  21393. this.pressed = true;
  21394. this._touches.add(e.pointerId.toString(), e);
  21395. }
  21396. else {
  21397. // You can only trigger the action buttons with a joystick declared
  21398. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21399. this._action();
  21400. this._touches.add(e.pointerId.toString(), e);
  21401. }
  21402. }
  21403. };
  21404. VirtualJoystick.prototype._onPointerMove = function (e) {
  21405. // If the current pointer is the one associated to the joystick (first touch contact)
  21406. if (this._joystickPointerID == e.pointerId) {
  21407. this._joystickPointerPos.x = e.clientX;
  21408. this._joystickPointerPos.y = e.clientY;
  21409. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21410. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21411. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21412. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21413. switch (this._axisTargetedByLeftAndRight) {
  21414. case 0 /* X */:
  21415. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21416. break;
  21417. case 1 /* Y */:
  21418. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21419. break;
  21420. case 2 /* Z */:
  21421. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21422. break;
  21423. }
  21424. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21425. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21426. switch (this._axisTargetedByUpAndDown) {
  21427. case 0 /* X */:
  21428. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21429. break;
  21430. case 1 /* Y */:
  21431. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21432. break;
  21433. case 2 /* Z */:
  21434. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21435. break;
  21436. }
  21437. }
  21438. else {
  21439. if (this._touches.item(e.pointerId.toString())) {
  21440. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21441. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21442. }
  21443. }
  21444. };
  21445. VirtualJoystick.prototype._onPointerUp = function (e) {
  21446. this._clearCanvas();
  21447. if (this._joystickPointerID == e.pointerId) {
  21448. this._joystickPointerID = -1;
  21449. this.pressed = false;
  21450. }
  21451. this._deltaJoystickVector.x = 0;
  21452. this._deltaJoystickVector.y = 0;
  21453. this._touches.remove(e.pointerId.toString());
  21454. };
  21455. /**
  21456. * Change the color of the virtual joystick
  21457. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21458. */
  21459. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21460. this._joystickColor = newColor;
  21461. };
  21462. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21463. this._action = action;
  21464. };
  21465. // Define which axis you'd like to control for left & right
  21466. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21467. switch (axis) {
  21468. case 0 /* X */:
  21469. case 1 /* Y */:
  21470. case 2 /* Z */:
  21471. this._axisTargetedByLeftAndRight = axis;
  21472. break;
  21473. default:
  21474. this._axisTargetedByLeftAndRight = 0 /* X */;
  21475. break;
  21476. }
  21477. };
  21478. // Define which axis you'd like to control for up & down
  21479. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21480. switch (axis) {
  21481. case 0 /* X */:
  21482. case 1 /* Y */:
  21483. case 2 /* Z */:
  21484. this._axisTargetedByUpAndDown = axis;
  21485. break;
  21486. default:
  21487. this._axisTargetedByUpAndDown = 1 /* Y */;
  21488. break;
  21489. }
  21490. };
  21491. VirtualJoystick.prototype._clearCanvas = function () {
  21492. if (this._leftJoystick) {
  21493. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21494. }
  21495. else {
  21496. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21497. }
  21498. };
  21499. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21500. var _this = this;
  21501. if (this.pressed) {
  21502. this._clearCanvas();
  21503. this._touches.forEach(function (touch) {
  21504. if (touch.pointerId === _this._joystickPointerID) {
  21505. VirtualJoystick.vjCanvasContext.beginPath();
  21506. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21507. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21508. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21509. VirtualJoystick.vjCanvasContext.stroke();
  21510. VirtualJoystick.vjCanvasContext.beginPath();
  21511. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21512. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21513. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21514. VirtualJoystick.vjCanvasContext.stroke();
  21515. VirtualJoystick.vjCanvasContext.beginPath();
  21516. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21517. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21518. VirtualJoystick.vjCanvasContext.stroke();
  21519. }
  21520. else {
  21521. VirtualJoystick.vjCanvasContext.beginPath();
  21522. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21523. VirtualJoystick.vjCanvasContext.beginPath();
  21524. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21525. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21526. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21527. VirtualJoystick.vjCanvasContext.stroke();
  21528. }
  21529. ;
  21530. });
  21531. }
  21532. requestAnimationFrame(function () {
  21533. _this._drawVirtualJoystick();
  21534. });
  21535. };
  21536. VirtualJoystick.prototype.releaseCanvas = function () {
  21537. if (VirtualJoystick.vjCanvas) {
  21538. document.body.removeChild(VirtualJoystick.vjCanvas);
  21539. VirtualJoystick.vjCanvas = null;
  21540. }
  21541. };
  21542. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21543. VirtualJoystick._globalJoystickIndex = 0;
  21544. return VirtualJoystick;
  21545. })();
  21546. BABYLON.VirtualJoystick = VirtualJoystick;
  21547. })(BABYLON || (BABYLON = {}));
  21548. var BABYLON;
  21549. (function (BABYLON) {
  21550. var VirtualJoystick;
  21551. (function (VirtualJoystick) {
  21552. var Collection = (function () {
  21553. function Collection() {
  21554. this._count = 0;
  21555. this._collection = new Array();
  21556. }
  21557. Collection.prototype.Count = function () {
  21558. return this._count;
  21559. };
  21560. Collection.prototype.add = function (key, item) {
  21561. if (this._collection[key] != undefined) {
  21562. return undefined;
  21563. }
  21564. this._collection[key] = item;
  21565. return ++this._count;
  21566. };
  21567. Collection.prototype.remove = function (key) {
  21568. if (this._collection[key] == undefined) {
  21569. return undefined;
  21570. }
  21571. delete this._collection[key];
  21572. return --this._count;
  21573. };
  21574. Collection.prototype.item = function (key) {
  21575. return this._collection[key];
  21576. };
  21577. Collection.prototype.forEach = function (block) {
  21578. var key;
  21579. for (key in this._collection) {
  21580. if (this._collection.hasOwnProperty(key)) {
  21581. block(this._collection[key]);
  21582. }
  21583. }
  21584. };
  21585. return Collection;
  21586. })();
  21587. VirtualJoystick.Collection = Collection;
  21588. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  21589. })(BABYLON || (BABYLON = {}));
  21590. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21591. var BABYLON;
  21592. (function (BABYLON) {
  21593. var OculusRiftDevKit2013_Metric = {
  21594. HResolution: 1280,
  21595. VResolution: 800,
  21596. HScreenSize: 0.149759993,
  21597. VScreenSize: 0.0935999975,
  21598. VScreenCenter: 0.0467999987,
  21599. EyeToScreenDistance: 0.0410000011,
  21600. LensSeparationDistance: 0.0635000020,
  21601. InterpupillaryDistance: 0.0640000030,
  21602. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21603. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21604. PostProcessScaleFactor: 1.714605507808412,
  21605. LensCenterOffset: 0.151976421
  21606. };
  21607. var _OculusInnerCamera = (function (_super) {
  21608. __extends(_OculusInnerCamera, _super);
  21609. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21610. _super.call(this, name, position, scene);
  21611. this._workMatrix = new BABYLON.Matrix();
  21612. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21613. // Constants
  21614. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21615. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21616. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21617. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21618. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21619. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21620. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21621. // Postprocess
  21622. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21623. }
  21624. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21625. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21626. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21627. return this._projectionMatrix;
  21628. };
  21629. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21630. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21631. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21632. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21633. // Computing target and final matrix
  21634. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21635. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21636. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21637. return this._viewMatrix;
  21638. };
  21639. return _OculusInnerCamera;
  21640. })(BABYLON.FreeCamera);
  21641. var OculusCamera = (function (_super) {
  21642. __extends(OculusCamera, _super);
  21643. function OculusCamera(name, position, scene) {
  21644. _super.call(this, name, position, scene);
  21645. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21646. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21647. this.subCameras.push(this._leftCamera);
  21648. this.subCameras.push(this._rightCamera);
  21649. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21650. }
  21651. OculusCamera.prototype._update = function () {
  21652. this._leftCamera.position.copyFrom(this.position);
  21653. this._rightCamera.position.copyFrom(this.position);
  21654. this._updateCamera(this._leftCamera);
  21655. this._updateCamera(this._rightCamera);
  21656. _super.prototype._update.call(this);
  21657. };
  21658. OculusCamera.prototype._updateCamera = function (camera) {
  21659. camera.minZ = this.minZ;
  21660. camera.maxZ = this.maxZ;
  21661. camera.rotation.x = this.rotation.x;
  21662. camera.rotation.y = this.rotation.y;
  21663. camera.rotation.z = this.rotation.z;
  21664. };
  21665. // Oculus events
  21666. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21667. var yaw = evt.alpha / 180 * Math.PI;
  21668. var pitch = evt.beta / 180 * Math.PI;
  21669. var roll = evt.gamma / 180 * Math.PI;
  21670. if (!this._offsetOrientation) {
  21671. this._offsetOrientation = {
  21672. yaw: yaw,
  21673. pitch: pitch,
  21674. roll: roll
  21675. };
  21676. return;
  21677. }
  21678. else {
  21679. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21680. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21681. this.rotation.z += this._offsetOrientation.roll - roll;
  21682. this._offsetOrientation.yaw = yaw;
  21683. this._offsetOrientation.pitch = pitch;
  21684. this._offsetOrientation.roll = roll;
  21685. }
  21686. };
  21687. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21688. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21689. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21690. };
  21691. OculusCamera.prototype.detachControl = function (element) {
  21692. _super.prototype.detachControl.call(this, element);
  21693. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21694. };
  21695. return OculusCamera;
  21696. })(BABYLON.FreeCamera);
  21697. BABYLON.OculusCamera = OculusCamera;
  21698. })(BABYLON || (BABYLON = {}));
  21699. //# sourceMappingURL=babylon.oculusCamera.js.map
  21700. var BABYLON;
  21701. (function (BABYLON) {
  21702. var OculusRiftDevKit2013_Metric = {
  21703. HResolution: 1280,
  21704. VResolution: 800,
  21705. HScreenSize: 0.149759993,
  21706. VScreenSize: 0.0935999975,
  21707. VScreenCenter: 0.0467999987,
  21708. EyeToScreenDistance: 0.0410000011,
  21709. LensSeparationDistance: 0.0635000020,
  21710. InterpupillaryDistance: 0.0640000030,
  21711. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21712. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21713. PostProcessScaleFactor: 1.714605507808412,
  21714. LensCenterOffset: 0.151976421
  21715. };
  21716. var _OculusInnerGamepadCamera = (function (_super) {
  21717. __extends(_OculusInnerGamepadCamera, _super);
  21718. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21719. _super.call(this, name, position, scene);
  21720. this._workMatrix = new BABYLON.Matrix();
  21721. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21722. // Constants
  21723. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21724. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21725. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21726. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21727. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21728. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21729. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21730. // Postprocess
  21731. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21732. }
  21733. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21734. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21735. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21736. return this._projectionMatrix;
  21737. };
  21738. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21739. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21740. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21741. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21742. // Computing target and final matrix
  21743. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21744. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21745. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21746. return this._viewMatrix;
  21747. };
  21748. return _OculusInnerGamepadCamera;
  21749. })(BABYLON.FreeCamera);
  21750. var OculusGamepadCamera = (function (_super) {
  21751. __extends(OculusGamepadCamera, _super);
  21752. function OculusGamepadCamera(name, position, scene) {
  21753. var _this = this;
  21754. _super.call(this, name, position, scene);
  21755. this.angularSensibility = 200;
  21756. this.moveSensibility = 75;
  21757. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21758. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21759. this.subCameras.push(this._leftCamera);
  21760. this.subCameras.push(this._rightCamera);
  21761. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21762. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21763. _this._onNewGameConnected(gamepad);
  21764. });
  21765. }
  21766. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21767. // Only the first gamepad can control the camera
  21768. if (gamepad.index === 0) {
  21769. this._gamepad = gamepad;
  21770. }
  21771. };
  21772. OculusGamepadCamera.prototype._update = function () {
  21773. this._leftCamera.position.copyFrom(this.position);
  21774. this._rightCamera.position.copyFrom(this.position);
  21775. this._updateCamera(this._leftCamera);
  21776. this._updateCamera(this._rightCamera);
  21777. _super.prototype._update.call(this);
  21778. };
  21779. OculusGamepadCamera.prototype._checkInputs = function () {
  21780. if (!this._gamepad) {
  21781. return;
  21782. }
  21783. var LSValues = this._gamepad.leftStick;
  21784. var normalizedLX = LSValues.x / this.moveSensibility;
  21785. var normalizedLY = LSValues.y / this.moveSensibility;
  21786. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21787. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21788. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21789. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21790. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21791. };
  21792. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21793. camera.minZ = this.minZ;
  21794. camera.maxZ = this.maxZ;
  21795. camera.rotation.x = this.rotation.x;
  21796. camera.rotation.y = this.rotation.y;
  21797. camera.rotation.z = this.rotation.z;
  21798. };
  21799. // Oculus events
  21800. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21801. var yaw = evt.alpha / 180 * Math.PI;
  21802. var pitch = evt.beta / 180 * Math.PI;
  21803. var roll = evt.gamma / 180 * Math.PI;
  21804. if (!this._offsetOrientation) {
  21805. this._offsetOrientation = {
  21806. yaw: yaw,
  21807. pitch: pitch,
  21808. roll: roll
  21809. };
  21810. return;
  21811. }
  21812. else {
  21813. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21814. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21815. this.rotation.z += this._offsetOrientation.roll - roll;
  21816. this._offsetOrientation.yaw = yaw;
  21817. this._offsetOrientation.pitch = pitch;
  21818. this._offsetOrientation.roll = roll;
  21819. }
  21820. };
  21821. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21822. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21823. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21824. };
  21825. OculusGamepadCamera.prototype.detachControl = function (element) {
  21826. _super.prototype.detachControl.call(this, element);
  21827. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21828. };
  21829. OculusGamepadCamera.prototype.dispose = function () {
  21830. this._gamepads.dispose();
  21831. _super.prototype.dispose.call(this);
  21832. };
  21833. return OculusGamepadCamera;
  21834. })(BABYLON.FreeCamera);
  21835. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21836. })(BABYLON || (BABYLON = {}));
  21837. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21838. var BABYLON;
  21839. (function (BABYLON) {
  21840. // We're mainly based on the logic defined into the FreeCamera code
  21841. var VirtualJoysticksCamera = (function (_super) {
  21842. __extends(VirtualJoysticksCamera, _super);
  21843. function VirtualJoysticksCamera(name, position, scene) {
  21844. _super.call(this, name, position, scene);
  21845. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21846. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21847. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21848. this._leftjoystick.setJoystickSensibility(0.15);
  21849. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21850. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21851. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21852. this._rightjoystick.reverseUpDown = true;
  21853. this._rightjoystick.setJoystickSensibility(0.05);
  21854. this._rightjoystick.setJoystickColor("yellow");
  21855. }
  21856. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21857. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21858. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21859. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21860. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21861. if (!this._leftjoystick.pressed) {
  21862. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21863. }
  21864. if (!this._rightjoystick.pressed) {
  21865. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21866. }
  21867. };
  21868. VirtualJoysticksCamera.prototype.dispose = function () {
  21869. this._leftjoystick.releaseCanvas();
  21870. _super.prototype.dispose.call(this);
  21871. };
  21872. return VirtualJoysticksCamera;
  21873. })(BABYLON.FreeCamera);
  21874. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21875. })(BABYLON || (BABYLON = {}));
  21876. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21877. var BABYLON;
  21878. (function (BABYLON) {
  21879. var ShaderMaterial = (function (_super) {
  21880. __extends(ShaderMaterial, _super);
  21881. function ShaderMaterial(name, scene, shaderPath, options) {
  21882. _super.call(this, name, scene);
  21883. this._textures = new Array();
  21884. this._floats = new Array();
  21885. this._floatsArrays = {};
  21886. this._colors3 = new Array();
  21887. this._colors4 = new Array();
  21888. this._vectors2 = new Array();
  21889. this._vectors3 = new Array();
  21890. this._matrices = new Array();
  21891. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21892. this._shaderPath = shaderPath;
  21893. options.needAlphaBlending = options.needAlphaBlending || false;
  21894. options.needAlphaTesting = options.needAlphaTesting || false;
  21895. options.attributes = options.attributes || ["position", "normal", "uv"];
  21896. options.uniforms = options.uniforms || ["worldViewProjection"];
  21897. options.samplers = options.samplers || [];
  21898. this._options = options;
  21899. }
  21900. ShaderMaterial.prototype.needAlphaBlending = function () {
  21901. return this._options.needAlphaBlending;
  21902. };
  21903. ShaderMaterial.prototype.needAlphaTesting = function () {
  21904. return this._options.needAlphaTesting;
  21905. };
  21906. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21907. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21908. this._options.uniforms.push(uniformName);
  21909. }
  21910. };
  21911. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21912. if (this._options.samplers.indexOf(name) === -1) {
  21913. this._options.samplers.push(name);
  21914. }
  21915. this._textures[name] = texture;
  21916. return this;
  21917. };
  21918. ShaderMaterial.prototype.setFloat = function (name, value) {
  21919. this._checkUniform(name);
  21920. this._floats[name] = value;
  21921. return this;
  21922. };
  21923. ShaderMaterial.prototype.setFloats = function (name, value) {
  21924. this._checkUniform(name);
  21925. this._floatsArrays[name] = value;
  21926. return this;
  21927. };
  21928. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21929. this._checkUniform(name);
  21930. this._colors3[name] = value;
  21931. return this;
  21932. };
  21933. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21934. this._checkUniform(name);
  21935. this._colors4[name] = value;
  21936. return this;
  21937. };
  21938. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21939. this._checkUniform(name);
  21940. this._vectors2[name] = value;
  21941. return this;
  21942. };
  21943. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21944. this._checkUniform(name);
  21945. this._vectors3[name] = value;
  21946. return this;
  21947. };
  21948. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21949. this._checkUniform(name);
  21950. this._matrices[name] = value;
  21951. return this;
  21952. };
  21953. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  21954. var scene = this.getScene();
  21955. var engine = scene.getEngine();
  21956. if (!this.checkReadyOnEveryCall) {
  21957. if (this._renderId === scene.getRenderId()) {
  21958. return true;
  21959. }
  21960. }
  21961. // Instances
  21962. var defines = [];
  21963. var fallbacks = new BABYLON.EffectFallbacks();
  21964. if (useInstances) {
  21965. defines.push("#define INSTANCES");
  21966. }
  21967. // Bones
  21968. if (mesh && mesh.useBones) {
  21969. defines.push("#define BONES");
  21970. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  21971. defines.push("#define BONES4");
  21972. fallbacks.addFallback(0, "BONES4");
  21973. }
  21974. // Alpha test
  21975. if (engine.getAlphaTesting()) {
  21976. defines.push("#define ALPHATEST");
  21977. }
  21978. var previousEffect = this._effect;
  21979. var join = defines.join("\n");
  21980. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  21981. if (!this._effect.isReady()) {
  21982. return false;
  21983. }
  21984. if (previousEffect !== this._effect) {
  21985. scene.resetCachedMaterial();
  21986. }
  21987. this._renderId = scene.getRenderId();
  21988. return true;
  21989. };
  21990. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21991. var scene = this.getScene();
  21992. if (this._options.uniforms.indexOf("world") !== -1) {
  21993. this._effect.setMatrix("world", world);
  21994. }
  21995. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21996. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21997. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21998. }
  21999. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  22000. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  22001. }
  22002. };
  22003. ShaderMaterial.prototype.bind = function (world, mesh) {
  22004. // Std values
  22005. this.bindOnlyWorldMatrix(world);
  22006. if (this.getScene().getCachedMaterial() !== this) {
  22007. if (this._options.uniforms.indexOf("view") !== -1) {
  22008. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  22009. }
  22010. if (this._options.uniforms.indexOf("projection") !== -1) {
  22011. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  22012. }
  22013. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  22014. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22015. }
  22016. // Bones
  22017. if (mesh.useBones) {
  22018. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22019. }
  22020. for (var name in this._textures) {
  22021. this._effect.setTexture(name, this._textures[name]);
  22022. }
  22023. for (name in this._floats) {
  22024. this._effect.setFloat(name, this._floats[name]);
  22025. }
  22026. for (name in this._floatsArrays) {
  22027. this._effect.setArray(name, this._floatsArrays[name]);
  22028. }
  22029. for (name in this._colors3) {
  22030. this._effect.setColor3(name, this._colors3[name]);
  22031. }
  22032. for (name in this._colors4) {
  22033. var color = this._colors4[name];
  22034. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22035. }
  22036. for (name in this._vectors2) {
  22037. this._effect.setVector2(name, this._vectors2[name]);
  22038. }
  22039. for (name in this._vectors3) {
  22040. this._effect.setVector3(name, this._vectors3[name]);
  22041. }
  22042. for (name in this._matrices) {
  22043. this._effect.setMatrix(name, this._matrices[name]);
  22044. }
  22045. }
  22046. _super.prototype.bind.call(this, world, mesh);
  22047. };
  22048. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  22049. for (var name in this._textures) {
  22050. this._textures[name].dispose();
  22051. }
  22052. this._textures = [];
  22053. _super.prototype.dispose.call(this, forceDisposeEffect);
  22054. };
  22055. return ShaderMaterial;
  22056. })(BABYLON.Material);
  22057. BABYLON.ShaderMaterial = ShaderMaterial;
  22058. })(BABYLON || (BABYLON = {}));
  22059. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  22060. (function (BABYLON) {
  22061. var VertexData = (function () {
  22062. function VertexData() {
  22063. }
  22064. VertexData.prototype.set = function (data, kind) {
  22065. switch (kind) {
  22066. case BABYLON.VertexBuffer.PositionKind:
  22067. this.positions = data;
  22068. break;
  22069. case BABYLON.VertexBuffer.NormalKind:
  22070. this.normals = data;
  22071. break;
  22072. case BABYLON.VertexBuffer.UVKind:
  22073. this.uvs = data;
  22074. break;
  22075. case BABYLON.VertexBuffer.UV2Kind:
  22076. this.uv2s = data;
  22077. break;
  22078. case BABYLON.VertexBuffer.ColorKind:
  22079. this.colors = data;
  22080. break;
  22081. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22082. this.matricesIndices = data;
  22083. break;
  22084. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22085. this.matricesWeights = data;
  22086. break;
  22087. }
  22088. };
  22089. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22090. this._applyTo(mesh, updatable);
  22091. };
  22092. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22093. this._applyTo(geometry, updatable);
  22094. };
  22095. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22096. this._update(mesh);
  22097. };
  22098. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22099. this._update(geometry);
  22100. };
  22101. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22102. if (this.positions) {
  22103. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22104. }
  22105. if (this.normals) {
  22106. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22107. }
  22108. if (this.uvs) {
  22109. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22110. }
  22111. if (this.uv2s) {
  22112. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  22113. }
  22114. if (this.colors) {
  22115. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22116. }
  22117. if (this.matricesIndices) {
  22118. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22119. }
  22120. if (this.matricesWeights) {
  22121. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22122. }
  22123. if (this.indices) {
  22124. meshOrGeometry.setIndices(this.indices);
  22125. }
  22126. };
  22127. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22128. if (this.positions) {
  22129. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22130. }
  22131. if (this.normals) {
  22132. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22133. }
  22134. if (this.uvs) {
  22135. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22136. }
  22137. if (this.uv2s) {
  22138. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  22139. }
  22140. if (this.colors) {
  22141. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22142. }
  22143. if (this.matricesIndices) {
  22144. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22145. }
  22146. if (this.matricesWeights) {
  22147. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22148. }
  22149. if (this.indices) {
  22150. meshOrGeometry.setIndices(this.indices);
  22151. }
  22152. };
  22153. VertexData.prototype.transform = function (matrix) {
  22154. var transformed = BABYLON.Vector3.Zero();
  22155. if (this.positions) {
  22156. var position = BABYLON.Vector3.Zero();
  22157. for (var index = 0; index < this.positions.length; index += 3) {
  22158. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22159. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22160. this.positions[index] = transformed.x;
  22161. this.positions[index + 1] = transformed.y;
  22162. this.positions[index + 2] = transformed.z;
  22163. }
  22164. }
  22165. if (this.normals) {
  22166. var normal = BABYLON.Vector3.Zero();
  22167. for (index = 0; index < this.normals.length; index += 3) {
  22168. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22169. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22170. this.normals[index] = transformed.x;
  22171. this.normals[index + 1] = transformed.y;
  22172. this.normals[index + 2] = transformed.z;
  22173. }
  22174. }
  22175. };
  22176. VertexData.prototype.merge = function (other) {
  22177. if (other.indices) {
  22178. if (!this.indices) {
  22179. this.indices = [];
  22180. }
  22181. var offset = this.positions ? this.positions.length / 3 : 0;
  22182. for (var index = 0; index < other.indices.length; index++) {
  22183. this.indices.push(other.indices[index] + offset);
  22184. }
  22185. }
  22186. if (other.positions) {
  22187. if (!this.positions) {
  22188. this.positions = [];
  22189. }
  22190. for (index = 0; index < other.positions.length; index++) {
  22191. this.positions.push(other.positions[index]);
  22192. }
  22193. }
  22194. if (other.normals) {
  22195. if (!this.normals) {
  22196. this.normals = [];
  22197. }
  22198. for (index = 0; index < other.normals.length; index++) {
  22199. this.normals.push(other.normals[index]);
  22200. }
  22201. }
  22202. if (other.uvs) {
  22203. if (!this.uvs) {
  22204. this.uvs = [];
  22205. }
  22206. for (index = 0; index < other.uvs.length; index++) {
  22207. this.uvs.push(other.uvs[index]);
  22208. }
  22209. }
  22210. if (other.uv2s) {
  22211. if (!this.uv2s) {
  22212. this.uv2s = [];
  22213. }
  22214. for (index = 0; index < other.uv2s.length; index++) {
  22215. this.uv2s.push(other.uv2s[index]);
  22216. }
  22217. }
  22218. if (other.matricesIndices) {
  22219. if (!this.matricesIndices) {
  22220. this.matricesIndices = [];
  22221. }
  22222. for (index = 0; index < other.matricesIndices.length; index++) {
  22223. this.matricesIndices.push(other.matricesIndices[index]);
  22224. }
  22225. }
  22226. if (other.matricesWeights) {
  22227. if (!this.matricesWeights) {
  22228. this.matricesWeights = [];
  22229. }
  22230. for (index = 0; index < other.matricesWeights.length; index++) {
  22231. this.matricesWeights.push(other.matricesWeights[index]);
  22232. }
  22233. }
  22234. if (other.colors) {
  22235. if (!this.colors) {
  22236. this.colors = [];
  22237. }
  22238. for (index = 0; index < other.colors.length; index++) {
  22239. this.colors.push(other.colors[index]);
  22240. }
  22241. }
  22242. };
  22243. // Statics
  22244. VertexData.ExtractFromMesh = function (mesh) {
  22245. return VertexData._ExtractFrom(mesh);
  22246. };
  22247. VertexData.ExtractFromGeometry = function (geometry) {
  22248. return VertexData._ExtractFrom(geometry);
  22249. };
  22250. VertexData._ExtractFrom = function (meshOrGeometry) {
  22251. var result = new VertexData();
  22252. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22253. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22254. }
  22255. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22256. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22257. }
  22258. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22259. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22260. }
  22261. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22262. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22263. }
  22264. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22265. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22266. }
  22267. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22268. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22269. }
  22270. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22271. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22272. }
  22273. result.indices = meshOrGeometry.getIndices();
  22274. return result;
  22275. };
  22276. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  22277. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22278. closeArray = closeArray || false;
  22279. closePath = closePath || false;
  22280. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22281. offset = offset || defaultOffset;
  22282. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22283. var positions = [];
  22284. var indices = [];
  22285. var normals = [];
  22286. var uvs = [];
  22287. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22288. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22289. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22290. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22291. var minlg; // minimal length among all paths from pathArray
  22292. var lg = []; // array of path lengths : nb of vertex per path
  22293. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  22294. var p; // path iterator
  22295. var i; // point iterator
  22296. var j; // point iterator
  22297. // if single path in pathArray
  22298. if (pathArray.length < 2) {
  22299. var ar1 = [];
  22300. var ar2 = [];
  22301. for (i = 0; i < pathArray[0].length - offset; i++) {
  22302. ar1.push(pathArray[0][i]);
  22303. ar2.push(pathArray[0][i + offset]);
  22304. }
  22305. pathArray = [ar1, ar2];
  22306. }
  22307. // positions and horizontal distances (u)
  22308. var idc = 0;
  22309. minlg = pathArray[0].length;
  22310. for (p = 0; p < pathArray.length; p++) {
  22311. uTotalDistance[p] = 0;
  22312. us[p] = [0];
  22313. var path = pathArray[p];
  22314. var l = path.length;
  22315. minlg = (minlg < l) ? minlg : l;
  22316. lg[p] = l;
  22317. idx[p] = idc;
  22318. j = 0;
  22319. while (j < l) {
  22320. positions.push(path[j].x, path[j].y, path[j].z);
  22321. if (j > 0) {
  22322. var vectlg = path[j].subtract(path[j - 1]).length();
  22323. var dist = vectlg + uTotalDistance[p];
  22324. us[p].push(dist);
  22325. uTotalDistance[p] = dist;
  22326. }
  22327. j++;
  22328. }
  22329. if (closePath) {
  22330. vectlg = path[0].subtract(path[j - 1]).length();
  22331. dist = vectlg + uTotalDistance[p];
  22332. uTotalDistance[p] = dist;
  22333. }
  22334. idc += l;
  22335. }
  22336. for (i = 0; i < minlg; i++) {
  22337. vTotalDistance[i] = 0;
  22338. vs[i] = [0];
  22339. var path1;
  22340. var path2;
  22341. for (p = 0; p < pathArray.length - 1; p++) {
  22342. path1 = pathArray[p];
  22343. path2 = pathArray[p + 1];
  22344. vectlg = path2[i].subtract(path1[i]).length();
  22345. dist = vectlg + vTotalDistance[i];
  22346. vs[i].push(dist);
  22347. vTotalDistance[i] = dist;
  22348. }
  22349. if (closeArray) {
  22350. path1 = pathArray[p];
  22351. path2 = pathArray[0];
  22352. vectlg = path2[i].subtract(path1[i]).length();
  22353. dist = vectlg + vTotalDistance[i];
  22354. vTotalDistance[i] = dist;
  22355. }
  22356. }
  22357. // uvs
  22358. var u;
  22359. var v;
  22360. for (p = 0; p < pathArray.length; p++) {
  22361. for (i = 0; i < minlg; i++) {
  22362. u = us[p][i] / uTotalDistance[p];
  22363. v = vs[i][p] / vTotalDistance[i];
  22364. uvs.push(u, v);
  22365. }
  22366. }
  22367. // indices
  22368. p = 0; // path index
  22369. var pi = 0; // positions array index
  22370. var l1 = lg[p] - 1; // path1 length
  22371. var l2 = lg[p + 1] - 1; // path2 length
  22372. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22373. var shft = idx[1] - idx[0]; // shift
  22374. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22375. var t1; // two consecutive triangles, so 4 points : point1
  22376. var t2; // point2
  22377. var t3; // point3
  22378. var t4; // point4
  22379. while (pi <= min && p < path1nb) {
  22380. // 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
  22381. t1 = pi;
  22382. t2 = pi + shft;
  22383. t3 = pi + 1;
  22384. t4 = pi + shft + 1;
  22385. indices.push(pi, pi + shft, pi + 1);
  22386. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22387. pi += 1;
  22388. if (pi === min) {
  22389. if (closePath) {
  22390. indices.push(pi, pi + shft, idx[p]);
  22391. indices.push(idx[p] + shft, idx[p], pi + shft);
  22392. t3 = idx[p];
  22393. t4 = idx[p] + shft;
  22394. }
  22395. p++;
  22396. if (p === lg.length - 1) {
  22397. shft = idx[0] - idx[p];
  22398. l1 = lg[p] - 1;
  22399. l2 = lg[0] - 1;
  22400. }
  22401. else {
  22402. shft = idx[p + 1] - idx[p];
  22403. l1 = lg[p] - 1;
  22404. l2 = lg[p + 1] - 1;
  22405. }
  22406. pi = idx[p];
  22407. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22408. }
  22409. }
  22410. // normals
  22411. VertexData.ComputeNormals(positions, indices, normals);
  22412. // sides
  22413. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22414. // Result
  22415. var vertexData = new VertexData();
  22416. vertexData.indices = indices;
  22417. vertexData.positions = positions;
  22418. vertexData.normals = normals;
  22419. vertexData.uvs = uvs;
  22420. return vertexData;
  22421. };
  22422. VertexData.CreateBox = function (size, sideOrientation) {
  22423. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22424. var normalsSource = [
  22425. new BABYLON.Vector3(0, 0, 1),
  22426. new BABYLON.Vector3(0, 0, -1),
  22427. new BABYLON.Vector3(1, 0, 0),
  22428. new BABYLON.Vector3(-1, 0, 0),
  22429. new BABYLON.Vector3(0, 1, 0),
  22430. new BABYLON.Vector3(0, -1, 0)
  22431. ];
  22432. var indices = [];
  22433. var positions = [];
  22434. var normals = [];
  22435. var uvs = [];
  22436. size = size || 1;
  22437. for (var index = 0; index < normalsSource.length; index++) {
  22438. var normal = normalsSource[index];
  22439. // Get two vectors perpendicular to the face normal and to each other.
  22440. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22441. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22442. // Six indices (two triangles) per face.
  22443. var verticesLength = positions.length / 3;
  22444. indices.push(verticesLength);
  22445. indices.push(verticesLength + 1);
  22446. indices.push(verticesLength + 2);
  22447. indices.push(verticesLength);
  22448. indices.push(verticesLength + 2);
  22449. indices.push(verticesLength + 3);
  22450. // Four vertices per face.
  22451. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22452. positions.push(vertex.x, vertex.y, vertex.z);
  22453. normals.push(normal.x, normal.y, normal.z);
  22454. uvs.push(1.0, 1.0);
  22455. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22456. positions.push(vertex.x, vertex.y, vertex.z);
  22457. normals.push(normal.x, normal.y, normal.z);
  22458. uvs.push(0.0, 1.0);
  22459. vertex = normal.add(side1).add(side2).scale(size / 2);
  22460. positions.push(vertex.x, vertex.y, vertex.z);
  22461. normals.push(normal.x, normal.y, normal.z);
  22462. uvs.push(0.0, 0.0);
  22463. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22464. positions.push(vertex.x, vertex.y, vertex.z);
  22465. normals.push(normal.x, normal.y, normal.z);
  22466. uvs.push(1.0, 0.0);
  22467. }
  22468. // sides
  22469. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22470. // Result
  22471. var vertexData = new VertexData();
  22472. vertexData.indices = indices;
  22473. vertexData.positions = positions;
  22474. vertexData.normals = normals;
  22475. vertexData.uvs = uvs;
  22476. return vertexData;
  22477. };
  22478. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22479. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22480. segments = segments || 32;
  22481. diameter = diameter || 1;
  22482. var radius = diameter / 2;
  22483. var totalZRotationSteps = 2 + segments;
  22484. var totalYRotationSteps = 2 * totalZRotationSteps;
  22485. var indices = [];
  22486. var positions = [];
  22487. var normals = [];
  22488. var uvs = [];
  22489. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22490. var normalizedZ = zRotationStep / totalZRotationSteps;
  22491. var angleZ = (normalizedZ * Math.PI);
  22492. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22493. var normalizedY = yRotationStep / totalYRotationSteps;
  22494. var angleY = normalizedY * Math.PI * 2;
  22495. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22496. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22497. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22498. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22499. var vertex = complete.scale(radius);
  22500. var normal = BABYLON.Vector3.Normalize(vertex);
  22501. positions.push(vertex.x, vertex.y, vertex.z);
  22502. normals.push(normal.x, normal.y, normal.z);
  22503. uvs.push(normalizedZ, normalizedY);
  22504. }
  22505. if (zRotationStep > 0) {
  22506. var verticesCount = positions.length / 3;
  22507. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22508. indices.push((firstIndex));
  22509. indices.push((firstIndex + 1));
  22510. indices.push(firstIndex + totalYRotationSteps + 1);
  22511. indices.push((firstIndex + totalYRotationSteps + 1));
  22512. indices.push((firstIndex + 1));
  22513. indices.push((firstIndex + totalYRotationSteps + 2));
  22514. }
  22515. }
  22516. }
  22517. // Sides
  22518. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22519. // Result
  22520. var vertexData = new VertexData();
  22521. vertexData.indices = indices;
  22522. vertexData.positions = positions;
  22523. vertexData.normals = normals;
  22524. vertexData.uvs = uvs;
  22525. return vertexData;
  22526. };
  22527. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22528. if (subdivisions === void 0) { subdivisions = 1; }
  22529. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22530. var radiusTop = diameterTop / 2;
  22531. var radiusBottom = diameterBottom / 2;
  22532. var indices = [];
  22533. var positions = [];
  22534. var normals = [];
  22535. var uvs = [];
  22536. height = height || 1;
  22537. diameterTop = diameterTop || 0.5;
  22538. diameterBottom = diameterBottom || 1;
  22539. tessellation = tessellation || 16;
  22540. subdivisions = subdivisions || 1;
  22541. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22542. var getCircleVector = function (i) {
  22543. var angle = (i * 2.0 * Math.PI / tessellation);
  22544. var dx = Math.cos(angle);
  22545. var dz = Math.sin(angle);
  22546. return new BABYLON.Vector3(dx, 0, dz);
  22547. };
  22548. var createCylinderCap = function (isTop) {
  22549. var radius = isTop ? radiusTop : radiusBottom;
  22550. if (radius === 0) {
  22551. return;
  22552. }
  22553. var vbase = positions.length / 3;
  22554. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22555. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22556. if (!isTop) {
  22557. offset.scaleInPlace(-1);
  22558. textureScale.x = -textureScale.x;
  22559. }
  22560. for (var i = 0; i < tessellation; i++) {
  22561. var circleVector = getCircleVector(i);
  22562. var position = circleVector.scale(radius).add(offset);
  22563. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22564. positions.push(position.x, position.y, position.z);
  22565. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22566. }
  22567. for (i = 0; i < tessellation - 2; i++) {
  22568. if (!isTop) {
  22569. indices.push(vbase);
  22570. indices.push(vbase + (i + 2) % tessellation);
  22571. indices.push(vbase + (i + 1) % tessellation);
  22572. }
  22573. else {
  22574. indices.push(vbase);
  22575. indices.push(vbase + (i + 1) % tessellation);
  22576. indices.push(vbase + (i + 2) % tessellation);
  22577. }
  22578. }
  22579. };
  22580. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22581. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22582. var stride = tessellation + 1;
  22583. for (var i = 0; i <= tessellation; i++) {
  22584. var circleVector = getCircleVector(i);
  22585. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22586. var position, radius = radiusBottom;
  22587. for (var s = 0; s <= subdivisions; s++) {
  22588. // Update variables
  22589. position = circleVector.scale(radius);
  22590. position.addInPlace(base.add(offset.scale(s)));
  22591. textureCoordinate.y += 1 / subdivisions;
  22592. radius += (radiusTop - radiusBottom) / subdivisions;
  22593. // Push in arrays
  22594. positions.push(position.x, position.y, position.z);
  22595. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22596. }
  22597. }
  22598. subdivisions += 1;
  22599. for (s = 0; s < subdivisions - 1; s++) {
  22600. for (i = 0; i <= tessellation; i++) {
  22601. indices.push(i * subdivisions + s);
  22602. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22603. indices.push(i * subdivisions + (s + 1));
  22604. indices.push(i * subdivisions + (s + 1));
  22605. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22606. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22607. }
  22608. }
  22609. // Create flat triangle fan caps to seal the top and bottom.
  22610. createCylinderCap(true);
  22611. createCylinderCap(false);
  22612. // Normals
  22613. VertexData.ComputeNormals(positions, indices, normals);
  22614. // Sides
  22615. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22616. // Result
  22617. var vertexData = new VertexData();
  22618. vertexData.indices = indices;
  22619. vertexData.positions = positions;
  22620. vertexData.normals = normals;
  22621. vertexData.uvs = uvs;
  22622. return vertexData;
  22623. };
  22624. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22625. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22626. var indices = [];
  22627. var positions = [];
  22628. var normals = [];
  22629. var uvs = [];
  22630. diameter = diameter || 1;
  22631. thickness = thickness || 0.5;
  22632. tessellation = tessellation || 16;
  22633. var stride = tessellation + 1;
  22634. for (var i = 0; i <= tessellation; i++) {
  22635. var u = i / tessellation;
  22636. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22637. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22638. for (var j = 0; j <= tessellation; j++) {
  22639. var v = 1 - j / tessellation;
  22640. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22641. var dx = Math.cos(innerAngle);
  22642. var dy = Math.sin(innerAngle);
  22643. // Create a vertex.
  22644. var normal = new BABYLON.Vector3(dx, dy, 0);
  22645. var position = normal.scale(thickness / 2);
  22646. var textureCoordinate = new BABYLON.Vector2(u, v);
  22647. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22648. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22649. positions.push(position.x, position.y, position.z);
  22650. normals.push(normal.x, normal.y, normal.z);
  22651. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22652. // And create indices for two triangles.
  22653. var nextI = (i + 1) % stride;
  22654. var nextJ = (j + 1) % stride;
  22655. indices.push(i * stride + j);
  22656. indices.push(i * stride + nextJ);
  22657. indices.push(nextI * stride + j);
  22658. indices.push(i * stride + nextJ);
  22659. indices.push(nextI * stride + nextJ);
  22660. indices.push(nextI * stride + j);
  22661. }
  22662. }
  22663. // Sides
  22664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22665. // Result
  22666. var vertexData = new VertexData();
  22667. vertexData.indices = indices;
  22668. vertexData.positions = positions;
  22669. vertexData.normals = normals;
  22670. vertexData.uvs = uvs;
  22671. return vertexData;
  22672. };
  22673. VertexData.CreateLines = function (points) {
  22674. var indices = [];
  22675. var positions = [];
  22676. for (var index = 0; index < points.length; index++) {
  22677. positions.push(points[index].x, points[index].y, points[index].z);
  22678. if (index > 0) {
  22679. indices.push(index - 1);
  22680. indices.push(index);
  22681. }
  22682. }
  22683. // Result
  22684. var vertexData = new VertexData();
  22685. vertexData.indices = indices;
  22686. vertexData.positions = positions;
  22687. return vertexData;
  22688. };
  22689. VertexData.CreateGround = function (width, height, subdivisions) {
  22690. var indices = [];
  22691. var positions = [];
  22692. var normals = [];
  22693. var uvs = [];
  22694. var row, col;
  22695. width = width || 1;
  22696. height = height || 1;
  22697. subdivisions = subdivisions || 1;
  22698. for (row = 0; row <= subdivisions; row++) {
  22699. for (col = 0; col <= subdivisions; col++) {
  22700. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22701. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22702. positions.push(position.x, position.y, position.z);
  22703. normals.push(normal.x, normal.y, normal.z);
  22704. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22705. }
  22706. }
  22707. for (row = 0; row < subdivisions; row++) {
  22708. for (col = 0; col < subdivisions; col++) {
  22709. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22710. indices.push(col + 1 + row * (subdivisions + 1));
  22711. indices.push(col + row * (subdivisions + 1));
  22712. indices.push(col + (row + 1) * (subdivisions + 1));
  22713. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22714. indices.push(col + row * (subdivisions + 1));
  22715. }
  22716. }
  22717. // Result
  22718. var vertexData = new VertexData();
  22719. vertexData.indices = indices;
  22720. vertexData.positions = positions;
  22721. vertexData.normals = normals;
  22722. vertexData.uvs = uvs;
  22723. return vertexData;
  22724. };
  22725. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22726. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22727. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22728. var indices = [];
  22729. var positions = [];
  22730. var normals = [];
  22731. var uvs = [];
  22732. var row, col, tileRow, tileCol;
  22733. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22734. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22735. precision.w = (precision.w < 1) ? 1 : precision.w;
  22736. precision.h = (precision.h < 1) ? 1 : precision.h;
  22737. var tileSize = {
  22738. 'w': (xmax - xmin) / subdivisions.w,
  22739. 'h': (zmax - zmin) / subdivisions.h
  22740. };
  22741. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22742. // Indices
  22743. var base = positions.length / 3;
  22744. var rowLength = precision.w + 1;
  22745. for (row = 0; row < precision.h; row++) {
  22746. for (col = 0; col < precision.w; col++) {
  22747. var square = [
  22748. base + col + row * rowLength,
  22749. base + (col + 1) + row * rowLength,
  22750. base + (col + 1) + (row + 1) * rowLength,
  22751. base + col + (row + 1) * rowLength
  22752. ];
  22753. indices.push(square[1]);
  22754. indices.push(square[2]);
  22755. indices.push(square[3]);
  22756. indices.push(square[0]);
  22757. indices.push(square[1]);
  22758. indices.push(square[3]);
  22759. }
  22760. }
  22761. // Position, normals and uvs
  22762. var position = BABYLON.Vector3.Zero();
  22763. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22764. for (row = 0; row <= precision.h; row++) {
  22765. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22766. for (col = 0; col <= precision.w; col++) {
  22767. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22768. position.y = 0;
  22769. positions.push(position.x, position.y, position.z);
  22770. normals.push(normal.x, normal.y, normal.z);
  22771. uvs.push(col / precision.w, row / precision.h);
  22772. }
  22773. }
  22774. }
  22775. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22776. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22777. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22778. }
  22779. }
  22780. // Result
  22781. var vertexData = new VertexData();
  22782. vertexData.indices = indices;
  22783. vertexData.positions = positions;
  22784. vertexData.normals = normals;
  22785. vertexData.uvs = uvs;
  22786. return vertexData;
  22787. };
  22788. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22789. var indices = [];
  22790. var positions = [];
  22791. var normals = [];
  22792. var uvs = [];
  22793. var row, col;
  22794. for (row = 0; row <= subdivisions; row++) {
  22795. for (col = 0; col <= subdivisions; col++) {
  22796. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22797. // Compute height
  22798. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22799. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22800. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22801. var r = buffer[pos] / 255.0;
  22802. var g = buffer[pos + 1] / 255.0;
  22803. var b = buffer[pos + 2] / 255.0;
  22804. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22805. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22806. // Add vertex
  22807. positions.push(position.x, position.y, position.z);
  22808. normals.push(0, 0, 0);
  22809. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22810. }
  22811. }
  22812. for (row = 0; row < subdivisions; row++) {
  22813. for (col = 0; col < subdivisions; col++) {
  22814. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22815. indices.push(col + 1 + row * (subdivisions + 1));
  22816. indices.push(col + row * (subdivisions + 1));
  22817. indices.push(col + (row + 1) * (subdivisions + 1));
  22818. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22819. indices.push(col + row * (subdivisions + 1));
  22820. }
  22821. }
  22822. // Normals
  22823. VertexData.ComputeNormals(positions, indices, normals);
  22824. // Result
  22825. var vertexData = new VertexData();
  22826. vertexData.indices = indices;
  22827. vertexData.positions = positions;
  22828. vertexData.normals = normals;
  22829. vertexData.uvs = uvs;
  22830. return vertexData;
  22831. };
  22832. VertexData.CreatePlane = function (size, sideOrientation) {
  22833. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22834. var indices = [];
  22835. var positions = [];
  22836. var normals = [];
  22837. var uvs = [];
  22838. size = size || 1;
  22839. // Vertices
  22840. var halfSize = size / 2.0;
  22841. positions.push(-halfSize, -halfSize, 0);
  22842. normals.push(0, 0, -1.0);
  22843. uvs.push(0.0, 0.0);
  22844. positions.push(halfSize, -halfSize, 0);
  22845. normals.push(0, 0, -1.0);
  22846. uvs.push(1.0, 0.0);
  22847. positions.push(halfSize, halfSize, 0);
  22848. normals.push(0, 0, -1.0);
  22849. uvs.push(1.0, 1.0);
  22850. positions.push(-halfSize, halfSize, 0);
  22851. normals.push(0, 0, -1.0);
  22852. uvs.push(0.0, 1.0);
  22853. // Indices
  22854. indices.push(0);
  22855. indices.push(1);
  22856. indices.push(2);
  22857. indices.push(0);
  22858. indices.push(2);
  22859. indices.push(3);
  22860. // Sides
  22861. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22862. // Result
  22863. var vertexData = new VertexData();
  22864. vertexData.indices = indices;
  22865. vertexData.positions = positions;
  22866. vertexData.normals = normals;
  22867. vertexData.uvs = uvs;
  22868. return vertexData;
  22869. };
  22870. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22871. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22872. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22873. var indices = [];
  22874. var positions = [];
  22875. var normals = [];
  22876. var uvs = [];
  22877. radius = radius || 2;
  22878. tube = tube || 0.5;
  22879. radialSegments = radialSegments || 32;
  22880. tubularSegments = tubularSegments || 32;
  22881. p = p || 2;
  22882. q = q || 3;
  22883. // Helper
  22884. var getPos = function (angle) {
  22885. var cu = Math.cos(angle);
  22886. var su = Math.sin(angle);
  22887. var quOverP = q / p * angle;
  22888. var cs = Math.cos(quOverP);
  22889. var tx = radius * (2 + cs) * 0.5 * cu;
  22890. var ty = radius * (2 + cs) * su * 0.5;
  22891. var tz = radius * Math.sin(quOverP) * 0.5;
  22892. return new BABYLON.Vector3(tx, ty, tz);
  22893. };
  22894. for (var i = 0; i <= radialSegments; i++) {
  22895. var modI = i % radialSegments;
  22896. var u = modI / radialSegments * 2 * p * Math.PI;
  22897. var p1 = getPos(u);
  22898. var p2 = getPos(u + 0.01);
  22899. var tang = p2.subtract(p1);
  22900. var n = p2.add(p1);
  22901. var bitan = BABYLON.Vector3.Cross(tang, n);
  22902. n = BABYLON.Vector3.Cross(bitan, tang);
  22903. bitan.normalize();
  22904. n.normalize();
  22905. for (var j = 0; j < tubularSegments; j++) {
  22906. var modJ = j % tubularSegments;
  22907. var v = modJ / tubularSegments * 2 * Math.PI;
  22908. var cx = -tube * Math.cos(v);
  22909. var cy = tube * Math.sin(v);
  22910. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22911. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22912. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22913. uvs.push(i / radialSegments);
  22914. uvs.push(j / tubularSegments);
  22915. }
  22916. }
  22917. for (i = 0; i < radialSegments; i++) {
  22918. for (j = 0; j < tubularSegments; j++) {
  22919. var jNext = (j + 1) % tubularSegments;
  22920. var a = i * tubularSegments + j;
  22921. var b = (i + 1) * tubularSegments + j;
  22922. var c = (i + 1) * tubularSegments + jNext;
  22923. var d = i * tubularSegments + jNext;
  22924. indices.push(d);
  22925. indices.push(b);
  22926. indices.push(a);
  22927. indices.push(d);
  22928. indices.push(c);
  22929. indices.push(b);
  22930. }
  22931. }
  22932. // Normals
  22933. VertexData.ComputeNormals(positions, indices, normals);
  22934. // Sides
  22935. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22936. // Result
  22937. var vertexData = new VertexData();
  22938. vertexData.indices = indices;
  22939. vertexData.positions = positions;
  22940. vertexData.normals = normals;
  22941. vertexData.uvs = uvs;
  22942. return vertexData;
  22943. };
  22944. // Tools
  22945. /**
  22946. * @param {any} - positions (number[] or Float32Array)
  22947. * @param {any} - indices (number[] or Uint16Array)
  22948. * @param {any} - normals (number[] or Float32Array)
  22949. */
  22950. VertexData.ComputeNormals = function (positions, indices, normals) {
  22951. var positionVectors = [];
  22952. var facesOfVertices = [];
  22953. var index;
  22954. for (index = 0; index < positions.length; index += 3) {
  22955. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22956. positionVectors.push(vector3);
  22957. facesOfVertices.push([]);
  22958. }
  22959. // Compute normals
  22960. var facesNormals = [];
  22961. for (index = 0; index < indices.length / 3; index++) {
  22962. var i1 = indices[index * 3];
  22963. var i2 = indices[index * 3 + 1];
  22964. var i3 = indices[index * 3 + 2];
  22965. var p1 = positionVectors[i1];
  22966. var p2 = positionVectors[i2];
  22967. var p3 = positionVectors[i3];
  22968. var p1p2 = p1.subtract(p2);
  22969. var p3p2 = p3.subtract(p2);
  22970. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22971. facesOfVertices[i1].push(index);
  22972. facesOfVertices[i2].push(index);
  22973. facesOfVertices[i3].push(index);
  22974. }
  22975. for (index = 0; index < positionVectors.length; index++) {
  22976. var faces = facesOfVertices[index];
  22977. var normal = BABYLON.Vector3.Zero();
  22978. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22979. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22980. }
  22981. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22982. normals[index * 3] = normal.x;
  22983. normals[index * 3 + 1] = normal.y;
  22984. normals[index * 3 + 2] = normal.z;
  22985. }
  22986. };
  22987. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22988. var li = indices.length;
  22989. var ln = normals.length;
  22990. var i;
  22991. var n;
  22992. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22993. switch (sideOrientation) {
  22994. case BABYLON.Mesh.FRONTSIDE:
  22995. break;
  22996. case BABYLON.Mesh.BACKSIDE:
  22997. var tmp;
  22998. for (i = 0; i < li; i += 3) {
  22999. tmp = indices[i];
  23000. indices[i] = indices[i + 2];
  23001. indices[i + 2] = tmp;
  23002. }
  23003. for (n = 0; n < ln; n++) {
  23004. normals[n] = -normals[n];
  23005. }
  23006. break;
  23007. case BABYLON.Mesh.DOUBLESIDE:
  23008. // positions
  23009. var lp = positions.length;
  23010. var l = lp / 3;
  23011. for (var p = 0; p < lp; p++) {
  23012. positions[lp + p] = positions[p];
  23013. }
  23014. for (i = 0; i < li; i += 3) {
  23015. indices[i + li] = indices[i + 2] + l;
  23016. indices[i + 1 + li] = indices[i + 1] + l;
  23017. indices[i + 2 + li] = indices[i] + l;
  23018. }
  23019. for (n = 0; n < ln; n++) {
  23020. normals[ln + n] = -normals[n];
  23021. }
  23022. // uvs
  23023. var lu = uvs.length;
  23024. for (var u = 0; u < lu; u++) {
  23025. uvs[u + lu] = uvs[u];
  23026. }
  23027. break;
  23028. }
  23029. };
  23030. return VertexData;
  23031. })();
  23032. BABYLON.VertexData = VertexData;
  23033. })(BABYLON || (BABYLON = {}));
  23034. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  23035. var BABYLON;
  23036. (function (BABYLON) {
  23037. var buildCamera = function (that, name) {
  23038. that._leftCamera.isIntermediate = true;
  23039. that.subCameras.push(that._leftCamera);
  23040. that.subCameras.push(that._rightCamera);
  23041. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  23042. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  23043. that._anaglyphPostProcess.onApply = function (effect) {
  23044. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  23045. };
  23046. that._update();
  23047. };
  23048. var AnaglyphArcRotateCamera = (function (_super) {
  23049. __extends(AnaglyphArcRotateCamera, _super);
  23050. // ANY
  23051. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  23052. _super.call(this, name, alpha, beta, radius, target, scene);
  23053. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23054. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  23055. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  23056. buildCamera(this, name);
  23057. }
  23058. AnaglyphArcRotateCamera.prototype._update = function () {
  23059. this._updateCamera(this._leftCamera);
  23060. this._updateCamera(this._rightCamera);
  23061. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  23062. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  23063. _super.prototype._update.call(this);
  23064. };
  23065. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  23066. camera.beta = this.beta;
  23067. camera.radius = this.radius;
  23068. camera.minZ = this.minZ;
  23069. camera.maxZ = this.maxZ;
  23070. camera.fov = this.fov;
  23071. camera.target = this.target;
  23072. };
  23073. return AnaglyphArcRotateCamera;
  23074. })(BABYLON.ArcRotateCamera);
  23075. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  23076. var AnaglyphFreeCamera = (function (_super) {
  23077. __extends(AnaglyphFreeCamera, _super);
  23078. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  23079. _super.call(this, name, position, scene);
  23080. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23081. this._transformMatrix = new BABYLON.Matrix();
  23082. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  23083. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  23084. buildCamera(this, name);
  23085. }
  23086. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  23087. var target = this.getTarget();
  23088. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  23089. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  23090. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  23091. };
  23092. AnaglyphFreeCamera.prototype._update = function () {
  23093. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  23094. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  23095. this._updateCamera(this._leftCamera);
  23096. this._updateCamera(this._rightCamera);
  23097. _super.prototype._update.call(this);
  23098. };
  23099. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  23100. camera.minZ = this.minZ;
  23101. camera.maxZ = this.maxZ;
  23102. camera.fov = this.fov;
  23103. camera.viewport = this.viewport;
  23104. camera.setTarget(this.getTarget());
  23105. };
  23106. return AnaglyphFreeCamera;
  23107. })(BABYLON.FreeCamera);
  23108. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  23109. })(BABYLON || (BABYLON = {}));
  23110. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  23111. var BABYLON;
  23112. (function (BABYLON) {
  23113. var AnaglyphPostProcess = (function (_super) {
  23114. __extends(AnaglyphPostProcess, _super);
  23115. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23116. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  23117. }
  23118. return AnaglyphPostProcess;
  23119. })(BABYLON.PostProcess);
  23120. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  23121. })(BABYLON || (BABYLON = {}));
  23122. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  23123. (function (BABYLON) {
  23124. var Tags = (function () {
  23125. function Tags() {
  23126. }
  23127. Tags.EnableFor = function (obj) {
  23128. obj._tags = obj._tags || {};
  23129. obj.hasTags = function () {
  23130. return Tags.HasTags(obj);
  23131. };
  23132. obj.addTags = function (tagsString) {
  23133. return Tags.AddTagsTo(obj, tagsString);
  23134. };
  23135. obj.removeTags = function (tagsString) {
  23136. return Tags.RemoveTagsFrom(obj, tagsString);
  23137. };
  23138. obj.matchesTagsQuery = function (tagsQuery) {
  23139. return Tags.MatchesQuery(obj, tagsQuery);
  23140. };
  23141. };
  23142. Tags.DisableFor = function (obj) {
  23143. delete obj._tags;
  23144. delete obj.hasTags;
  23145. delete obj.addTags;
  23146. delete obj.removeTags;
  23147. delete obj.matchesTagsQuery;
  23148. };
  23149. Tags.HasTags = function (obj) {
  23150. if (!obj._tags) {
  23151. return false;
  23152. }
  23153. return !BABYLON.Tools.IsEmpty(obj._tags);
  23154. };
  23155. Tags.GetTags = function (obj) {
  23156. if (!obj._tags) {
  23157. return null;
  23158. }
  23159. return obj._tags;
  23160. };
  23161. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23162. // a tag cannot start with '||', '&&', and '!'
  23163. // it cannot contain whitespaces
  23164. Tags.AddTagsTo = function (obj, tagsString) {
  23165. if (!tagsString) {
  23166. return;
  23167. }
  23168. var tags = tagsString.split(" ");
  23169. for (var t in tags) {
  23170. Tags._AddTagTo(obj, tags[t]);
  23171. }
  23172. };
  23173. Tags._AddTagTo = function (obj, tag) {
  23174. tag = tag.trim();
  23175. if (tag === "" || tag === "true" || tag === "false") {
  23176. return;
  23177. }
  23178. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  23179. return;
  23180. }
  23181. Tags.EnableFor(obj);
  23182. obj._tags[tag] = true;
  23183. };
  23184. Tags.RemoveTagsFrom = function (obj, tagsString) {
  23185. if (!Tags.HasTags(obj)) {
  23186. return;
  23187. }
  23188. var tags = tagsString.split(" ");
  23189. for (var t in tags) {
  23190. Tags._RemoveTagFrom(obj, tags[t]);
  23191. }
  23192. };
  23193. Tags._RemoveTagFrom = function (obj, tag) {
  23194. delete obj._tags[tag];
  23195. };
  23196. Tags.MatchesQuery = function (obj, tagsQuery) {
  23197. if (tagsQuery === undefined) {
  23198. return true;
  23199. }
  23200. if (tagsQuery === "") {
  23201. return Tags.HasTags(obj);
  23202. }
  23203. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  23204. };
  23205. return Tags;
  23206. })();
  23207. BABYLON.Tags = Tags;
  23208. })(BABYLON || (BABYLON = {}));
  23209. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  23210. (function (BABYLON) {
  23211. var Internals;
  23212. (function (Internals) {
  23213. var AndOrNotEvaluator = (function () {
  23214. function AndOrNotEvaluator() {
  23215. }
  23216. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  23217. if (!query.match(/\([^\(\)]*\)/g)) {
  23218. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  23219. }
  23220. else {
  23221. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  23222. // remove parenthesis
  23223. r = r.slice(1, r.length - 1);
  23224. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  23225. });
  23226. }
  23227. if (query === "true") {
  23228. return true;
  23229. }
  23230. if (query === "false") {
  23231. return false;
  23232. }
  23233. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  23234. };
  23235. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  23236. evaluateCallback = evaluateCallback || (function (r) {
  23237. return r === "true" ? true : false;
  23238. });
  23239. var result;
  23240. var or = parenthesisContent.split("||");
  23241. for (var i in or) {
  23242. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  23243. var and = ori.split("&&");
  23244. if (and.length > 1) {
  23245. for (var j = 0; j < and.length; ++j) {
  23246. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  23247. if (andj !== "true" && andj !== "false") {
  23248. if (andj[0] === "!") {
  23249. result = !evaluateCallback(andj.substring(1));
  23250. }
  23251. else {
  23252. result = evaluateCallback(andj);
  23253. }
  23254. }
  23255. else {
  23256. result = andj === "true" ? true : false;
  23257. }
  23258. if (!result) {
  23259. ori = "false";
  23260. break;
  23261. }
  23262. }
  23263. }
  23264. if (result || ori === "true") {
  23265. result = true;
  23266. break;
  23267. }
  23268. // result equals false (or undefined)
  23269. if (ori !== "true" && ori !== "false") {
  23270. if (ori[0] === "!") {
  23271. result = !evaluateCallback(ori.substring(1));
  23272. }
  23273. else {
  23274. result = evaluateCallback(ori);
  23275. }
  23276. }
  23277. else {
  23278. result = ori === "true" ? true : false;
  23279. }
  23280. }
  23281. // the whole parenthesis scope is replaced by 'true' or 'false'
  23282. return result ? "true" : "false";
  23283. };
  23284. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  23285. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  23286. // remove whitespaces
  23287. r = r.replace(/[\s]/g, function () { return ""; });
  23288. return r.length % 2 ? "!" : "";
  23289. });
  23290. booleanString = booleanString.trim();
  23291. if (booleanString === "!true") {
  23292. booleanString = "false";
  23293. }
  23294. else if (booleanString === "!false") {
  23295. booleanString = "true";
  23296. }
  23297. return booleanString;
  23298. };
  23299. return AndOrNotEvaluator;
  23300. })();
  23301. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  23302. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23303. })(BABYLON || (BABYLON = {}));
  23304. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  23305. (function (BABYLON) {
  23306. var PostProcessRenderPass = (function () {
  23307. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  23308. this._enabled = true;
  23309. this._refCount = 0;
  23310. this._name = name;
  23311. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  23312. this.setRenderList(renderList);
  23313. this._renderTexture.onBeforeRender = beforeRender;
  23314. this._renderTexture.onAfterRender = afterRender;
  23315. this._scene = scene;
  23316. this._renderList = renderList;
  23317. }
  23318. // private
  23319. PostProcessRenderPass.prototype._incRefCount = function () {
  23320. if (this._refCount === 0) {
  23321. this._scene.customRenderTargets.push(this._renderTexture);
  23322. }
  23323. return ++this._refCount;
  23324. };
  23325. PostProcessRenderPass.prototype._decRefCount = function () {
  23326. this._refCount--;
  23327. if (this._refCount <= 0) {
  23328. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23329. }
  23330. return this._refCount;
  23331. };
  23332. PostProcessRenderPass.prototype._update = function () {
  23333. this.setRenderList(this._renderList);
  23334. };
  23335. // public
  23336. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23337. this._renderTexture.renderList = renderList;
  23338. };
  23339. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23340. return this._renderTexture;
  23341. };
  23342. return PostProcessRenderPass;
  23343. })();
  23344. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23345. })(BABYLON || (BABYLON = {}));
  23346. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23347. (function (BABYLON) {
  23348. var PostProcessRenderEffect = (function () {
  23349. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23350. this._engine = engine;
  23351. this._name = name;
  23352. this._singleInstance = singleInstance || true;
  23353. this._getPostProcess = getPostProcess;
  23354. this._cameras = [];
  23355. this._indicesForCamera = [];
  23356. this._postProcesses = {};
  23357. this._renderPasses = {};
  23358. this._renderEffectAsPasses = {};
  23359. }
  23360. PostProcessRenderEffect.prototype._update = function () {
  23361. for (var renderPassName in this._renderPasses) {
  23362. this._renderPasses[renderPassName]._update();
  23363. }
  23364. };
  23365. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23366. this._renderPasses[renderPass._name] = renderPass;
  23367. this._linkParameters();
  23368. };
  23369. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23370. delete this._renderPasses[renderPass._name];
  23371. this._linkParameters();
  23372. };
  23373. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23374. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23375. this._linkParameters();
  23376. };
  23377. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23378. for (var renderPassName in this._renderPasses) {
  23379. if (renderPassName === passName) {
  23380. return this._renderPasses[passName];
  23381. }
  23382. }
  23383. };
  23384. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23385. this._renderPasses = {};
  23386. this._linkParameters();
  23387. };
  23388. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23389. var cameraKey;
  23390. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23391. for (var i = 0; i < _cam.length; i++) {
  23392. var camera = _cam[i];
  23393. var cameraName = camera.name;
  23394. if (this._singleInstance) {
  23395. cameraKey = 0;
  23396. }
  23397. else {
  23398. cameraKey = cameraName;
  23399. }
  23400. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23401. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23402. if (!this._indicesForCamera[cameraName]) {
  23403. this._indicesForCamera[cameraName] = [];
  23404. }
  23405. this._indicesForCamera[cameraName].push(index);
  23406. if (this._cameras.indexOf(camera) === -1) {
  23407. this._cameras[cameraName] = camera;
  23408. }
  23409. for (var passName in this._renderPasses) {
  23410. this._renderPasses[passName]._incRefCount();
  23411. }
  23412. }
  23413. this._linkParameters();
  23414. };
  23415. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23416. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23417. for (var i = 0; i < _cam.length; i++) {
  23418. var camera = _cam[i];
  23419. var cameraName = camera.name;
  23420. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23421. var index = this._cameras.indexOf(cameraName);
  23422. this._indicesForCamera.splice(index, 1);
  23423. this._cameras.splice(index, 1);
  23424. for (var passName in this._renderPasses) {
  23425. this._renderPasses[passName]._decRefCount();
  23426. }
  23427. }
  23428. };
  23429. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23430. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23431. for (var i = 0; i < _cam.length; i++) {
  23432. var camera = _cam[i];
  23433. var cameraName = camera.name;
  23434. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23435. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23436. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23437. }
  23438. }
  23439. for (var passName in this._renderPasses) {
  23440. this._renderPasses[passName]._incRefCount();
  23441. }
  23442. }
  23443. };
  23444. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23445. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23446. for (var i = 0; i < _cam.length; i++) {
  23447. var camera = _cam[i];
  23448. var cameraName = camera.Name;
  23449. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23450. for (var passName in this._renderPasses) {
  23451. this._renderPasses[passName]._decRefCount();
  23452. }
  23453. }
  23454. };
  23455. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23456. if (this._singleInstance) {
  23457. return this._postProcesses[0];
  23458. }
  23459. else {
  23460. return this._postProcesses[camera.name];
  23461. }
  23462. };
  23463. PostProcessRenderEffect.prototype._linkParameters = function () {
  23464. var _this = this;
  23465. for (var index in this._postProcesses) {
  23466. if (this.applyParameters) {
  23467. this.applyParameters(this._postProcesses[index]);
  23468. }
  23469. this._postProcesses[index].onBeforeRender = function (effect) {
  23470. _this._linkTextures(effect);
  23471. };
  23472. }
  23473. };
  23474. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23475. for (var renderPassName in this._renderPasses) {
  23476. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23477. }
  23478. for (var renderEffectName in this._renderEffectAsPasses) {
  23479. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23480. }
  23481. };
  23482. return PostProcessRenderEffect;
  23483. })();
  23484. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23485. })(BABYLON || (BABYLON = {}));
  23486. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23487. (function (BABYLON) {
  23488. var PostProcessRenderPipeline = (function () {
  23489. function PostProcessRenderPipeline(engine, name) {
  23490. this._engine = engine;
  23491. this._name = name;
  23492. this._renderEffects = {};
  23493. this._renderEffectsForIsolatedPass = {};
  23494. this._cameras = [];
  23495. }
  23496. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23497. this._renderEffects[renderEffect._name] = renderEffect;
  23498. };
  23499. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23500. var renderEffects = this._renderEffects[renderEffectName];
  23501. if (!renderEffects) {
  23502. return;
  23503. }
  23504. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23505. };
  23506. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23507. var renderEffects = this._renderEffects[renderEffectName];
  23508. if (!renderEffects) {
  23509. return;
  23510. }
  23511. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23512. };
  23513. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23514. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23515. var indicesToDelete = [];
  23516. for (var i = 0; i < _cam.length; i++) {
  23517. var camera = _cam[i];
  23518. var cameraName = camera.name;
  23519. if (this._cameras.indexOf(camera) === -1) {
  23520. this._cameras[cameraName] = camera;
  23521. }
  23522. else if (unique) {
  23523. indicesToDelete.push(i);
  23524. }
  23525. }
  23526. for (var i = 0; i < indicesToDelete.length; i++) {
  23527. cameras.splice(indicesToDelete[i], 1);
  23528. }
  23529. for (var renderEffectName in this._renderEffects) {
  23530. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23531. }
  23532. };
  23533. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23534. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23535. for (var renderEffectName in this._renderEffects) {
  23536. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23537. }
  23538. for (var i = 0; i < _cam.length; i++) {
  23539. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23540. }
  23541. };
  23542. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23543. var _this = this;
  23544. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23545. var pass = null;
  23546. for (var renderEffectName in this._renderEffects) {
  23547. pass = this._renderEffects[renderEffectName].getPass(passName);
  23548. if (pass != null) {
  23549. break;
  23550. }
  23551. }
  23552. if (pass === null) {
  23553. return;
  23554. }
  23555. for (var renderEffectName in this._renderEffects) {
  23556. this._renderEffects[renderEffectName]._disable(_cam);
  23557. }
  23558. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23559. for (var i = 0; i < _cam.length; i++) {
  23560. var camera = _cam[i];
  23561. var cameraName = camera.name;
  23562. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23563. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23564. });
  23565. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23566. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23567. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23568. }
  23569. };
  23570. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23571. var _this = this;
  23572. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23573. for (var i = 0; i < _cam.length; i++) {
  23574. var camera = _cam[i];
  23575. var cameraName = camera.name;
  23576. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23577. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23578. });
  23579. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23580. }
  23581. for (var renderEffectName in this._renderEffects) {
  23582. this._renderEffects[renderEffectName]._enable(_cam);
  23583. }
  23584. };
  23585. PostProcessRenderPipeline.prototype._update = function () {
  23586. for (var renderEffectName in this._renderEffects) {
  23587. this._renderEffects[renderEffectName]._update();
  23588. }
  23589. for (var i = 0; i < this._cameras.length; i++) {
  23590. var cameraName = this._cameras[i].name;
  23591. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23592. this._renderEffectsForIsolatedPass[cameraName]._update();
  23593. }
  23594. }
  23595. };
  23596. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23597. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23598. return PostProcessRenderPipeline;
  23599. })();
  23600. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23601. })(BABYLON || (BABYLON = {}));
  23602. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23603. (function (BABYLON) {
  23604. var PostProcessRenderPipelineManager = (function () {
  23605. function PostProcessRenderPipelineManager() {
  23606. this._renderPipelines = {};
  23607. }
  23608. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23609. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23610. };
  23611. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23612. var renderPipeline = this._renderPipelines[renderPipelineName];
  23613. if (!renderPipeline) {
  23614. return;
  23615. }
  23616. renderPipeline._attachCameras(cameras, unique);
  23617. };
  23618. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23619. var renderPipeline = this._renderPipelines[renderPipelineName];
  23620. if (!renderPipeline) {
  23621. return;
  23622. }
  23623. renderPipeline._detachCameras(cameras);
  23624. };
  23625. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23626. var renderPipeline = this._renderPipelines[renderPipelineName];
  23627. if (!renderPipeline) {
  23628. return;
  23629. }
  23630. renderPipeline._enableEffect(renderEffectName, cameras);
  23631. };
  23632. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23633. var renderPipeline = this._renderPipelines[renderPipelineName];
  23634. if (!renderPipeline) {
  23635. return;
  23636. }
  23637. renderPipeline._disableEffect(renderEffectName, cameras);
  23638. };
  23639. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23640. var renderPipeline = this._renderPipelines[renderPipelineName];
  23641. if (!renderPipeline) {
  23642. return;
  23643. }
  23644. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23645. };
  23646. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23647. var renderPipeline = this._renderPipelines[renderPipelineName];
  23648. if (!renderPipeline) {
  23649. return;
  23650. }
  23651. renderPipeline._disableDisplayOnlyPass(cameras);
  23652. };
  23653. PostProcessRenderPipelineManager.prototype.update = function () {
  23654. for (var renderPipelineName in this._renderPipelines) {
  23655. this._renderPipelines[renderPipelineName]._update();
  23656. }
  23657. };
  23658. return PostProcessRenderPipelineManager;
  23659. })();
  23660. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23661. })(BABYLON || (BABYLON = {}));
  23662. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23663. var BABYLON;
  23664. (function (BABYLON) {
  23665. var DisplayPassPostProcess = (function (_super) {
  23666. __extends(DisplayPassPostProcess, _super);
  23667. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23668. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23669. }
  23670. return DisplayPassPostProcess;
  23671. })(BABYLON.PostProcess);
  23672. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23673. })(BABYLON || (BABYLON = {}));
  23674. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23675. (function (BABYLON) {
  23676. var BoundingBoxRenderer = (function () {
  23677. function BoundingBoxRenderer(scene) {
  23678. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23679. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23680. this.showBackLines = true;
  23681. this.renderList = new BABYLON.SmartArray(32);
  23682. this._scene = scene;
  23683. }
  23684. BoundingBoxRenderer.prototype._prepareRessources = function () {
  23685. if (this._colorShader) {
  23686. return;
  23687. }
  23688. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  23689. attributes: ["position"],
  23690. uniforms: ["worldViewProjection", "color"]
  23691. });
  23692. var engine = this._scene.getEngine();
  23693. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23694. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23695. 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]);
  23696. };
  23697. BoundingBoxRenderer.prototype.reset = function () {
  23698. this.renderList.reset();
  23699. };
  23700. BoundingBoxRenderer.prototype.render = function () {
  23701. if (this.renderList.length === 0) {
  23702. return;
  23703. }
  23704. this._prepareRessources();
  23705. if (!this._colorShader.isReady()) {
  23706. return;
  23707. }
  23708. var engine = this._scene.getEngine();
  23709. engine.setDepthWrite(false);
  23710. this._colorShader._preBind();
  23711. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23712. var boundingBox = this.renderList.data[boundingBoxIndex];
  23713. var min = boundingBox.minimum;
  23714. var max = boundingBox.maximum;
  23715. var diff = max.subtract(min);
  23716. var median = min.add(diff.scale(0.5));
  23717. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23718. // VBOs
  23719. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23720. if (this.showBackLines) {
  23721. // Back
  23722. engine.setDepthFunctionToGreaterOrEqual();
  23723. this._scene.resetCachedMaterial();
  23724. this._colorShader.setColor4("color", this.backColor.toColor4());
  23725. this._colorShader.bind(worldMatrix);
  23726. // Draw order
  23727. engine.draw(false, 0, 24);
  23728. }
  23729. // Front
  23730. engine.setDepthFunctionToLess();
  23731. this._scene.resetCachedMaterial();
  23732. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23733. this._colorShader.bind(worldMatrix);
  23734. // Draw order
  23735. engine.draw(false, 0, 24);
  23736. }
  23737. this._colorShader.unbind();
  23738. engine.setDepthFunctionToLessOrEqual();
  23739. engine.setDepthWrite(true);
  23740. };
  23741. BoundingBoxRenderer.prototype.dispose = function () {
  23742. if (!this._colorShader) {
  23743. return;
  23744. }
  23745. this._colorShader.dispose();
  23746. this._vb.dispose();
  23747. this._scene.getEngine()._releaseBuffer(this._ib);
  23748. };
  23749. return BoundingBoxRenderer;
  23750. })();
  23751. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23752. })(BABYLON || (BABYLON = {}));
  23753. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23754. (function (BABYLON) {
  23755. var Internals;
  23756. (function (Internals) {
  23757. /*
  23758. * Based on jsTGALoader - Javascript loader for TGA file
  23759. * By Vincent Thibault
  23760. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23761. */
  23762. var TGATools = (function () {
  23763. function TGATools() {
  23764. }
  23765. TGATools.GetTGAHeader = function (data) {
  23766. var offset = 0;
  23767. var header = {
  23768. id_length: data[offset++],
  23769. colormap_type: data[offset++],
  23770. image_type: data[offset++],
  23771. colormap_index: data[offset++] | data[offset++] << 8,
  23772. colormap_length: data[offset++] | data[offset++] << 8,
  23773. colormap_size: data[offset++],
  23774. origin: [
  23775. data[offset++] | data[offset++] << 8,
  23776. data[offset++] | data[offset++] << 8
  23777. ],
  23778. width: data[offset++] | data[offset++] << 8,
  23779. height: data[offset++] | data[offset++] << 8,
  23780. pixel_size: data[offset++],
  23781. flags: data[offset++]
  23782. };
  23783. return header;
  23784. };
  23785. TGATools.UploadContent = function (gl, data) {
  23786. // Not enough data to contain header ?
  23787. if (data.length < 19) {
  23788. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23789. return;
  23790. }
  23791. // Read Header
  23792. var offset = 18;
  23793. var header = TGATools.GetTGAHeader(data);
  23794. // Assume it's a valid Targa file.
  23795. if (header.id_length + offset > data.length) {
  23796. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23797. return;
  23798. }
  23799. // Skip not needed data
  23800. offset += header.id_length;
  23801. var use_rle = false;
  23802. var use_pal = false;
  23803. var use_rgb = false;
  23804. var use_grey = false;
  23805. switch (header.image_type) {
  23806. case TGATools._TYPE_RLE_INDEXED:
  23807. use_rle = true;
  23808. case TGATools._TYPE_INDEXED:
  23809. use_pal = true;
  23810. break;
  23811. case TGATools._TYPE_RLE_RGB:
  23812. use_rle = true;
  23813. case TGATools._TYPE_RGB:
  23814. use_rgb = true;
  23815. break;
  23816. case TGATools._TYPE_RLE_GREY:
  23817. use_rle = true;
  23818. case TGATools._TYPE_GREY:
  23819. use_grey = true;
  23820. break;
  23821. }
  23822. var pixel_data;
  23823. var numAlphaBits = header.flags & 0xf;
  23824. var pixel_size = header.pixel_size >> 3;
  23825. var pixel_total = header.width * header.height * pixel_size;
  23826. // Read palettes
  23827. var palettes;
  23828. if (use_pal) {
  23829. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23830. }
  23831. // Read LRE
  23832. if (use_rle) {
  23833. pixel_data = new Uint8Array(pixel_total);
  23834. var c, count, i;
  23835. var localOffset = 0;
  23836. var pixels = new Uint8Array(pixel_size);
  23837. while (offset < pixel_total && localOffset < pixel_total) {
  23838. c = data[offset++];
  23839. count = (c & 0x7f) + 1;
  23840. // RLE pixels
  23841. if (c & 0x80) {
  23842. for (i = 0; i < pixel_size; ++i) {
  23843. pixels[i] = data[offset++];
  23844. }
  23845. for (i = 0; i < count; ++i) {
  23846. pixel_data.set(pixels, localOffset + i * pixel_size);
  23847. }
  23848. localOffset += pixel_size * count;
  23849. }
  23850. else {
  23851. count *= pixel_size;
  23852. for (i = 0; i < count; ++i) {
  23853. pixel_data[localOffset + i] = data[offset++];
  23854. }
  23855. localOffset += count;
  23856. }
  23857. }
  23858. }
  23859. else {
  23860. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23861. }
  23862. // Load to texture
  23863. var x_start, y_start, x_step, y_step, y_end, x_end;
  23864. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23865. default:
  23866. case TGATools._ORIGIN_UL:
  23867. x_start = 0;
  23868. x_step = 1;
  23869. x_end = header.width;
  23870. y_start = 0;
  23871. y_step = 1;
  23872. y_end = header.height;
  23873. break;
  23874. case TGATools._ORIGIN_BL:
  23875. x_start = 0;
  23876. x_step = 1;
  23877. x_end = header.width;
  23878. y_start = header.height - 1;
  23879. y_step = -1;
  23880. y_end = -1;
  23881. break;
  23882. case TGATools._ORIGIN_UR:
  23883. x_start = header.width - 1;
  23884. x_step = -1;
  23885. x_end = -1;
  23886. y_start = 0;
  23887. y_step = 1;
  23888. y_end = header.height;
  23889. break;
  23890. case TGATools._ORIGIN_BR:
  23891. x_start = header.width - 1;
  23892. x_step = -1;
  23893. x_end = -1;
  23894. y_start = header.height - 1;
  23895. y_step = -1;
  23896. y_end = -1;
  23897. break;
  23898. }
  23899. // Load the specify method
  23900. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23901. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23902. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23903. };
  23904. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23905. var image = pixel_data, colormap = palettes;
  23906. var width = header.width, height = header.height;
  23907. var color, i = 0, x, y;
  23908. var imageData = new Uint8Array(width * height * 4);
  23909. for (y = y_start; y !== y_end; y += y_step) {
  23910. for (x = x_start; x !== x_end; x += x_step, i++) {
  23911. color = image[i];
  23912. imageData[(x + width * y) * 4 + 3] = 255;
  23913. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23914. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23915. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23916. }
  23917. }
  23918. return imageData;
  23919. };
  23920. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23921. var image = pixel_data;
  23922. var width = header.width, height = header.height;
  23923. var color, i = 0, x, y;
  23924. var imageData = new Uint8Array(width * height * 4);
  23925. for (y = y_start; y !== y_end; y += y_step) {
  23926. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23927. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23928. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23929. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23930. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23931. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23932. }
  23933. }
  23934. return imageData;
  23935. };
  23936. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23937. var image = pixel_data;
  23938. var width = header.width, height = header.height;
  23939. var i = 0, x, y;
  23940. var imageData = new Uint8Array(width * height * 4);
  23941. for (y = y_start; y !== y_end; y += y_step) {
  23942. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23943. imageData[(x + width * y) * 4 + 3] = 255;
  23944. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23945. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23946. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23947. }
  23948. }
  23949. return imageData;
  23950. };
  23951. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23952. var image = pixel_data;
  23953. var width = header.width, height = header.height;
  23954. var i = 0, x, y;
  23955. var imageData = new Uint8Array(width * height * 4);
  23956. for (y = y_start; y !== y_end; y += y_step) {
  23957. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23958. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23959. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23960. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23961. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23962. }
  23963. }
  23964. return imageData;
  23965. };
  23966. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23967. var image = pixel_data;
  23968. var width = header.width, height = header.height;
  23969. var color, i = 0, x, y;
  23970. var imageData = new Uint8Array(width * height * 4);
  23971. for (y = y_start; y !== y_end; y += y_step) {
  23972. for (x = x_start; x !== x_end; x += x_step, i++) {
  23973. color = image[i];
  23974. imageData[(x + width * y) * 4 + 0] = color;
  23975. imageData[(x + width * y) * 4 + 1] = color;
  23976. imageData[(x + width * y) * 4 + 2] = color;
  23977. imageData[(x + width * y) * 4 + 3] = 255;
  23978. }
  23979. }
  23980. return imageData;
  23981. };
  23982. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23983. var image = pixel_data;
  23984. var width = header.width, height = header.height;
  23985. var i = 0, x, y;
  23986. var imageData = new Uint8Array(width * height * 4);
  23987. for (y = y_start; y !== y_end; y += y_step) {
  23988. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23989. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23990. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23991. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23992. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23993. }
  23994. }
  23995. return imageData;
  23996. };
  23997. TGATools._TYPE_NO_DATA = 0;
  23998. TGATools._TYPE_INDEXED = 1;
  23999. TGATools._TYPE_RGB = 2;
  24000. TGATools._TYPE_GREY = 3;
  24001. TGATools._TYPE_RLE_INDEXED = 9;
  24002. TGATools._TYPE_RLE_RGB = 10;
  24003. TGATools._TYPE_RLE_GREY = 11;
  24004. TGATools._ORIGIN_MASK = 0x30;
  24005. TGATools._ORIGIN_SHIFT = 0x04;
  24006. TGATools._ORIGIN_BL = 0x00;
  24007. TGATools._ORIGIN_BR = 0x01;
  24008. TGATools._ORIGIN_UL = 0x02;
  24009. TGATools._ORIGIN_UR = 0x03;
  24010. return TGATools;
  24011. })();
  24012. Internals.TGATools = TGATools;
  24013. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24014. })(BABYLON || (BABYLON = {}));
  24015. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  24016. (function (BABYLON) {
  24017. var Internals;
  24018. (function (Internals) {
  24019. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  24020. // All values and structures referenced from:
  24021. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  24022. var DDS_MAGIC = 0x20534444;
  24023. 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;
  24024. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  24025. 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;
  24026. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  24027. function FourCCToInt32(value) {
  24028. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  24029. }
  24030. function Int32ToFourCC(value) {
  24031. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  24032. }
  24033. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  24034. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  24035. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  24036. var headerLengthInt = 31; // The header length in 32 bit ints
  24037. // Offsets into the header array
  24038. var off_magic = 0;
  24039. var off_size = 1;
  24040. var off_flags = 2;
  24041. var off_height = 3;
  24042. var off_width = 4;
  24043. var off_mipmapCount = 7;
  24044. var off_pfFlags = 20;
  24045. var off_pfFourCC = 21;
  24046. var off_RGBbpp = 22;
  24047. var off_RMask = 23;
  24048. var off_GMask = 24;
  24049. var off_BMask = 25;
  24050. var off_AMask = 26;
  24051. var off_caps1 = 27;
  24052. var off_caps2 = 28;
  24053. ;
  24054. var DDSTools = (function () {
  24055. function DDSTools() {
  24056. }
  24057. DDSTools.GetDDSInfo = function (arrayBuffer) {
  24058. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  24059. var mipmapCount = 1;
  24060. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  24061. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24062. }
  24063. return {
  24064. width: header[off_width],
  24065. height: header[off_height],
  24066. mipmapCount: mipmapCount,
  24067. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  24068. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  24069. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  24070. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  24071. };
  24072. };
  24073. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24074. var byteArray = new Uint8Array(dataLength);
  24075. var srcData = new Uint8Array(arrayBuffer);
  24076. var index = 0;
  24077. for (var y = height - 1; y >= 0; y--) {
  24078. for (var x = 0; x < width; x++) {
  24079. var srcPos = dataOffset + (x + y * width) * 4;
  24080. byteArray[index + 2] = srcData[srcPos];
  24081. byteArray[index + 1] = srcData[srcPos + 1];
  24082. byteArray[index] = srcData[srcPos + 2];
  24083. byteArray[index + 3] = srcData[srcPos + 3];
  24084. index += 4;
  24085. }
  24086. }
  24087. return byteArray;
  24088. };
  24089. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24090. var byteArray = new Uint8Array(dataLength);
  24091. var srcData = new Uint8Array(arrayBuffer);
  24092. var index = 0;
  24093. for (var y = height - 1; y >= 0; y--) {
  24094. for (var x = 0; x < width; x++) {
  24095. var srcPos = dataOffset + (x + y * width) * 3;
  24096. byteArray[index + 2] = srcData[srcPos];
  24097. byteArray[index + 1] = srcData[srcPos + 1];
  24098. byteArray[index] = srcData[srcPos + 2];
  24099. index += 3;
  24100. }
  24101. }
  24102. return byteArray;
  24103. };
  24104. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24105. var byteArray = new Uint8Array(dataLength);
  24106. var srcData = new Uint8Array(arrayBuffer);
  24107. var index = 0;
  24108. for (var y = height - 1; y >= 0; y--) {
  24109. for (var x = 0; x < width; x++) {
  24110. var srcPos = dataOffset + (x + y * width);
  24111. byteArray[index] = srcData[srcPos];
  24112. index++;
  24113. }
  24114. }
  24115. return byteArray;
  24116. };
  24117. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  24118. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  24119. if (header[off_magic] != DDS_MAGIC) {
  24120. BABYLON.Tools.Error("Invalid magic number in DDS header");
  24121. return;
  24122. }
  24123. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  24124. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  24125. return;
  24126. }
  24127. if (info.isFourCC) {
  24128. fourCC = header[off_pfFourCC];
  24129. switch (fourCC) {
  24130. case FOURCC_DXT1:
  24131. blockBytes = 8;
  24132. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24133. break;
  24134. case FOURCC_DXT3:
  24135. blockBytes = 16;
  24136. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24137. break;
  24138. case FOURCC_DXT5:
  24139. blockBytes = 16;
  24140. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24141. break;
  24142. default:
  24143. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  24144. return;
  24145. }
  24146. }
  24147. mipmapCount = 1;
  24148. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  24149. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24150. }
  24151. var bpp = header[off_RGBbpp];
  24152. for (var face = 0; face < faces; face++) {
  24153. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  24154. width = header[off_width];
  24155. height = header[off_height];
  24156. dataOffset = header[off_size] + 4;
  24157. for (i = 0; i < mipmapCount; ++i) {
  24158. if (info.isRGB) {
  24159. if (bpp == 24) {
  24160. dataLength = width * height * 3;
  24161. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24162. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  24163. }
  24164. else {
  24165. dataLength = width * height * 4;
  24166. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24167. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  24168. }
  24169. }
  24170. else if (info.isLuminance) {
  24171. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  24172. var unpaddedRowSize = width;
  24173. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  24174. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  24175. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24176. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  24177. }
  24178. else {
  24179. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  24180. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  24181. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  24182. }
  24183. dataOffset += dataLength;
  24184. width *= 0.5;
  24185. height *= 0.5;
  24186. width = Math.max(1.0, width);
  24187. height = Math.max(1.0, height);
  24188. }
  24189. }
  24190. };
  24191. return DDSTools;
  24192. })();
  24193. Internals.DDSTools = DDSTools;
  24194. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24195. })(BABYLON || (BABYLON = {}));
  24196. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  24197. (function (BABYLON) {
  24198. var SmartArray = (function () {
  24199. function SmartArray(capacity) {
  24200. this.length = 0;
  24201. this._duplicateId = 0;
  24202. this.data = new Array(capacity);
  24203. this._id = SmartArray._GlobalId++;
  24204. }
  24205. SmartArray.prototype.push = function (value) {
  24206. this.data[this.length++] = value;
  24207. if (this.length > this.data.length) {
  24208. this.data.length *= 2;
  24209. }
  24210. if (!value.__smartArrayFlags) {
  24211. value.__smartArrayFlags = {};
  24212. }
  24213. value.__smartArrayFlags[this._id] = this._duplicateId;
  24214. };
  24215. SmartArray.prototype.pushNoDuplicate = function (value) {
  24216. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  24217. return;
  24218. }
  24219. this.push(value);
  24220. };
  24221. SmartArray.prototype.sort = function (compareFn) {
  24222. this.data.sort(compareFn);
  24223. };
  24224. SmartArray.prototype.reset = function () {
  24225. this.length = 0;
  24226. this._duplicateId++;
  24227. };
  24228. SmartArray.prototype.concat = function (array) {
  24229. if (array.length === 0) {
  24230. return;
  24231. }
  24232. if (this.length + array.length > this.data.length) {
  24233. this.data.length = (this.length + array.length) * 2;
  24234. }
  24235. for (var index = 0; index < array.length; index++) {
  24236. this.data[this.length++] = (array.data || array)[index];
  24237. }
  24238. };
  24239. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  24240. if (array.length === 0) {
  24241. return;
  24242. }
  24243. if (this.length + array.length > this.data.length) {
  24244. this.data.length = (this.length + array.length) * 2;
  24245. }
  24246. for (var index = 0; index < array.length; index++) {
  24247. var item = (array.data || array)[index];
  24248. this.pushNoDuplicate(item);
  24249. }
  24250. };
  24251. SmartArray.prototype.indexOf = function (value) {
  24252. var position = this.data.indexOf(value);
  24253. if (position >= this.length) {
  24254. return -1;
  24255. }
  24256. return position;
  24257. };
  24258. // Statics
  24259. SmartArray._GlobalId = 0;
  24260. return SmartArray;
  24261. })();
  24262. BABYLON.SmartArray = SmartArray;
  24263. })(BABYLON || (BABYLON = {}));
  24264. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  24265. (function (BABYLON) {
  24266. var CannonJSPlugin = (function () {
  24267. function CannonJSPlugin() {
  24268. this._registeredMeshes = [];
  24269. this._physicsMaterials = [];
  24270. this.updateBodyPosition = function (mesh) {
  24271. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24272. var registeredMesh = this._registeredMeshes[index];
  24273. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24274. var body = registeredMesh.body;
  24275. var center = mesh.getBoundingInfo().boundingBox.center;
  24276. body.position.set(center.x, center.z, center.y);
  24277. body.quaternion.x = mesh.rotationQuaternion.x;
  24278. body.quaternion.z = mesh.rotationQuaternion.y;
  24279. body.quaternion.y = mesh.rotationQuaternion.z;
  24280. body.quaternion.w = -mesh.rotationQuaternion.w;
  24281. return;
  24282. }
  24283. }
  24284. };
  24285. }
  24286. CannonJSPlugin.prototype.initialize = function (iterations) {
  24287. if (iterations === void 0) { iterations = 10; }
  24288. this._world = new CANNON.World();
  24289. this._world.broadphase = new CANNON.NaiveBroadphase();
  24290. this._world.solver.iterations = iterations;
  24291. };
  24292. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24293. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24294. };
  24295. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24296. this._world.step(delta);
  24297. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24298. var registeredMesh = this._registeredMeshes[index];
  24299. if (registeredMesh.isChild) {
  24300. continue;
  24301. }
  24302. // Body position
  24303. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24304. var deltaPos = registeredMesh.delta;
  24305. if (deltaPos) {
  24306. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24307. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24308. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24309. }
  24310. else {
  24311. registeredMesh.mesh.position.x = bodyX;
  24312. registeredMesh.mesh.position.y = bodyZ;
  24313. registeredMesh.mesh.position.z = bodyY;
  24314. }
  24315. if (!registeredMesh.mesh.rotationQuaternion) {
  24316. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24317. }
  24318. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24319. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24320. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24321. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24322. }
  24323. };
  24324. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24325. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24326. };
  24327. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24328. this.unregisterMesh(mesh);
  24329. mesh.computeWorldMatrix(true);
  24330. switch (impostor) {
  24331. case BABYLON.PhysicsEngine.SphereImpostor:
  24332. var bbox = mesh.getBoundingInfo().boundingBox;
  24333. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24334. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24335. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24336. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24337. case BABYLON.PhysicsEngine.BoxImpostor:
  24338. bbox = mesh.getBoundingInfo().boundingBox;
  24339. var min = bbox.minimumWorld;
  24340. var max = bbox.maximumWorld;
  24341. var box = max.subtract(min).scale(0.5);
  24342. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24343. case BABYLON.PhysicsEngine.PlaneImpostor:
  24344. return this._createPlane(mesh, options);
  24345. case BABYLON.PhysicsEngine.MeshImpostor:
  24346. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24347. var rawFaces = mesh.getIndices();
  24348. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24349. }
  24350. return null;
  24351. };
  24352. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24353. var shape = new CANNON.Sphere(radius);
  24354. if (!options) {
  24355. return shape;
  24356. }
  24357. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24358. };
  24359. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24360. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24361. if (!options) {
  24362. return shape;
  24363. }
  24364. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24365. };
  24366. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24367. var shape = new CANNON.Plane();
  24368. if (!options) {
  24369. return shape;
  24370. }
  24371. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24372. };
  24373. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24374. var verts = [], faces = [];
  24375. mesh.computeWorldMatrix(true);
  24376. for (var i = 0; i < rawVerts.length; i += 3) {
  24377. var transformed = BABYLON.Vector3.Zero();
  24378. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24379. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24380. }
  24381. for (var j = 0; j < rawFaces.length; j += 3) {
  24382. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24383. }
  24384. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24385. if (!options) {
  24386. return shape;
  24387. }
  24388. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24389. };
  24390. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24391. var index;
  24392. var mat;
  24393. for (index = 0; index < this._physicsMaterials.length; index++) {
  24394. mat = this._physicsMaterials[index];
  24395. if (mat.friction === friction && mat.restitution === restitution) {
  24396. return mat;
  24397. }
  24398. }
  24399. var currentMat = new CANNON.Material();
  24400. currentMat.friction = friction;
  24401. currentMat.restitution = restitution;
  24402. this._physicsMaterials.push(currentMat);
  24403. for (index = 0; index < this._physicsMaterials.length; index++) {
  24404. mat = this._physicsMaterials[index];
  24405. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24406. contactMaterial.contactEquationStiffness = 1e10;
  24407. contactMaterial.contactEquationRegularizationTime = 10;
  24408. this._world.addContactMaterial(contactMaterial);
  24409. }
  24410. return currentMat;
  24411. };
  24412. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24413. var initialRotation = null;
  24414. if (mesh.rotationQuaternion) {
  24415. initialRotation = mesh.rotationQuaternion.clone();
  24416. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24417. }
  24418. // The delta between the mesh position and the mesh bounding box center
  24419. var bbox = mesh.getBoundingInfo().boundingBox;
  24420. var deltaPosition = mesh.position.subtract(bbox.center);
  24421. var material = this._addMaterial(friction, restitution);
  24422. var body = new CANNON.RigidBody(mass, shape, material);
  24423. if (initialRotation) {
  24424. body.quaternion.x = initialRotation.x;
  24425. body.quaternion.z = initialRotation.y;
  24426. body.quaternion.y = initialRotation.z;
  24427. body.quaternion.w = -initialRotation.w;
  24428. }
  24429. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24430. this._world.add(body);
  24431. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24432. return body;
  24433. };
  24434. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24435. var compoundShape = new CANNON.Compound();
  24436. for (var index = 0; index < parts.length; index++) {
  24437. var mesh = parts[index].mesh;
  24438. var shape = this.registerMesh(mesh, parts[index].impostor);
  24439. if (index == 0) {
  24440. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24441. }
  24442. else {
  24443. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24444. }
  24445. }
  24446. var initialMesh = parts[0].mesh;
  24447. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24448. body.parts = parts;
  24449. return body;
  24450. };
  24451. CannonJSPlugin.prototype._unbindBody = function (body) {
  24452. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24453. var registeredMesh = this._registeredMeshes[index];
  24454. if (registeredMesh.body === body) {
  24455. registeredMesh.body = null;
  24456. registeredMesh.delta = 0;
  24457. }
  24458. }
  24459. };
  24460. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24461. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24462. var registeredMesh = this._registeredMeshes[index];
  24463. if (registeredMesh.mesh === mesh) {
  24464. // Remove body
  24465. if (registeredMesh.body) {
  24466. this._world.remove(registeredMesh.body);
  24467. this._unbindBody(registeredMesh.body);
  24468. }
  24469. this._registeredMeshes.splice(index, 1);
  24470. return;
  24471. }
  24472. }
  24473. };
  24474. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24475. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24476. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24477. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24478. var registeredMesh = this._registeredMeshes[index];
  24479. if (registeredMesh.mesh === mesh) {
  24480. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24481. return;
  24482. }
  24483. }
  24484. };
  24485. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24486. var body1 = null, body2 = null;
  24487. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24488. var registeredMesh = this._registeredMeshes[index];
  24489. if (registeredMesh.mesh === mesh1) {
  24490. body1 = registeredMesh.body;
  24491. }
  24492. else if (registeredMesh.mesh === mesh2) {
  24493. body2 = registeredMesh.body;
  24494. }
  24495. }
  24496. if (!body1 || !body2) {
  24497. return false;
  24498. }
  24499. 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));
  24500. this._world.addConstraint(constraint);
  24501. return true;
  24502. };
  24503. CannonJSPlugin.prototype.dispose = function () {
  24504. while (this._registeredMeshes.length) {
  24505. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24506. }
  24507. };
  24508. CannonJSPlugin.prototype.isSupported = function () {
  24509. return window.CANNON !== undefined;
  24510. };
  24511. return CannonJSPlugin;
  24512. })();
  24513. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24514. })(BABYLON || (BABYLON = {}));
  24515. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24516. var BABYLON;
  24517. (function (BABYLON) {
  24518. var Condition = (function () {
  24519. function Condition(actionManager) {
  24520. this._actionManager = actionManager;
  24521. }
  24522. Condition.prototype.isValid = function () {
  24523. return true;
  24524. };
  24525. Condition.prototype._getProperty = function (propertyPath) {
  24526. return this._actionManager._getProperty(propertyPath);
  24527. };
  24528. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24529. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24530. };
  24531. return Condition;
  24532. })();
  24533. BABYLON.Condition = Condition;
  24534. var ValueCondition = (function (_super) {
  24535. __extends(ValueCondition, _super);
  24536. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24537. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24538. _super.call(this, actionManager);
  24539. this.propertyPath = propertyPath;
  24540. this.value = value;
  24541. this.operator = operator;
  24542. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24543. this._property = this._getProperty(this.propertyPath);
  24544. }
  24545. Object.defineProperty(ValueCondition, "IsEqual", {
  24546. get: function () {
  24547. return ValueCondition._IsEqual;
  24548. },
  24549. enumerable: true,
  24550. configurable: true
  24551. });
  24552. Object.defineProperty(ValueCondition, "IsDifferent", {
  24553. get: function () {
  24554. return ValueCondition._IsDifferent;
  24555. },
  24556. enumerable: true,
  24557. configurable: true
  24558. });
  24559. Object.defineProperty(ValueCondition, "IsGreater", {
  24560. get: function () {
  24561. return ValueCondition._IsGreater;
  24562. },
  24563. enumerable: true,
  24564. configurable: true
  24565. });
  24566. Object.defineProperty(ValueCondition, "IsLesser", {
  24567. get: function () {
  24568. return ValueCondition._IsLesser;
  24569. },
  24570. enumerable: true,
  24571. configurable: true
  24572. });
  24573. // Methods
  24574. ValueCondition.prototype.isValid = function () {
  24575. switch (this.operator) {
  24576. case ValueCondition.IsGreater:
  24577. return this._target[this._property] > this.value;
  24578. case ValueCondition.IsLesser:
  24579. return this._target[this._property] < this.value;
  24580. case ValueCondition.IsEqual:
  24581. case ValueCondition.IsDifferent:
  24582. var check;
  24583. if (this.value.equals) {
  24584. check = this.value.equals(this._target[this._property]);
  24585. }
  24586. else {
  24587. check = this.value === this._target[this._property];
  24588. }
  24589. return this.operator === ValueCondition.IsEqual ? check : !check;
  24590. }
  24591. return false;
  24592. };
  24593. // Statics
  24594. ValueCondition._IsEqual = 0;
  24595. ValueCondition._IsDifferent = 1;
  24596. ValueCondition._IsGreater = 2;
  24597. ValueCondition._IsLesser = 3;
  24598. return ValueCondition;
  24599. })(Condition);
  24600. BABYLON.ValueCondition = ValueCondition;
  24601. var PredicateCondition = (function (_super) {
  24602. __extends(PredicateCondition, _super);
  24603. function PredicateCondition(actionManager, predicate) {
  24604. _super.call(this, actionManager);
  24605. this.predicate = predicate;
  24606. }
  24607. PredicateCondition.prototype.isValid = function () {
  24608. return this.predicate();
  24609. };
  24610. return PredicateCondition;
  24611. })(Condition);
  24612. BABYLON.PredicateCondition = PredicateCondition;
  24613. var StateCondition = (function (_super) {
  24614. __extends(StateCondition, _super);
  24615. function StateCondition(actionManager, target, value) {
  24616. _super.call(this, actionManager);
  24617. this.value = value;
  24618. this._target = target;
  24619. }
  24620. // Methods
  24621. StateCondition.prototype.isValid = function () {
  24622. return this._target.state === this.value;
  24623. };
  24624. return StateCondition;
  24625. })(Condition);
  24626. BABYLON.StateCondition = StateCondition;
  24627. })(BABYLON || (BABYLON = {}));
  24628. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24629. (function (BABYLON) {
  24630. var Action = (function () {
  24631. function Action(triggerOptions, condition) {
  24632. this.triggerOptions = triggerOptions;
  24633. if (triggerOptions.parameter) {
  24634. this.trigger = triggerOptions.trigger;
  24635. this._triggerParameter = triggerOptions.parameter;
  24636. }
  24637. else {
  24638. this.trigger = triggerOptions;
  24639. }
  24640. this._nextActiveAction = this;
  24641. this._condition = condition;
  24642. }
  24643. // Methods
  24644. Action.prototype._prepare = function () {
  24645. };
  24646. Action.prototype.getTriggerParameter = function () {
  24647. return this._triggerParameter;
  24648. };
  24649. Action.prototype._executeCurrent = function (evt) {
  24650. if (this._nextActiveAction._condition) {
  24651. var condition = this._nextActiveAction._condition;
  24652. var currentRenderId = this._actionManager.getScene().getRenderId();
  24653. // We cache the current evaluation for the current frame
  24654. if (condition._evaluationId === currentRenderId) {
  24655. if (!condition._currentResult) {
  24656. return;
  24657. }
  24658. }
  24659. else {
  24660. condition._evaluationId = currentRenderId;
  24661. if (!condition.isValid()) {
  24662. condition._currentResult = false;
  24663. return;
  24664. }
  24665. condition._currentResult = true;
  24666. }
  24667. }
  24668. this._nextActiveAction.execute(evt);
  24669. if (this._nextActiveAction._child) {
  24670. if (!this._nextActiveAction._child._actionManager) {
  24671. this._nextActiveAction._child._actionManager = this._actionManager;
  24672. }
  24673. this._nextActiveAction = this._nextActiveAction._child;
  24674. }
  24675. else {
  24676. this._nextActiveAction = this;
  24677. }
  24678. };
  24679. Action.prototype.execute = function (evt) {
  24680. };
  24681. Action.prototype.then = function (action) {
  24682. this._child = action;
  24683. action._actionManager = this._actionManager;
  24684. action._prepare();
  24685. return action;
  24686. };
  24687. Action.prototype._getProperty = function (propertyPath) {
  24688. return this._actionManager._getProperty(propertyPath);
  24689. };
  24690. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24691. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24692. };
  24693. return Action;
  24694. })();
  24695. BABYLON.Action = Action;
  24696. })(BABYLON || (BABYLON = {}));
  24697. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24698. (function (BABYLON) {
  24699. /**
  24700. * ActionEvent is the event beint sent when an action is triggered.
  24701. */
  24702. var ActionEvent = (function () {
  24703. /**
  24704. * @constructor
  24705. * @param source The mesh that triggered the action.
  24706. * @param pointerX the X mouse cursor position at the time of the event
  24707. * @param pointerY the Y mouse cursor position at the time of the event
  24708. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24709. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24710. */
  24711. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24712. this.source = source;
  24713. this.pointerX = pointerX;
  24714. this.pointerY = pointerY;
  24715. this.meshUnderPointer = meshUnderPointer;
  24716. this.sourceEvent = sourceEvent;
  24717. }
  24718. /**
  24719. * Helper function to auto-create an ActionEvent from a source mesh.
  24720. * @param source the source mesh that triggered the event
  24721. * @param evt {Event} The original (browser) event
  24722. */
  24723. ActionEvent.CreateNew = function (source, evt) {
  24724. var scene = source.getScene();
  24725. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24726. };
  24727. /**
  24728. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24729. * @param scene the scene where the event occurred
  24730. * @param evt {Event} The original (browser) event
  24731. */
  24732. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24733. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24734. };
  24735. return ActionEvent;
  24736. })();
  24737. BABYLON.ActionEvent = ActionEvent;
  24738. /**
  24739. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24740. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24741. */
  24742. var ActionManager = (function () {
  24743. function ActionManager(scene) {
  24744. // Members
  24745. this.actions = new Array();
  24746. this._scene = scene;
  24747. scene._actionManagers.push(this);
  24748. }
  24749. Object.defineProperty(ActionManager, "NothingTrigger", {
  24750. get: function () {
  24751. return ActionManager._NothingTrigger;
  24752. },
  24753. enumerable: true,
  24754. configurable: true
  24755. });
  24756. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24757. get: function () {
  24758. return ActionManager._OnPickTrigger;
  24759. },
  24760. enumerable: true,
  24761. configurable: true
  24762. });
  24763. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24764. get: function () {
  24765. return ActionManager._OnLeftPickTrigger;
  24766. },
  24767. enumerable: true,
  24768. configurable: true
  24769. });
  24770. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24771. get: function () {
  24772. return ActionManager._OnRightPickTrigger;
  24773. },
  24774. enumerable: true,
  24775. configurable: true
  24776. });
  24777. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24778. get: function () {
  24779. return ActionManager._OnCenterPickTrigger;
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24785. get: function () {
  24786. return ActionManager._OnPointerOverTrigger;
  24787. },
  24788. enumerable: true,
  24789. configurable: true
  24790. });
  24791. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24792. get: function () {
  24793. return ActionManager._OnPointerOutTrigger;
  24794. },
  24795. enumerable: true,
  24796. configurable: true
  24797. });
  24798. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24799. get: function () {
  24800. return ActionManager._OnEveryFrameTrigger;
  24801. },
  24802. enumerable: true,
  24803. configurable: true
  24804. });
  24805. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24806. get: function () {
  24807. return ActionManager._OnIntersectionEnterTrigger;
  24808. },
  24809. enumerable: true,
  24810. configurable: true
  24811. });
  24812. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24813. get: function () {
  24814. return ActionManager._OnIntersectionExitTrigger;
  24815. },
  24816. enumerable: true,
  24817. configurable: true
  24818. });
  24819. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24820. get: function () {
  24821. return ActionManager._OnKeyDownTrigger;
  24822. },
  24823. enumerable: true,
  24824. configurable: true
  24825. });
  24826. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24827. get: function () {
  24828. return ActionManager._OnKeyUpTrigger;
  24829. },
  24830. enumerable: true,
  24831. configurable: true
  24832. });
  24833. // Methods
  24834. ActionManager.prototype.dispose = function () {
  24835. var index = this._scene._actionManagers.indexOf(this);
  24836. if (index > -1) {
  24837. this._scene._actionManagers.splice(index, 1);
  24838. }
  24839. };
  24840. ActionManager.prototype.getScene = function () {
  24841. return this._scene;
  24842. };
  24843. /**
  24844. * Does this action manager handles actions of any of the given triggers
  24845. * @param {number[]} triggers - the triggers to be tested
  24846. * @return {boolean} whether one (or more) of the triggers is handeled
  24847. */
  24848. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24849. for (var index = 0; index < this.actions.length; index++) {
  24850. var action = this.actions[index];
  24851. if (triggers.indexOf(action.trigger) > -1) {
  24852. return true;
  24853. }
  24854. }
  24855. return false;
  24856. };
  24857. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24858. /**
  24859. * Does this action manager has pointer triggers
  24860. * @return {boolean} whether or not it has pointer triggers
  24861. */
  24862. get: function () {
  24863. for (var index = 0; index < this.actions.length; index++) {
  24864. var action = this.actions[index];
  24865. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24866. return true;
  24867. }
  24868. }
  24869. return false;
  24870. },
  24871. enumerable: true,
  24872. configurable: true
  24873. });
  24874. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24875. /**
  24876. * Does this action manager has pick triggers
  24877. * @return {boolean} whether or not it has pick triggers
  24878. */
  24879. get: function () {
  24880. for (var index = 0; index < this.actions.length; index++) {
  24881. var action = this.actions[index];
  24882. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24883. return true;
  24884. }
  24885. }
  24886. return false;
  24887. },
  24888. enumerable: true,
  24889. configurable: true
  24890. });
  24891. /**
  24892. * Registers an action to this action manager
  24893. * @param {BABYLON.Action} action - the action to be registered
  24894. * @return {BABYLON.Action} the action amended (prepared) after registration
  24895. */
  24896. ActionManager.prototype.registerAction = function (action) {
  24897. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24898. if (this.getScene().actionManager !== this) {
  24899. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24900. return null;
  24901. }
  24902. }
  24903. this.actions.push(action);
  24904. action._actionManager = this;
  24905. action._prepare();
  24906. return action;
  24907. };
  24908. /**
  24909. * Process a specific trigger
  24910. * @param {number} trigger - the trigger to process
  24911. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24912. */
  24913. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24914. for (var index = 0; index < this.actions.length; index++) {
  24915. var action = this.actions[index];
  24916. if (action.trigger === trigger) {
  24917. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24918. var parameter = action.getTriggerParameter();
  24919. if (parameter) {
  24920. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24921. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24922. if (actualkey !== parameter.toLowerCase()) {
  24923. continue;
  24924. }
  24925. }
  24926. }
  24927. action._executeCurrent(evt);
  24928. }
  24929. }
  24930. };
  24931. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24932. var properties = propertyPath.split(".");
  24933. for (var index = 0; index < properties.length - 1; index++) {
  24934. target = target[properties[index]];
  24935. }
  24936. return target;
  24937. };
  24938. ActionManager.prototype._getProperty = function (propertyPath) {
  24939. var properties = propertyPath.split(".");
  24940. return properties[properties.length - 1];
  24941. };
  24942. // Statics
  24943. ActionManager._NothingTrigger = 0;
  24944. ActionManager._OnPickTrigger = 1;
  24945. ActionManager._OnLeftPickTrigger = 2;
  24946. ActionManager._OnRightPickTrigger = 3;
  24947. ActionManager._OnCenterPickTrigger = 4;
  24948. ActionManager._OnPointerOverTrigger = 5;
  24949. ActionManager._OnPointerOutTrigger = 6;
  24950. ActionManager._OnEveryFrameTrigger = 7;
  24951. ActionManager._OnIntersectionEnterTrigger = 8;
  24952. ActionManager._OnIntersectionExitTrigger = 9;
  24953. ActionManager._OnKeyDownTrigger = 10;
  24954. ActionManager._OnKeyUpTrigger = 11;
  24955. return ActionManager;
  24956. })();
  24957. BABYLON.ActionManager = ActionManager;
  24958. })(BABYLON || (BABYLON = {}));
  24959. //# sourceMappingURL=babylon.actionManager.js.map
  24960. var BABYLON;
  24961. (function (BABYLON) {
  24962. var InterpolateValueAction = (function (_super) {
  24963. __extends(InterpolateValueAction, _super);
  24964. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24965. if (duration === void 0) { duration = 1000; }
  24966. _super.call(this, triggerOptions, condition);
  24967. this.propertyPath = propertyPath;
  24968. this.value = value;
  24969. this.duration = duration;
  24970. this.stopOtherAnimations = stopOtherAnimations;
  24971. this._target = target;
  24972. }
  24973. InterpolateValueAction.prototype._prepare = function () {
  24974. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24975. this._property = this._getProperty(this.propertyPath);
  24976. };
  24977. InterpolateValueAction.prototype.execute = function () {
  24978. var scene = this._actionManager.getScene();
  24979. var keys = [
  24980. {
  24981. frame: 0,
  24982. value: this._target[this._property]
  24983. },
  24984. {
  24985. frame: 100,
  24986. value: this.value
  24987. }
  24988. ];
  24989. var dataType;
  24990. if (typeof this.value === "number") {
  24991. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24992. }
  24993. else if (this.value instanceof BABYLON.Color3) {
  24994. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24995. }
  24996. else if (this.value instanceof BABYLON.Vector3) {
  24997. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24998. }
  24999. else if (this.value instanceof BABYLON.Matrix) {
  25000. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25001. }
  25002. else if (this.value instanceof BABYLON.Quaternion) {
  25003. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25004. }
  25005. else {
  25006. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25007. return;
  25008. }
  25009. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25010. animation.setKeys(keys);
  25011. if (this.stopOtherAnimations) {
  25012. scene.stopAnimation(this._target);
  25013. }
  25014. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  25015. };
  25016. return InterpolateValueAction;
  25017. })(BABYLON.Action);
  25018. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25019. })(BABYLON || (BABYLON = {}));
  25020. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  25021. var BABYLON;
  25022. (function (BABYLON) {
  25023. var SwitchBooleanAction = (function (_super) {
  25024. __extends(SwitchBooleanAction, _super);
  25025. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25026. _super.call(this, triggerOptions, condition);
  25027. this.propertyPath = propertyPath;
  25028. this._target = target;
  25029. }
  25030. SwitchBooleanAction.prototype._prepare = function () {
  25031. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25032. this._property = this._getProperty(this.propertyPath);
  25033. };
  25034. SwitchBooleanAction.prototype.execute = function () {
  25035. this._target[this._property] = !this._target[this._property];
  25036. };
  25037. return SwitchBooleanAction;
  25038. })(BABYLON.Action);
  25039. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25040. var SetStateAction = (function (_super) {
  25041. __extends(SetStateAction, _super);
  25042. function SetStateAction(triggerOptions, target, value, condition) {
  25043. _super.call(this, triggerOptions, condition);
  25044. this.value = value;
  25045. this._target = target;
  25046. }
  25047. SetStateAction.prototype.execute = function () {
  25048. this._target.state = this.value;
  25049. };
  25050. return SetStateAction;
  25051. })(BABYLON.Action);
  25052. BABYLON.SetStateAction = SetStateAction;
  25053. var SetValueAction = (function (_super) {
  25054. __extends(SetValueAction, _super);
  25055. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25056. _super.call(this, triggerOptions, condition);
  25057. this.propertyPath = propertyPath;
  25058. this.value = value;
  25059. this._target = target;
  25060. }
  25061. SetValueAction.prototype._prepare = function () {
  25062. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25063. this._property = this._getProperty(this.propertyPath);
  25064. };
  25065. SetValueAction.prototype.execute = function () {
  25066. this._target[this._property] = this.value;
  25067. };
  25068. return SetValueAction;
  25069. })(BABYLON.Action);
  25070. BABYLON.SetValueAction = SetValueAction;
  25071. var IncrementValueAction = (function (_super) {
  25072. __extends(IncrementValueAction, _super);
  25073. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25074. _super.call(this, triggerOptions, condition);
  25075. this.propertyPath = propertyPath;
  25076. this.value = value;
  25077. this._target = target;
  25078. }
  25079. IncrementValueAction.prototype._prepare = function () {
  25080. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25081. this._property = this._getProperty(this.propertyPath);
  25082. if (typeof this._target[this._property] !== "number") {
  25083. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25084. }
  25085. };
  25086. IncrementValueAction.prototype.execute = function () {
  25087. this._target[this._property] += this.value;
  25088. };
  25089. return IncrementValueAction;
  25090. })(BABYLON.Action);
  25091. BABYLON.IncrementValueAction = IncrementValueAction;
  25092. var PlayAnimationAction = (function (_super) {
  25093. __extends(PlayAnimationAction, _super);
  25094. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25095. _super.call(this, triggerOptions, condition);
  25096. this.from = from;
  25097. this.to = to;
  25098. this.loop = loop;
  25099. this._target = target;
  25100. }
  25101. PlayAnimationAction.prototype._prepare = function () {
  25102. };
  25103. PlayAnimationAction.prototype.execute = function () {
  25104. var scene = this._actionManager.getScene();
  25105. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25106. };
  25107. return PlayAnimationAction;
  25108. })(BABYLON.Action);
  25109. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25110. var StopAnimationAction = (function (_super) {
  25111. __extends(StopAnimationAction, _super);
  25112. function StopAnimationAction(triggerOptions, target, condition) {
  25113. _super.call(this, triggerOptions, condition);
  25114. this._target = target;
  25115. }
  25116. StopAnimationAction.prototype._prepare = function () {
  25117. };
  25118. StopAnimationAction.prototype.execute = function () {
  25119. var scene = this._actionManager.getScene();
  25120. scene.stopAnimation(this._target);
  25121. };
  25122. return StopAnimationAction;
  25123. })(BABYLON.Action);
  25124. BABYLON.StopAnimationAction = StopAnimationAction;
  25125. var DoNothingAction = (function (_super) {
  25126. __extends(DoNothingAction, _super);
  25127. function DoNothingAction(triggerOptions, condition) {
  25128. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25129. _super.call(this, triggerOptions, condition);
  25130. }
  25131. DoNothingAction.prototype.execute = function () {
  25132. };
  25133. return DoNothingAction;
  25134. })(BABYLON.Action);
  25135. BABYLON.DoNothingAction = DoNothingAction;
  25136. var CombineAction = (function (_super) {
  25137. __extends(CombineAction, _super);
  25138. function CombineAction(triggerOptions, children, condition) {
  25139. _super.call(this, triggerOptions, condition);
  25140. this.children = children;
  25141. }
  25142. CombineAction.prototype._prepare = function () {
  25143. for (var index = 0; index < this.children.length; index++) {
  25144. this.children[index]._actionManager = this._actionManager;
  25145. this.children[index]._prepare();
  25146. }
  25147. };
  25148. CombineAction.prototype.execute = function (evt) {
  25149. for (var index = 0; index < this.children.length; index++) {
  25150. this.children[index].execute(evt);
  25151. }
  25152. };
  25153. return CombineAction;
  25154. })(BABYLON.Action);
  25155. BABYLON.CombineAction = CombineAction;
  25156. var ExecuteCodeAction = (function (_super) {
  25157. __extends(ExecuteCodeAction, _super);
  25158. function ExecuteCodeAction(triggerOptions, func, condition) {
  25159. _super.call(this, triggerOptions, condition);
  25160. this.func = func;
  25161. }
  25162. ExecuteCodeAction.prototype.execute = function (evt) {
  25163. this.func(evt);
  25164. };
  25165. return ExecuteCodeAction;
  25166. })(BABYLON.Action);
  25167. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25168. var SetParentAction = (function (_super) {
  25169. __extends(SetParentAction, _super);
  25170. function SetParentAction(triggerOptions, target, parent, condition) {
  25171. _super.call(this, triggerOptions, condition);
  25172. this._target = target;
  25173. this._parent = parent;
  25174. }
  25175. SetParentAction.prototype._prepare = function () {
  25176. };
  25177. SetParentAction.prototype.execute = function () {
  25178. if (this._target.parent === this._parent) {
  25179. return;
  25180. }
  25181. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25182. invertParentWorldMatrix.invert();
  25183. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25184. this._target.parent = this._parent;
  25185. };
  25186. return SetParentAction;
  25187. })(BABYLON.Action);
  25188. BABYLON.SetParentAction = SetParentAction;
  25189. var PlaySoundAction = (function (_super) {
  25190. __extends(PlaySoundAction, _super);
  25191. function PlaySoundAction(triggerOptions, sound, condition) {
  25192. _super.call(this, triggerOptions, condition);
  25193. this._sound = sound;
  25194. }
  25195. PlaySoundAction.prototype._prepare = function () {
  25196. };
  25197. PlaySoundAction.prototype.execute = function () {
  25198. if (this._sound !== undefined)
  25199. this._sound.play();
  25200. };
  25201. return PlaySoundAction;
  25202. })(BABYLON.Action);
  25203. BABYLON.PlaySoundAction = PlaySoundAction;
  25204. var StopSoundAction = (function (_super) {
  25205. __extends(StopSoundAction, _super);
  25206. function StopSoundAction(triggerOptions, sound, condition) {
  25207. _super.call(this, triggerOptions, condition);
  25208. this._sound = sound;
  25209. }
  25210. StopSoundAction.prototype._prepare = function () {
  25211. };
  25212. StopSoundAction.prototype.execute = function () {
  25213. if (this._sound !== undefined)
  25214. this._sound.stop();
  25215. };
  25216. return StopSoundAction;
  25217. })(BABYLON.Action);
  25218. BABYLON.StopSoundAction = StopSoundAction;
  25219. })(BABYLON || (BABYLON = {}));
  25220. //# sourceMappingURL=babylon.directActions.js.map
  25221. var BABYLON;
  25222. (function (BABYLON) {
  25223. var Geometry = (function () {
  25224. function Geometry(id, scene, vertexData, updatable, mesh) {
  25225. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25226. this._totalVertices = 0;
  25227. this._indices = [];
  25228. this._isDisposed = false;
  25229. this.id = id;
  25230. this._engine = scene.getEngine();
  25231. this._meshes = [];
  25232. this._scene = scene;
  25233. // vertexData
  25234. if (vertexData) {
  25235. this.setAllVerticesData(vertexData, updatable);
  25236. }
  25237. else {
  25238. this._totalVertices = 0;
  25239. this._indices = [];
  25240. }
  25241. // applyToMesh
  25242. if (mesh) {
  25243. this.applyToMesh(mesh);
  25244. mesh.computeWorldMatrix(true);
  25245. }
  25246. }
  25247. Geometry.prototype.getScene = function () {
  25248. return this._scene;
  25249. };
  25250. Geometry.prototype.getEngine = function () {
  25251. return this._engine;
  25252. };
  25253. Geometry.prototype.isReady = function () {
  25254. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25255. };
  25256. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25257. vertexData.applyToGeometry(this, updatable);
  25258. };
  25259. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25260. this._vertexBuffers = this._vertexBuffers || {};
  25261. if (this._vertexBuffers[kind]) {
  25262. this._vertexBuffers[kind].dispose();
  25263. }
  25264. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25265. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25266. stride = this._vertexBuffers[kind].getStrideSize();
  25267. this._totalVertices = data.length / stride;
  25268. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25269. var meshes = this._meshes;
  25270. var numOfMeshes = meshes.length;
  25271. for (var index = 0; index < numOfMeshes; index++) {
  25272. var mesh = meshes[index];
  25273. mesh._resetPointsArrayCache();
  25274. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25275. mesh._createGlobalSubMesh();
  25276. mesh.computeWorldMatrix(true);
  25277. }
  25278. }
  25279. };
  25280. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25281. var vertexBuffer = this.getVertexBuffer(kind);
  25282. if (!vertexBuffer) {
  25283. return;
  25284. }
  25285. vertexBuffer.updateDirectly(data, offset);
  25286. };
  25287. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25288. var vertexBuffer = this.getVertexBuffer(kind);
  25289. if (!vertexBuffer) {
  25290. return;
  25291. }
  25292. vertexBuffer.update(data);
  25293. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25294. var extend;
  25295. var stride = vertexBuffer.getStrideSize();
  25296. this._totalVertices = data.length / stride;
  25297. if (updateExtends) {
  25298. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25299. }
  25300. var meshes = this._meshes;
  25301. var numOfMeshes = meshes.length;
  25302. for (var index = 0; index < numOfMeshes; index++) {
  25303. var mesh = meshes[index];
  25304. mesh._resetPointsArrayCache();
  25305. if (updateExtends) {
  25306. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25307. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25308. var subMesh = mesh.subMeshes[subIndex];
  25309. subMesh.refreshBoundingInfo();
  25310. }
  25311. }
  25312. }
  25313. }
  25314. };
  25315. Geometry.prototype.getTotalVertices = function () {
  25316. if (!this.isReady()) {
  25317. return 0;
  25318. }
  25319. return this._totalVertices;
  25320. };
  25321. Geometry.prototype.getVerticesData = function (kind) {
  25322. var vertexBuffer = this.getVertexBuffer(kind);
  25323. if (!vertexBuffer) {
  25324. return null;
  25325. }
  25326. return vertexBuffer.getData();
  25327. };
  25328. Geometry.prototype.getVertexBuffer = function (kind) {
  25329. if (!this.isReady()) {
  25330. return null;
  25331. }
  25332. return this._vertexBuffers[kind];
  25333. };
  25334. Geometry.prototype.getVertexBuffers = function () {
  25335. if (!this.isReady()) {
  25336. return null;
  25337. }
  25338. return this._vertexBuffers;
  25339. };
  25340. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25341. if (!this._vertexBuffers) {
  25342. if (this._delayInfo) {
  25343. return this._delayInfo.indexOf(kind) !== -1;
  25344. }
  25345. return false;
  25346. }
  25347. return this._vertexBuffers[kind] !== undefined;
  25348. };
  25349. Geometry.prototype.getVerticesDataKinds = function () {
  25350. var result = [];
  25351. if (!this._vertexBuffers && this._delayInfo) {
  25352. for (var kind in this._delayInfo) {
  25353. result.push(kind);
  25354. }
  25355. }
  25356. else {
  25357. for (kind in this._vertexBuffers) {
  25358. result.push(kind);
  25359. }
  25360. }
  25361. return result;
  25362. };
  25363. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25364. if (this._indexBuffer) {
  25365. this._engine._releaseBuffer(this._indexBuffer);
  25366. }
  25367. this._indices = indices;
  25368. if (this._meshes.length !== 0 && this._indices) {
  25369. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25370. }
  25371. if (totalVertices !== undefined) {
  25372. this._totalVertices = totalVertices;
  25373. }
  25374. var meshes = this._meshes;
  25375. var numOfMeshes = meshes.length;
  25376. for (var index = 0; index < numOfMeshes; index++) {
  25377. meshes[index]._createGlobalSubMesh();
  25378. }
  25379. };
  25380. Geometry.prototype.getTotalIndices = function () {
  25381. if (!this.isReady()) {
  25382. return 0;
  25383. }
  25384. return this._indices.length;
  25385. };
  25386. Geometry.prototype.getIndices = function () {
  25387. if (!this.isReady()) {
  25388. return null;
  25389. }
  25390. return this._indices;
  25391. };
  25392. Geometry.prototype.getIndexBuffer = function () {
  25393. if (!this.isReady()) {
  25394. return null;
  25395. }
  25396. return this._indexBuffer;
  25397. };
  25398. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25399. var meshes = this._meshes;
  25400. var index = meshes.indexOf(mesh);
  25401. if (index === -1) {
  25402. return;
  25403. }
  25404. for (var kind in this._vertexBuffers) {
  25405. this._vertexBuffers[kind].dispose();
  25406. }
  25407. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25408. this._indexBuffer = null;
  25409. }
  25410. meshes.splice(index, 1);
  25411. mesh._geometry = null;
  25412. if (meshes.length === 0 && shouldDispose) {
  25413. this.dispose();
  25414. }
  25415. };
  25416. Geometry.prototype.applyToMesh = function (mesh) {
  25417. if (mesh._geometry === this) {
  25418. return;
  25419. }
  25420. var previousGeometry = mesh._geometry;
  25421. if (previousGeometry) {
  25422. previousGeometry.releaseForMesh(mesh);
  25423. }
  25424. var meshes = this._meshes;
  25425. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25426. mesh._geometry = this;
  25427. this._scene.pushGeometry(this);
  25428. meshes.push(mesh);
  25429. if (this.isReady()) {
  25430. this._applyToMesh(mesh);
  25431. }
  25432. else {
  25433. mesh._boundingInfo = this._boundingInfo;
  25434. }
  25435. };
  25436. Geometry.prototype._applyToMesh = function (mesh) {
  25437. var numOfMeshes = this._meshes.length;
  25438. for (var kind in this._vertexBuffers) {
  25439. if (numOfMeshes === 1) {
  25440. this._vertexBuffers[kind].create();
  25441. }
  25442. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25443. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25444. mesh._resetPointsArrayCache();
  25445. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25446. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25447. mesh._createGlobalSubMesh();
  25448. //bounding info was just created again, world matrix should be applied again.
  25449. mesh._updateBoundingInfo();
  25450. }
  25451. }
  25452. // indexBuffer
  25453. if (numOfMeshes === 1 && this._indices) {
  25454. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25455. }
  25456. if (this._indexBuffer) {
  25457. this._indexBuffer.references = numOfMeshes;
  25458. }
  25459. };
  25460. Geometry.prototype.load = function (scene, onLoaded) {
  25461. var _this = this;
  25462. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25463. return;
  25464. }
  25465. if (this.isReady()) {
  25466. if (onLoaded) {
  25467. onLoaded();
  25468. }
  25469. return;
  25470. }
  25471. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25472. scene._addPendingData(this);
  25473. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25474. _this._delayLoadingFunction(JSON.parse(data), _this);
  25475. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25476. _this._delayInfo = [];
  25477. scene._removePendingData(_this);
  25478. var meshes = _this._meshes;
  25479. var numOfMeshes = meshes.length;
  25480. for (var index = 0; index < numOfMeshes; index++) {
  25481. _this._applyToMesh(meshes[index]);
  25482. }
  25483. if (onLoaded) {
  25484. onLoaded();
  25485. }
  25486. }, function () {
  25487. }, scene.database);
  25488. };
  25489. Geometry.prototype.isDisposed = function () {
  25490. return this._isDisposed;
  25491. };
  25492. Geometry.prototype.dispose = function () {
  25493. var meshes = this._meshes;
  25494. var numOfMeshes = meshes.length;
  25495. var index;
  25496. for (index = 0; index < numOfMeshes; index++) {
  25497. this.releaseForMesh(meshes[index]);
  25498. }
  25499. this._meshes = [];
  25500. for (var kind in this._vertexBuffers) {
  25501. this._vertexBuffers[kind].dispose();
  25502. }
  25503. this._vertexBuffers = [];
  25504. this._totalVertices = 0;
  25505. if (this._indexBuffer) {
  25506. this._engine._releaseBuffer(this._indexBuffer);
  25507. }
  25508. this._indexBuffer = null;
  25509. this._indices = [];
  25510. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25511. this.delayLoadingFile = null;
  25512. this._delayLoadingFunction = null;
  25513. this._delayInfo = [];
  25514. this._boundingInfo = null; // todo: .dispose()
  25515. var geometries = this._scene.getGeometries();
  25516. index = geometries.indexOf(this);
  25517. if (index > -1) {
  25518. geometries.splice(index, 1);
  25519. }
  25520. this._isDisposed = true;
  25521. };
  25522. Geometry.prototype.copy = function (id) {
  25523. var vertexData = new BABYLON.VertexData();
  25524. vertexData.indices = [];
  25525. var indices = this.getIndices();
  25526. for (var index = 0; index < indices.length; index++) {
  25527. vertexData.indices.push(indices[index]);
  25528. }
  25529. var updatable = false;
  25530. var stopChecking = false;
  25531. for (var kind in this._vertexBuffers) {
  25532. // using slice() to make a copy of the array and not just reference it
  25533. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25534. if (!stopChecking) {
  25535. updatable = this.getVertexBuffer(kind).isUpdatable();
  25536. stopChecking = !updatable;
  25537. }
  25538. }
  25539. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25540. geometry.delayLoadState = this.delayLoadState;
  25541. geometry.delayLoadingFile = this.delayLoadingFile;
  25542. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25543. for (kind in this._delayInfo) {
  25544. geometry._delayInfo = geometry._delayInfo || [];
  25545. geometry._delayInfo.push(kind);
  25546. }
  25547. // Bounding info
  25548. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25549. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25550. return geometry;
  25551. };
  25552. // Statics
  25553. Geometry.ExtractFromMesh = function (mesh, id) {
  25554. var geometry = mesh._geometry;
  25555. if (!geometry) {
  25556. return null;
  25557. }
  25558. return geometry.copy(id);
  25559. };
  25560. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25561. // be aware Math.random() could cause collisions
  25562. Geometry.RandomId = function () {
  25563. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25564. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25565. return v.toString(16);
  25566. });
  25567. };
  25568. return Geometry;
  25569. })();
  25570. BABYLON.Geometry = Geometry;
  25571. /////// Primitives //////////////////////////////////////////////
  25572. var Geometry;
  25573. (function (Geometry) {
  25574. var Primitives;
  25575. (function (Primitives) {
  25576. /// Abstract class
  25577. var _Primitive = (function (_super) {
  25578. __extends(_Primitive, _super);
  25579. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25580. this._beingRegenerated = true;
  25581. this._canBeRegenerated = canBeRegenerated;
  25582. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25583. this._beingRegenerated = false;
  25584. }
  25585. _Primitive.prototype.canBeRegenerated = function () {
  25586. return this._canBeRegenerated;
  25587. };
  25588. _Primitive.prototype.regenerate = function () {
  25589. if (!this._canBeRegenerated) {
  25590. return;
  25591. }
  25592. this._beingRegenerated = true;
  25593. this.setAllVerticesData(this._regenerateVertexData(), false);
  25594. this._beingRegenerated = false;
  25595. };
  25596. _Primitive.prototype.asNewGeometry = function (id) {
  25597. return _super.prototype.copy.call(this, id);
  25598. };
  25599. // overrides
  25600. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25601. if (!this._beingRegenerated) {
  25602. return;
  25603. }
  25604. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25605. };
  25606. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25607. if (!this._beingRegenerated) {
  25608. return;
  25609. }
  25610. _super.prototype.setVerticesData.call(this, kind, data, false);
  25611. };
  25612. // to override
  25613. // protected
  25614. _Primitive.prototype._regenerateVertexData = function () {
  25615. throw new Error("Abstract method");
  25616. };
  25617. _Primitive.prototype.copy = function (id) {
  25618. throw new Error("Must be overriden in sub-classes.");
  25619. };
  25620. return _Primitive;
  25621. })(Geometry);
  25622. Primitives._Primitive = _Primitive;
  25623. var Ribbon = (function (_super) {
  25624. __extends(Ribbon, _super);
  25625. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25626. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25627. this.pathArray = pathArray;
  25628. this.closeArray = closeArray;
  25629. this.closePath = closePath;
  25630. this.offset = offset;
  25631. this.side = side;
  25632. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25633. }
  25634. Ribbon.prototype._regenerateVertexData = function () {
  25635. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25636. };
  25637. Ribbon.prototype.copy = function (id) {
  25638. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25639. };
  25640. return Ribbon;
  25641. })(_Primitive);
  25642. Primitives.Ribbon = Ribbon;
  25643. var Box = (function (_super) {
  25644. __extends(Box, _super);
  25645. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25646. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25647. this.size = size;
  25648. this.side = side;
  25649. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25650. }
  25651. Box.prototype._regenerateVertexData = function () {
  25652. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25653. };
  25654. Box.prototype.copy = function (id) {
  25655. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25656. };
  25657. return Box;
  25658. })(_Primitive);
  25659. Primitives.Box = Box;
  25660. var Sphere = (function (_super) {
  25661. __extends(Sphere, _super);
  25662. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25663. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25664. this.segments = segments;
  25665. this.diameter = diameter;
  25666. this.side = side;
  25667. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25668. }
  25669. Sphere.prototype._regenerateVertexData = function () {
  25670. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25671. };
  25672. Sphere.prototype.copy = function (id) {
  25673. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25674. };
  25675. return Sphere;
  25676. })(_Primitive);
  25677. Primitives.Sphere = Sphere;
  25678. var Cylinder = (function (_super) {
  25679. __extends(Cylinder, _super);
  25680. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25681. if (subdivisions === void 0) { subdivisions = 1; }
  25682. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25683. this.height = height;
  25684. this.diameterTop = diameterTop;
  25685. this.diameterBottom = diameterBottom;
  25686. this.tessellation = tessellation;
  25687. this.subdivisions = subdivisions;
  25688. this.side = side;
  25689. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25690. }
  25691. Cylinder.prototype._regenerateVertexData = function () {
  25692. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25693. };
  25694. Cylinder.prototype.copy = function (id) {
  25695. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25696. };
  25697. return Cylinder;
  25698. })(_Primitive);
  25699. Primitives.Cylinder = Cylinder;
  25700. var Torus = (function (_super) {
  25701. __extends(Torus, _super);
  25702. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25703. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25704. this.diameter = diameter;
  25705. this.thickness = thickness;
  25706. this.tessellation = tessellation;
  25707. this.side = side;
  25708. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25709. }
  25710. Torus.prototype._regenerateVertexData = function () {
  25711. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25712. };
  25713. Torus.prototype.copy = function (id) {
  25714. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25715. };
  25716. return Torus;
  25717. })(_Primitive);
  25718. Primitives.Torus = Torus;
  25719. var Ground = (function (_super) {
  25720. __extends(Ground, _super);
  25721. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25722. this.width = width;
  25723. this.height = height;
  25724. this.subdivisions = subdivisions;
  25725. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25726. }
  25727. Ground.prototype._regenerateVertexData = function () {
  25728. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25729. };
  25730. Ground.prototype.copy = function (id) {
  25731. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25732. };
  25733. return Ground;
  25734. })(_Primitive);
  25735. Primitives.Ground = Ground;
  25736. var TiledGround = (function (_super) {
  25737. __extends(TiledGround, _super);
  25738. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25739. this.xmin = xmin;
  25740. this.zmin = zmin;
  25741. this.xmax = xmax;
  25742. this.zmax = zmax;
  25743. this.subdivisions = subdivisions;
  25744. this.precision = precision;
  25745. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25746. }
  25747. TiledGround.prototype._regenerateVertexData = function () {
  25748. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25749. };
  25750. TiledGround.prototype.copy = function (id) {
  25751. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25752. };
  25753. return TiledGround;
  25754. })(_Primitive);
  25755. Primitives.TiledGround = TiledGround;
  25756. var Plane = (function (_super) {
  25757. __extends(Plane, _super);
  25758. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25759. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25760. this.size = size;
  25761. this.side = side;
  25762. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25763. }
  25764. Plane.prototype._regenerateVertexData = function () {
  25765. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25766. };
  25767. Plane.prototype.copy = function (id) {
  25768. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25769. };
  25770. return Plane;
  25771. })(_Primitive);
  25772. Primitives.Plane = Plane;
  25773. var TorusKnot = (function (_super) {
  25774. __extends(TorusKnot, _super);
  25775. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25776. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25777. this.radius = radius;
  25778. this.tube = tube;
  25779. this.radialSegments = radialSegments;
  25780. this.tubularSegments = tubularSegments;
  25781. this.p = p;
  25782. this.q = q;
  25783. this.side = side;
  25784. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25785. }
  25786. TorusKnot.prototype._regenerateVertexData = function () {
  25787. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25788. };
  25789. TorusKnot.prototype.copy = function (id) {
  25790. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25791. };
  25792. return TorusKnot;
  25793. })(_Primitive);
  25794. Primitives.TorusKnot = TorusKnot;
  25795. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25796. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25797. })(BABYLON || (BABYLON = {}));
  25798. //# sourceMappingURL=babylon.geometry.js.map
  25799. var BABYLON;
  25800. (function (BABYLON) {
  25801. var Gamepads = (function () {
  25802. function Gamepads(ongamedpadconnected) {
  25803. var _this = this;
  25804. this.babylonGamepads = [];
  25805. this.oneGamepadConnected = false;
  25806. this.isMonitoring = false;
  25807. this.gamepadEventSupported = 'GamepadEvent' in window;
  25808. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25809. 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=";
  25810. this._callbackGamepadConnected = ongamedpadconnected;
  25811. if (this.gamepadSupportAvailable) {
  25812. // Checking if the gamepad connected event is supported (like in Firefox)
  25813. if (this.gamepadEventSupported) {
  25814. window.addEventListener('gamepadconnected', function (evt) {
  25815. _this._onGamepadConnected(evt);
  25816. }, false);
  25817. window.addEventListener('gamepaddisconnected', function (evt) {
  25818. _this._onGamepadDisconnected(evt);
  25819. }, false);
  25820. }
  25821. else {
  25822. this._startMonitoringGamepads();
  25823. }
  25824. if (!this.oneGamepadConnected) {
  25825. this._insertGamepadDOMInstructions();
  25826. }
  25827. }
  25828. else {
  25829. this._insertGamepadDOMNotSupported();
  25830. }
  25831. }
  25832. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25833. Gamepads.gamepadDOMInfo = document.createElement("div");
  25834. var buttonAImage = document.createElement("img");
  25835. buttonAImage.src = this.buttonADataURL;
  25836. var spanMessage = document.createElement("span");
  25837. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25838. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25839. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25840. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25841. Gamepads.gamepadDOMInfo.style.width = "100%";
  25842. Gamepads.gamepadDOMInfo.style.height = "48px";
  25843. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25844. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25845. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25846. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25847. buttonAImage.style.position = "relative";
  25848. buttonAImage.style.bottom = "8px";
  25849. spanMessage.style.position = "relative";
  25850. spanMessage.style.fontSize = "32px";
  25851. spanMessage.style.bottom = "32px";
  25852. spanMessage.style.color = "green";
  25853. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25854. };
  25855. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25856. Gamepads.gamepadDOMInfo = document.createElement("div");
  25857. var spanMessage = document.createElement("span");
  25858. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25859. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25860. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25861. Gamepads.gamepadDOMInfo.style.width = "100%";
  25862. Gamepads.gamepadDOMInfo.style.height = "40px";
  25863. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25864. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25865. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25866. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25867. spanMessage.style.position = "relative";
  25868. spanMessage.style.fontSize = "32px";
  25869. spanMessage.style.color = "red";
  25870. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25871. };
  25872. Gamepads.prototype.dispose = function () {
  25873. if (Gamepads.gamepadDOMInfo) {
  25874. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25875. }
  25876. };
  25877. Gamepads.prototype._onGamepadConnected = function (evt) {
  25878. var newGamepad = this._addNewGamepad(evt.gamepad);
  25879. if (this._callbackGamepadConnected)
  25880. this._callbackGamepadConnected(newGamepad);
  25881. this._startMonitoringGamepads();
  25882. };
  25883. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25884. if (!this.oneGamepadConnected) {
  25885. this.oneGamepadConnected = true;
  25886. if (Gamepads.gamepadDOMInfo) {
  25887. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25888. Gamepads.gamepadDOMInfo = null;
  25889. }
  25890. }
  25891. var newGamepad;
  25892. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25893. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25894. }
  25895. else {
  25896. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25897. }
  25898. this.babylonGamepads.push(newGamepad);
  25899. return newGamepad;
  25900. };
  25901. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25902. for (var i in this.babylonGamepads) {
  25903. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25904. this.babylonGamepads.splice(i, 1);
  25905. break;
  25906. }
  25907. }
  25908. // If no gamepads are left, stop the polling loop.
  25909. if (this.babylonGamepads.length == 0) {
  25910. this._stopMonitoringGamepads();
  25911. }
  25912. };
  25913. Gamepads.prototype._startMonitoringGamepads = function () {
  25914. if (!this.isMonitoring) {
  25915. this.isMonitoring = true;
  25916. this._checkGamepadsStatus();
  25917. }
  25918. };
  25919. Gamepads.prototype._stopMonitoringGamepads = function () {
  25920. this.isMonitoring = false;
  25921. };
  25922. Gamepads.prototype._checkGamepadsStatus = function () {
  25923. var _this = this;
  25924. // updating gamepad objects
  25925. this._updateGamepadObjects();
  25926. for (var i in this.babylonGamepads) {
  25927. this.babylonGamepads[i].update();
  25928. }
  25929. if (this.isMonitoring) {
  25930. if (window.requestAnimationFrame) {
  25931. window.requestAnimationFrame(function () {
  25932. _this._checkGamepadsStatus();
  25933. });
  25934. }
  25935. else if (window.mozRequestAnimationFrame) {
  25936. window.mozRequestAnimationFrame(function () {
  25937. _this._checkGamepadsStatus();
  25938. });
  25939. }
  25940. else if (window.webkitRequestAnimationFrame) {
  25941. window.webkitRequestAnimationFrame(function () {
  25942. _this._checkGamepadsStatus();
  25943. });
  25944. }
  25945. }
  25946. };
  25947. // This function is called only on Chrome, which does not yet support
  25948. // connection/disconnection events, but requires you to monitor
  25949. // an array for changes.
  25950. Gamepads.prototype._updateGamepadObjects = function () {
  25951. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25952. for (var i = 0; i < gamepads.length; i++) {
  25953. if (gamepads[i]) {
  25954. if (!(gamepads[i].index in this.babylonGamepads)) {
  25955. var newGamepad = this._addNewGamepad(gamepads[i]);
  25956. if (this._callbackGamepadConnected) {
  25957. this._callbackGamepadConnected(newGamepad);
  25958. }
  25959. }
  25960. else {
  25961. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25962. }
  25963. }
  25964. }
  25965. };
  25966. return Gamepads;
  25967. })();
  25968. BABYLON.Gamepads = Gamepads;
  25969. var StickValues = (function () {
  25970. function StickValues(x, y) {
  25971. this.x = x;
  25972. this.y = y;
  25973. }
  25974. return StickValues;
  25975. })();
  25976. BABYLON.StickValues = StickValues;
  25977. var Gamepad = (function () {
  25978. function Gamepad(id, index, browserGamepad) {
  25979. this.id = id;
  25980. this.index = index;
  25981. this.browserGamepad = browserGamepad;
  25982. if (this.browserGamepad.axes.length >= 2) {
  25983. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25984. }
  25985. if (this.browserGamepad.axes.length >= 4) {
  25986. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25987. }
  25988. }
  25989. Gamepad.prototype.onleftstickchanged = function (callback) {
  25990. this._onleftstickchanged = callback;
  25991. };
  25992. Gamepad.prototype.onrightstickchanged = function (callback) {
  25993. this._onrightstickchanged = callback;
  25994. };
  25995. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25996. get: function () {
  25997. return this._leftStick;
  25998. },
  25999. set: function (newValues) {
  26000. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  26001. this._onleftstickchanged(newValues);
  26002. }
  26003. this._leftStick = newValues;
  26004. },
  26005. enumerable: true,
  26006. configurable: true
  26007. });
  26008. Object.defineProperty(Gamepad.prototype, "rightStick", {
  26009. get: function () {
  26010. return this._rightStick;
  26011. },
  26012. set: function (newValues) {
  26013. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  26014. this._onrightstickchanged(newValues);
  26015. }
  26016. this._rightStick = newValues;
  26017. },
  26018. enumerable: true,
  26019. configurable: true
  26020. });
  26021. Gamepad.prototype.update = function () {
  26022. if (this._leftStick) {
  26023. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26024. }
  26025. if (this._rightStick) {
  26026. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26027. }
  26028. };
  26029. return Gamepad;
  26030. })();
  26031. BABYLON.Gamepad = Gamepad;
  26032. var GenericPad = (function (_super) {
  26033. __extends(GenericPad, _super);
  26034. function GenericPad(id, index, gamepad) {
  26035. _super.call(this, id, index, gamepad);
  26036. this.id = id;
  26037. this.index = index;
  26038. this.gamepad = gamepad;
  26039. this._buttons = new Array(gamepad.buttons.length);
  26040. }
  26041. GenericPad.prototype.onbuttondown = function (callback) {
  26042. this._onbuttondown = callback;
  26043. };
  26044. GenericPad.prototype.onbuttonup = function (callback) {
  26045. this._onbuttonup = callback;
  26046. };
  26047. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  26048. if (newValue !== currentValue) {
  26049. if (this._onbuttondown && newValue === 1) {
  26050. this._onbuttondown(buttonIndex);
  26051. }
  26052. if (this._onbuttonup && newValue === 0) {
  26053. this._onbuttonup(buttonIndex);
  26054. }
  26055. }
  26056. return newValue;
  26057. };
  26058. GenericPad.prototype.update = function () {
  26059. _super.prototype.update.call(this);
  26060. for (var index = 0; index < this._buttons.length; index++) {
  26061. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  26062. }
  26063. };
  26064. return GenericPad;
  26065. })(Gamepad);
  26066. BABYLON.GenericPad = GenericPad;
  26067. (function (Xbox360Button) {
  26068. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  26069. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  26070. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  26071. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  26072. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  26073. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  26074. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  26075. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  26076. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  26077. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  26078. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  26079. var Xbox360Button = BABYLON.Xbox360Button;
  26080. (function (Xbox360Dpad) {
  26081. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  26082. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  26083. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  26084. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  26085. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  26086. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  26087. var Xbox360Pad = (function (_super) {
  26088. __extends(Xbox360Pad, _super);
  26089. function Xbox360Pad() {
  26090. _super.apply(this, arguments);
  26091. this._leftTrigger = 0;
  26092. this._rightTrigger = 0;
  26093. this._buttonA = 0;
  26094. this._buttonB = 0;
  26095. this._buttonX = 0;
  26096. this._buttonY = 0;
  26097. this._buttonBack = 0;
  26098. this._buttonStart = 0;
  26099. this._buttonLB = 0;
  26100. this._buttonRB = 0;
  26101. this._buttonLeftStick = 0;
  26102. this._buttonRightStick = 0;
  26103. this._dPadUp = 0;
  26104. this._dPadDown = 0;
  26105. this._dPadLeft = 0;
  26106. this._dPadRight = 0;
  26107. }
  26108. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  26109. this._onlefttriggerchanged = callback;
  26110. };
  26111. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  26112. this._onrighttriggerchanged = callback;
  26113. };
  26114. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  26115. get: function () {
  26116. return this._leftTrigger;
  26117. },
  26118. set: function (newValue) {
  26119. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  26120. this._onlefttriggerchanged(newValue);
  26121. }
  26122. this._leftTrigger = newValue;
  26123. },
  26124. enumerable: true,
  26125. configurable: true
  26126. });
  26127. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  26128. get: function () {
  26129. return this._rightTrigger;
  26130. },
  26131. set: function (newValue) {
  26132. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  26133. this._onrighttriggerchanged(newValue);
  26134. }
  26135. this._rightTrigger = newValue;
  26136. },
  26137. enumerable: true,
  26138. configurable: true
  26139. });
  26140. Xbox360Pad.prototype.onbuttondown = function (callback) {
  26141. this._onbuttondown = callback;
  26142. };
  26143. Xbox360Pad.prototype.onbuttonup = function (callback) {
  26144. this._onbuttonup = callback;
  26145. };
  26146. Xbox360Pad.prototype.ondpaddown = function (callback) {
  26147. this._ondpaddown = callback;
  26148. };
  26149. Xbox360Pad.prototype.ondpadup = function (callback) {
  26150. this._ondpadup = callback;
  26151. };
  26152. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  26153. if (newValue !== currentValue) {
  26154. if (this._onbuttondown && newValue === 1) {
  26155. this._onbuttondown(buttonType);
  26156. }
  26157. if (this._onbuttonup && newValue === 0) {
  26158. this._onbuttonup(buttonType);
  26159. }
  26160. }
  26161. return newValue;
  26162. };
  26163. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  26164. if (newValue !== currentValue) {
  26165. if (this._ondpaddown && newValue === 1) {
  26166. this._ondpaddown(buttonType);
  26167. }
  26168. if (this._ondpadup && newValue === 0) {
  26169. this._ondpadup(buttonType);
  26170. }
  26171. }
  26172. return newValue;
  26173. };
  26174. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  26175. get: function () {
  26176. return this._buttonA;
  26177. },
  26178. set: function (value) {
  26179. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  26180. },
  26181. enumerable: true,
  26182. configurable: true
  26183. });
  26184. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  26185. get: function () {
  26186. return this._buttonB;
  26187. },
  26188. set: function (value) {
  26189. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  26190. },
  26191. enumerable: true,
  26192. configurable: true
  26193. });
  26194. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  26195. get: function () {
  26196. return this._buttonX;
  26197. },
  26198. set: function (value) {
  26199. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  26200. },
  26201. enumerable: true,
  26202. configurable: true
  26203. });
  26204. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  26205. get: function () {
  26206. return this._buttonY;
  26207. },
  26208. set: function (value) {
  26209. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  26210. },
  26211. enumerable: true,
  26212. configurable: true
  26213. });
  26214. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  26215. get: function () {
  26216. return this._buttonStart;
  26217. },
  26218. set: function (value) {
  26219. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  26220. },
  26221. enumerable: true,
  26222. configurable: true
  26223. });
  26224. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  26225. get: function () {
  26226. return this._buttonBack;
  26227. },
  26228. set: function (value) {
  26229. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  26230. },
  26231. enumerable: true,
  26232. configurable: true
  26233. });
  26234. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  26235. get: function () {
  26236. return this._buttonLB;
  26237. },
  26238. set: function (value) {
  26239. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  26240. },
  26241. enumerable: true,
  26242. configurable: true
  26243. });
  26244. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  26245. get: function () {
  26246. return this._buttonRB;
  26247. },
  26248. set: function (value) {
  26249. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  26250. },
  26251. enumerable: true,
  26252. configurable: true
  26253. });
  26254. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  26255. get: function () {
  26256. return this._buttonLeftStick;
  26257. },
  26258. set: function (value) {
  26259. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  26260. },
  26261. enumerable: true,
  26262. configurable: true
  26263. });
  26264. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  26265. get: function () {
  26266. return this._buttonRightStick;
  26267. },
  26268. set: function (value) {
  26269. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  26270. },
  26271. enumerable: true,
  26272. configurable: true
  26273. });
  26274. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  26275. get: function () {
  26276. return this._dPadUp;
  26277. },
  26278. set: function (value) {
  26279. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  26280. },
  26281. enumerable: true,
  26282. configurable: true
  26283. });
  26284. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  26285. get: function () {
  26286. return this._dPadDown;
  26287. },
  26288. set: function (value) {
  26289. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  26290. },
  26291. enumerable: true,
  26292. configurable: true
  26293. });
  26294. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  26295. get: function () {
  26296. return this._dPadLeft;
  26297. },
  26298. set: function (value) {
  26299. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  26300. },
  26301. enumerable: true,
  26302. configurable: true
  26303. });
  26304. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  26305. get: function () {
  26306. return this._dPadRight;
  26307. },
  26308. set: function (value) {
  26309. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  26310. },
  26311. enumerable: true,
  26312. configurable: true
  26313. });
  26314. Xbox360Pad.prototype.update = function () {
  26315. _super.prototype.update.call(this);
  26316. this.buttonA = this.browserGamepad.buttons[0].value;
  26317. this.buttonB = this.browserGamepad.buttons[1].value;
  26318. this.buttonX = this.browserGamepad.buttons[2].value;
  26319. this.buttonY = this.browserGamepad.buttons[3].value;
  26320. this.buttonLB = this.browserGamepad.buttons[4].value;
  26321. this.buttonRB = this.browserGamepad.buttons[5].value;
  26322. this.leftTrigger = this.browserGamepad.buttons[6].value;
  26323. this.rightTrigger = this.browserGamepad.buttons[7].value;
  26324. this.buttonBack = this.browserGamepad.buttons[8].value;
  26325. this.buttonStart = this.browserGamepad.buttons[9].value;
  26326. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  26327. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  26328. this.dPadUp = this.browserGamepad.buttons[12].value;
  26329. this.dPadDown = this.browserGamepad.buttons[13].value;
  26330. this.dPadLeft = this.browserGamepad.buttons[14].value;
  26331. this.dPadRight = this.browserGamepad.buttons[15].value;
  26332. };
  26333. return Xbox360Pad;
  26334. })(Gamepad);
  26335. BABYLON.Xbox360Pad = Xbox360Pad;
  26336. })(BABYLON || (BABYLON = {}));
  26337. //# sourceMappingURL=babylon.gamepads.js.map
  26338. var BABYLON;
  26339. (function (BABYLON) {
  26340. // We're mainly based on the logic defined into the FreeCamera code
  26341. var GamepadCamera = (function (_super) {
  26342. __extends(GamepadCamera, _super);
  26343. function GamepadCamera(name, position, scene) {
  26344. var _this = this;
  26345. _super.call(this, name, position, scene);
  26346. this.angularSensibility = 200;
  26347. this.moveSensibility = 75;
  26348. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26349. _this._onNewGameConnected(gamepad);
  26350. });
  26351. }
  26352. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26353. // Only the first gamepad can control the camera
  26354. if (gamepad.index === 0) {
  26355. this._gamepad = gamepad;
  26356. }
  26357. };
  26358. GamepadCamera.prototype._checkInputs = function () {
  26359. if (!this._gamepad) {
  26360. return;
  26361. }
  26362. var LSValues = this._gamepad.leftStick;
  26363. var normalizedLX = LSValues.x / this.moveSensibility;
  26364. var normalizedLY = LSValues.y / this.moveSensibility;
  26365. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26366. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26367. var RSValues = this._gamepad.rightStick;
  26368. var normalizedRX = RSValues.x / this.angularSensibility;
  26369. var normalizedRY = RSValues.y / this.angularSensibility;
  26370. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26371. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26372. ;
  26373. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26374. var speed = this._computeLocalCameraSpeed() * 50.0;
  26375. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26376. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26377. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26378. };
  26379. GamepadCamera.prototype.dispose = function () {
  26380. this._gamepads.dispose();
  26381. _super.prototype.dispose.call(this);
  26382. };
  26383. return GamepadCamera;
  26384. })(BABYLON.FreeCamera);
  26385. BABYLON.GamepadCamera = GamepadCamera;
  26386. })(BABYLON || (BABYLON = {}));
  26387. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26388. var BABYLON;
  26389. (function (BABYLON) {
  26390. var LinesMesh = (function (_super) {
  26391. __extends(LinesMesh, _super);
  26392. function LinesMesh(name, scene, updatable) {
  26393. if (updatable === void 0) { updatable = false; }
  26394. _super.call(this, name, scene);
  26395. this.color = new BABYLON.Color3(1, 1, 1);
  26396. this.alpha = 1;
  26397. this._indices = new Array();
  26398. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26399. attributes: ["position"],
  26400. uniforms: ["worldViewProjection", "color"],
  26401. needAlphaBlending: true
  26402. });
  26403. }
  26404. Object.defineProperty(LinesMesh.prototype, "material", {
  26405. get: function () {
  26406. return this._colorShader;
  26407. },
  26408. enumerable: true,
  26409. configurable: true
  26410. });
  26411. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26412. get: function () {
  26413. return false;
  26414. },
  26415. enumerable: true,
  26416. configurable: true
  26417. });
  26418. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26419. get: function () {
  26420. return false;
  26421. },
  26422. enumerable: true,
  26423. configurable: true
  26424. });
  26425. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26426. var engine = this.getScene().getEngine();
  26427. var indexToBind = this._geometry.getIndexBuffer();
  26428. // VBOs
  26429. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26430. // Color
  26431. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26432. };
  26433. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26434. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26435. return;
  26436. }
  26437. var engine = this.getScene().getEngine();
  26438. // Draw order
  26439. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26440. };
  26441. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26442. return null;
  26443. };
  26444. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26445. this._colorShader.dispose();
  26446. _super.prototype.dispose.call(this, doNotRecurse);
  26447. };
  26448. return LinesMesh;
  26449. })(BABYLON.Mesh);
  26450. BABYLON.LinesMesh = LinesMesh;
  26451. })(BABYLON || (BABYLON = {}));
  26452. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26453. (function (BABYLON) {
  26454. var OutlineRenderer = (function () {
  26455. function OutlineRenderer(scene) {
  26456. this._scene = scene;
  26457. }
  26458. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26459. var _this = this;
  26460. if (useOverlay === void 0) { useOverlay = false; }
  26461. var scene = this._scene;
  26462. var engine = this._scene.getEngine();
  26463. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26464. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26465. return;
  26466. }
  26467. var mesh = subMesh.getRenderingMesh();
  26468. var material = subMesh.getMaterial();
  26469. engine.enableEffect(this._effect);
  26470. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26471. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26472. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26473. // Bones
  26474. if (mesh.useBones) {
  26475. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26476. }
  26477. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26478. // Alpha test
  26479. if (material && material.needAlphaTesting()) {
  26480. var alphaTexture = material.getAlphaTestTexture();
  26481. this._effect.setTexture("diffuseSampler", alphaTexture);
  26482. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26483. }
  26484. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26485. _this._effect.setMatrix("world", world);
  26486. });
  26487. };
  26488. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26489. var defines = [];
  26490. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26491. var mesh = subMesh.getMesh();
  26492. var material = subMesh.getMaterial();
  26493. // Alpha test
  26494. if (material && material.needAlphaTesting()) {
  26495. defines.push("#define ALPHATEST");
  26496. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26497. attribs.push(BABYLON.VertexBuffer.UVKind);
  26498. defines.push("#define UV1");
  26499. }
  26500. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26501. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26502. defines.push("#define UV2");
  26503. }
  26504. }
  26505. // Bones
  26506. if (mesh.useBones) {
  26507. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26508. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26509. defines.push("#define BONES");
  26510. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26511. }
  26512. // Instances
  26513. if (useInstances) {
  26514. defines.push("#define INSTANCES");
  26515. attribs.push("world0");
  26516. attribs.push("world1");
  26517. attribs.push("world2");
  26518. attribs.push("world3");
  26519. }
  26520. // Get correct effect
  26521. var join = defines.join("\n");
  26522. if (this._cachedDefines !== join) {
  26523. this._cachedDefines = join;
  26524. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26525. }
  26526. return this._effect.isReady();
  26527. };
  26528. return OutlineRenderer;
  26529. })();
  26530. BABYLON.OutlineRenderer = OutlineRenderer;
  26531. })(BABYLON || (BABYLON = {}));
  26532. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26533. (function (BABYLON) {
  26534. var MeshAssetTask = (function () {
  26535. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26536. this.name = name;
  26537. this.meshesNames = meshesNames;
  26538. this.rootUrl = rootUrl;
  26539. this.sceneFilename = sceneFilename;
  26540. this.isCompleted = false;
  26541. }
  26542. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26543. var _this = this;
  26544. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26545. _this.loadedMeshes = meshes;
  26546. _this.loadedParticleSystems = particleSystems;
  26547. _this.loadedSkeletons = skeletons;
  26548. _this.isCompleted = true;
  26549. if (_this.onSuccess) {
  26550. _this.onSuccess(_this);
  26551. }
  26552. onSuccess();
  26553. }, null, function () {
  26554. if (_this.onError) {
  26555. _this.onError(_this);
  26556. }
  26557. onError();
  26558. });
  26559. };
  26560. return MeshAssetTask;
  26561. })();
  26562. BABYLON.MeshAssetTask = MeshAssetTask;
  26563. var TextFileAssetTask = (function () {
  26564. function TextFileAssetTask(name, url) {
  26565. this.name = name;
  26566. this.url = url;
  26567. this.isCompleted = false;
  26568. }
  26569. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26570. var _this = this;
  26571. BABYLON.Tools.LoadFile(this.url, function (data) {
  26572. _this.text = data;
  26573. _this.isCompleted = true;
  26574. if (_this.onSuccess) {
  26575. _this.onSuccess(_this);
  26576. }
  26577. onSuccess();
  26578. }, null, scene.database, false, function () {
  26579. if (_this.onError) {
  26580. _this.onError(_this);
  26581. }
  26582. onError();
  26583. });
  26584. };
  26585. return TextFileAssetTask;
  26586. })();
  26587. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26588. var BinaryFileAssetTask = (function () {
  26589. function BinaryFileAssetTask(name, url) {
  26590. this.name = name;
  26591. this.url = url;
  26592. this.isCompleted = false;
  26593. }
  26594. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26595. var _this = this;
  26596. BABYLON.Tools.LoadFile(this.url, function (data) {
  26597. _this.data = data;
  26598. _this.isCompleted = true;
  26599. if (_this.onSuccess) {
  26600. _this.onSuccess(_this);
  26601. }
  26602. onSuccess();
  26603. }, null, scene.database, true, function () {
  26604. if (_this.onError) {
  26605. _this.onError(_this);
  26606. }
  26607. onError();
  26608. });
  26609. };
  26610. return BinaryFileAssetTask;
  26611. })();
  26612. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26613. var ImageAssetTask = (function () {
  26614. function ImageAssetTask(name, url) {
  26615. this.name = name;
  26616. this.url = url;
  26617. this.isCompleted = false;
  26618. }
  26619. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26620. var _this = this;
  26621. var img = new Image();
  26622. img.onload = function () {
  26623. _this.image = img;
  26624. _this.isCompleted = true;
  26625. if (_this.onSuccess) {
  26626. _this.onSuccess(_this);
  26627. }
  26628. onSuccess();
  26629. };
  26630. img.onerror = function () {
  26631. if (_this.onError) {
  26632. _this.onError(_this);
  26633. }
  26634. onError();
  26635. };
  26636. img.src = this.url;
  26637. };
  26638. return ImageAssetTask;
  26639. })();
  26640. BABYLON.ImageAssetTask = ImageAssetTask;
  26641. var TextureAssetTask = (function () {
  26642. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26644. this.name = name;
  26645. this.url = url;
  26646. this.noMipmap = noMipmap;
  26647. this.invertY = invertY;
  26648. this.samplingMode = samplingMode;
  26649. this.isCompleted = false;
  26650. }
  26651. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26652. var _this = this;
  26653. var onload = function () {
  26654. _this.isCompleted = true;
  26655. if (_this.onSuccess) {
  26656. _this.onSuccess(_this);
  26657. }
  26658. onSuccess();
  26659. };
  26660. var onerror = function () {
  26661. if (_this.onError) {
  26662. _this.onError(_this);
  26663. }
  26664. onError();
  26665. };
  26666. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26667. };
  26668. return TextureAssetTask;
  26669. })();
  26670. BABYLON.TextureAssetTask = TextureAssetTask;
  26671. var AssetsManager = (function () {
  26672. function AssetsManager(scene) {
  26673. this._tasks = new Array();
  26674. this._waitingTasksCount = 0;
  26675. this.useDefaultLoadingScreen = true;
  26676. this._scene = scene;
  26677. }
  26678. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26679. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26680. this._tasks.push(task);
  26681. return task;
  26682. };
  26683. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26684. var task = new TextFileAssetTask(taskName, url);
  26685. this._tasks.push(task);
  26686. return task;
  26687. };
  26688. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26689. var task = new BinaryFileAssetTask(taskName, url);
  26690. this._tasks.push(task);
  26691. return task;
  26692. };
  26693. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26694. var task = new ImageAssetTask(taskName, url);
  26695. this._tasks.push(task);
  26696. return task;
  26697. };
  26698. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26700. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26701. this._tasks.push(task);
  26702. return task;
  26703. };
  26704. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26705. this._waitingTasksCount--;
  26706. if (this._waitingTasksCount === 0) {
  26707. if (this.onFinish) {
  26708. this.onFinish(this._tasks);
  26709. }
  26710. this._scene.getEngine().hideLoadingUI();
  26711. }
  26712. };
  26713. AssetsManager.prototype._runTask = function (task) {
  26714. var _this = this;
  26715. task.run(this._scene, function () {
  26716. if (_this.onTaskSuccess) {
  26717. _this.onTaskSuccess(task);
  26718. }
  26719. _this._decreaseWaitingTasksCount();
  26720. }, function () {
  26721. if (_this.onTaskError) {
  26722. _this.onTaskError(task);
  26723. }
  26724. _this._decreaseWaitingTasksCount();
  26725. });
  26726. };
  26727. AssetsManager.prototype.reset = function () {
  26728. this._tasks = new Array();
  26729. return this;
  26730. };
  26731. AssetsManager.prototype.load = function () {
  26732. this._waitingTasksCount = this._tasks.length;
  26733. if (this._waitingTasksCount === 0) {
  26734. if (this.onFinish) {
  26735. this.onFinish(this._tasks);
  26736. }
  26737. return this;
  26738. }
  26739. if (this.useDefaultLoadingScreen) {
  26740. this._scene.getEngine().displayLoadingUI();
  26741. }
  26742. for (var index = 0; index < this._tasks.length; index++) {
  26743. var task = this._tasks[index];
  26744. this._runTask(task);
  26745. }
  26746. return this;
  26747. };
  26748. return AssetsManager;
  26749. })();
  26750. BABYLON.AssetsManager = AssetsManager;
  26751. })(BABYLON || (BABYLON = {}));
  26752. //# sourceMappingURL=babylon.assetsManager.js.map
  26753. var BABYLON;
  26754. (function (BABYLON) {
  26755. var VRDeviceOrientationCamera = (function (_super) {
  26756. __extends(VRDeviceOrientationCamera, _super);
  26757. function VRDeviceOrientationCamera(name, position, scene) {
  26758. _super.call(this, name, position, scene);
  26759. this._alpha = 0;
  26760. this._beta = 0;
  26761. this._gamma = 0;
  26762. }
  26763. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26764. this._alpha = +evt.alpha | 0;
  26765. this._beta = +evt.beta | 0;
  26766. this._gamma = +evt.gamma | 0;
  26767. if (this._gamma < 0) {
  26768. this._gamma = 90 + this._gamma;
  26769. }
  26770. else {
  26771. // Incline it in the correct angle.
  26772. this._gamma = 270 - this._gamma;
  26773. }
  26774. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26775. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26776. this.rotation.z = this._beta / 180.0 * Math.PI;
  26777. };
  26778. return VRDeviceOrientationCamera;
  26779. })(BABYLON.OculusCamera);
  26780. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26781. })(BABYLON || (BABYLON = {}));
  26782. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26783. var BABYLON;
  26784. (function (BABYLON) {
  26785. var WebVRCamera = (function (_super) {
  26786. __extends(WebVRCamera, _super);
  26787. function WebVRCamera(name, position, scene) {
  26788. _super.call(this, name, position, scene);
  26789. this._hmdDevice = null;
  26790. this._sensorDevice = null;
  26791. this._cacheState = null;
  26792. this._cacheQuaternion = new BABYLON.Quaternion();
  26793. this._cacheRotation = BABYLON.Vector3.Zero();
  26794. this._vrEnabled = false;
  26795. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26796. }
  26797. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26798. var size = devices.length;
  26799. var i = 0;
  26800. // Reset devices.
  26801. this._sensorDevice = null;
  26802. this._hmdDevice = null;
  26803. while (i < size && this._hmdDevice === null) {
  26804. if (devices[i] instanceof HMDVRDevice) {
  26805. this._hmdDevice = devices[i];
  26806. }
  26807. i++;
  26808. }
  26809. i = 0;
  26810. while (i < size && this._sensorDevice === null) {
  26811. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26812. this._sensorDevice = devices[i];
  26813. }
  26814. i++;
  26815. }
  26816. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26817. };
  26818. WebVRCamera.prototype._update = function () {
  26819. if (this._vrEnabled) {
  26820. this._cacheState = this._sensorDevice.getState();
  26821. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26822. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26823. this.rotation.x = -this._cacheRotation.z;
  26824. this.rotation.y = -this._cacheRotation.y;
  26825. this.rotation.z = this._cacheRotation.x;
  26826. }
  26827. _super.prototype._update.call(this);
  26828. };
  26829. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26830. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26831. if (navigator.getVRDevices) {
  26832. navigator.getVRDevices().then(this._getWebVRDevices);
  26833. }
  26834. else if (navigator.mozGetVRDevices) {
  26835. navigator.mozGetVRDevices(this._getWebVRDevices);
  26836. }
  26837. };
  26838. WebVRCamera.prototype.detachControl = function (element) {
  26839. _super.prototype.detachControl.call(this, element);
  26840. this._vrEnabled = false;
  26841. };
  26842. return WebVRCamera;
  26843. })(BABYLON.OculusCamera);
  26844. BABYLON.WebVRCamera = WebVRCamera;
  26845. })(BABYLON || (BABYLON = {}));
  26846. //# sourceMappingURL=babylon.webVRCamera.js.map
  26847. var BABYLON;
  26848. (function (BABYLON) {
  26849. // Standard optimizations
  26850. var SceneOptimization = (function () {
  26851. function SceneOptimization(priority) {
  26852. if (priority === void 0) { priority = 0; }
  26853. this.priority = priority;
  26854. this.apply = function (scene) {
  26855. return true; // Return true if everything that can be done was applied
  26856. };
  26857. }
  26858. return SceneOptimization;
  26859. })();
  26860. BABYLON.SceneOptimization = SceneOptimization;
  26861. var TextureOptimization = (function (_super) {
  26862. __extends(TextureOptimization, _super);
  26863. function TextureOptimization(priority, maximumSize) {
  26864. var _this = this;
  26865. if (priority === void 0) { priority = 0; }
  26866. if (maximumSize === void 0) { maximumSize = 1024; }
  26867. _super.call(this, priority);
  26868. this.priority = priority;
  26869. this.maximumSize = maximumSize;
  26870. this.apply = function (scene) {
  26871. var allDone = true;
  26872. for (var index = 0; index < scene.textures.length; index++) {
  26873. var texture = scene.textures[index];
  26874. if (!texture.canRescale) {
  26875. continue;
  26876. }
  26877. var currentSize = texture.getSize();
  26878. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26879. if (maxDimension > _this.maximumSize) {
  26880. texture.scale(0.5);
  26881. allDone = false;
  26882. }
  26883. }
  26884. return allDone;
  26885. };
  26886. }
  26887. return TextureOptimization;
  26888. })(SceneOptimization);
  26889. BABYLON.TextureOptimization = TextureOptimization;
  26890. var HardwareScalingOptimization = (function (_super) {
  26891. __extends(HardwareScalingOptimization, _super);
  26892. function HardwareScalingOptimization(priority, maximumScale) {
  26893. var _this = this;
  26894. if (priority === void 0) { priority = 0; }
  26895. if (maximumScale === void 0) { maximumScale = 2; }
  26896. _super.call(this, priority);
  26897. this.priority = priority;
  26898. this.maximumScale = maximumScale;
  26899. this._currentScale = 1;
  26900. this.apply = function (scene) {
  26901. _this._currentScale++;
  26902. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26903. return _this._currentScale >= _this.maximumScale;
  26904. };
  26905. }
  26906. return HardwareScalingOptimization;
  26907. })(SceneOptimization);
  26908. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26909. var ShadowsOptimization = (function (_super) {
  26910. __extends(ShadowsOptimization, _super);
  26911. function ShadowsOptimization() {
  26912. _super.apply(this, arguments);
  26913. this.apply = function (scene) {
  26914. scene.shadowsEnabled = false;
  26915. return true;
  26916. };
  26917. }
  26918. return ShadowsOptimization;
  26919. })(SceneOptimization);
  26920. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26921. var PostProcessesOptimization = (function (_super) {
  26922. __extends(PostProcessesOptimization, _super);
  26923. function PostProcessesOptimization() {
  26924. _super.apply(this, arguments);
  26925. this.apply = function (scene) {
  26926. scene.postProcessesEnabled = false;
  26927. return true;
  26928. };
  26929. }
  26930. return PostProcessesOptimization;
  26931. })(SceneOptimization);
  26932. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26933. var LensFlaresOptimization = (function (_super) {
  26934. __extends(LensFlaresOptimization, _super);
  26935. function LensFlaresOptimization() {
  26936. _super.apply(this, arguments);
  26937. this.apply = function (scene) {
  26938. scene.lensFlaresEnabled = false;
  26939. return true;
  26940. };
  26941. }
  26942. return LensFlaresOptimization;
  26943. })(SceneOptimization);
  26944. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26945. var ParticlesOptimization = (function (_super) {
  26946. __extends(ParticlesOptimization, _super);
  26947. function ParticlesOptimization() {
  26948. _super.apply(this, arguments);
  26949. this.apply = function (scene) {
  26950. scene.particlesEnabled = false;
  26951. return true;
  26952. };
  26953. }
  26954. return ParticlesOptimization;
  26955. })(SceneOptimization);
  26956. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26957. var RenderTargetsOptimization = (function (_super) {
  26958. __extends(RenderTargetsOptimization, _super);
  26959. function RenderTargetsOptimization() {
  26960. _super.apply(this, arguments);
  26961. this.apply = function (scene) {
  26962. scene.renderTargetsEnabled = false;
  26963. return true;
  26964. };
  26965. }
  26966. return RenderTargetsOptimization;
  26967. })(SceneOptimization);
  26968. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26969. var MergeMeshesOptimization = (function (_super) {
  26970. __extends(MergeMeshesOptimization, _super);
  26971. function MergeMeshesOptimization() {
  26972. var _this = this;
  26973. _super.apply(this, arguments);
  26974. this._canBeMerged = function (abstractMesh) {
  26975. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26976. return false;
  26977. }
  26978. var mesh = abstractMesh;
  26979. if (!mesh.isVisible || !mesh.isEnabled()) {
  26980. return false;
  26981. }
  26982. if (mesh.instances.length > 0) {
  26983. return false;
  26984. }
  26985. if (mesh.skeleton || mesh.hasLODLevels) {
  26986. return false;
  26987. }
  26988. return true;
  26989. };
  26990. this.apply = function (scene) {
  26991. var globalPool = scene.meshes.slice(0);
  26992. var globalLength = globalPool.length;
  26993. for (var index = 0; index < globalLength; index++) {
  26994. var currentPool = new Array();
  26995. var current = globalPool[index];
  26996. // Checks
  26997. if (!_this._canBeMerged(current)) {
  26998. continue;
  26999. }
  27000. currentPool.push(current);
  27001. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  27002. var otherMesh = globalPool[subIndex];
  27003. if (!_this._canBeMerged(otherMesh)) {
  27004. continue;
  27005. }
  27006. if (otherMesh.material !== current.material) {
  27007. continue;
  27008. }
  27009. if (otherMesh.checkCollisions !== current.checkCollisions) {
  27010. continue;
  27011. }
  27012. currentPool.push(otherMesh);
  27013. globalLength--;
  27014. globalPool.splice(subIndex, 1);
  27015. subIndex--;
  27016. }
  27017. if (currentPool.length < 2) {
  27018. continue;
  27019. }
  27020. // Merge meshes
  27021. BABYLON.Mesh.MergeMeshes(currentPool);
  27022. }
  27023. return true;
  27024. };
  27025. }
  27026. return MergeMeshesOptimization;
  27027. })(SceneOptimization);
  27028. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  27029. // Options
  27030. var SceneOptimizerOptions = (function () {
  27031. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  27032. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  27033. if (trackerDuration === void 0) { trackerDuration = 2000; }
  27034. this.targetFrameRate = targetFrameRate;
  27035. this.trackerDuration = trackerDuration;
  27036. this.optimizations = new Array();
  27037. }
  27038. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  27039. var result = new SceneOptimizerOptions(targetFrameRate);
  27040. var priority = 0;
  27041. result.optimizations.push(new MergeMeshesOptimization(priority));
  27042. result.optimizations.push(new ShadowsOptimization(priority));
  27043. result.optimizations.push(new LensFlaresOptimization(priority));
  27044. // Next priority
  27045. priority++;
  27046. result.optimizations.push(new PostProcessesOptimization(priority));
  27047. result.optimizations.push(new ParticlesOptimization(priority));
  27048. // Next priority
  27049. priority++;
  27050. result.optimizations.push(new TextureOptimization(priority, 1024));
  27051. return result;
  27052. };
  27053. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  27054. var result = new SceneOptimizerOptions(targetFrameRate);
  27055. var priority = 0;
  27056. result.optimizations.push(new MergeMeshesOptimization(priority));
  27057. result.optimizations.push(new ShadowsOptimization(priority));
  27058. result.optimizations.push(new LensFlaresOptimization(priority));
  27059. // Next priority
  27060. priority++;
  27061. result.optimizations.push(new PostProcessesOptimization(priority));
  27062. result.optimizations.push(new ParticlesOptimization(priority));
  27063. // Next priority
  27064. priority++;
  27065. result.optimizations.push(new TextureOptimization(priority, 512));
  27066. // Next priority
  27067. priority++;
  27068. result.optimizations.push(new RenderTargetsOptimization(priority));
  27069. // Next priority
  27070. priority++;
  27071. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  27072. return result;
  27073. };
  27074. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  27075. var result = new SceneOptimizerOptions(targetFrameRate);
  27076. var priority = 0;
  27077. result.optimizations.push(new MergeMeshesOptimization(priority));
  27078. result.optimizations.push(new ShadowsOptimization(priority));
  27079. result.optimizations.push(new LensFlaresOptimization(priority));
  27080. // Next priority
  27081. priority++;
  27082. result.optimizations.push(new PostProcessesOptimization(priority));
  27083. result.optimizations.push(new ParticlesOptimization(priority));
  27084. // Next priority
  27085. priority++;
  27086. result.optimizations.push(new TextureOptimization(priority, 256));
  27087. // Next priority
  27088. priority++;
  27089. result.optimizations.push(new RenderTargetsOptimization(priority));
  27090. // Next priority
  27091. priority++;
  27092. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  27093. return result;
  27094. };
  27095. return SceneOptimizerOptions;
  27096. })();
  27097. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  27098. // Scene optimizer tool
  27099. var SceneOptimizer = (function () {
  27100. function SceneOptimizer() {
  27101. }
  27102. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  27103. // TODO: add an epsilon
  27104. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  27105. if (onSuccess) {
  27106. onSuccess();
  27107. }
  27108. return;
  27109. }
  27110. // Apply current level of optimizations
  27111. var allDone = true;
  27112. var noOptimizationApplied = true;
  27113. for (var index = 0; index < options.optimizations.length; index++) {
  27114. var optimization = options.optimizations[index];
  27115. if (optimization.priority === currentPriorityLevel) {
  27116. noOptimizationApplied = false;
  27117. allDone = allDone && optimization.apply(scene);
  27118. }
  27119. }
  27120. // If no optimization was applied, this is a failure :(
  27121. if (noOptimizationApplied) {
  27122. if (onFailure) {
  27123. onFailure();
  27124. }
  27125. return;
  27126. }
  27127. // If all optimizations were done, move to next level
  27128. if (allDone) {
  27129. currentPriorityLevel++;
  27130. }
  27131. // Let's the system running for a specific amount of time before checking FPS
  27132. scene.executeWhenReady(function () {
  27133. setTimeout(function () {
  27134. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  27135. }, options.trackerDuration);
  27136. });
  27137. };
  27138. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  27139. if (!options) {
  27140. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  27141. }
  27142. // Let's the system running for a specific amount of time before checking FPS
  27143. scene.executeWhenReady(function () {
  27144. setTimeout(function () {
  27145. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  27146. }, options.trackerDuration);
  27147. });
  27148. };
  27149. return SceneOptimizer;
  27150. })();
  27151. BABYLON.SceneOptimizer = SceneOptimizer;
  27152. })(BABYLON || (BABYLON = {}));
  27153. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  27154. (function (BABYLON) {
  27155. var Internals;
  27156. (function (Internals) {
  27157. var MeshLODLevel = (function () {
  27158. function MeshLODLevel(distance, mesh) {
  27159. this.distance = distance;
  27160. this.mesh = mesh;
  27161. }
  27162. return MeshLODLevel;
  27163. })();
  27164. Internals.MeshLODLevel = MeshLODLevel;
  27165. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27166. })(BABYLON || (BABYLON = {}));
  27167. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  27168. (function (BABYLON) {
  27169. var AudioEngine = (function () {
  27170. function AudioEngine() {
  27171. this.audioContext = null;
  27172. this.canUseWebAudio = false;
  27173. this.WarnedWebAudioUnsupported = false;
  27174. try {
  27175. if (typeof AudioContext !== 'undefined') {
  27176. this.audioContext = new AudioContext();
  27177. this.canUseWebAudio = true;
  27178. }
  27179. else if (typeof webkitAudioContext !== 'undefined') {
  27180. this.audioContext = new webkitAudioContext();
  27181. this.canUseWebAudio = true;
  27182. }
  27183. }
  27184. catch (e) {
  27185. this.canUseWebAudio = false;
  27186. BABYLON.Tools.Error("Web Audio: " + e.message);
  27187. }
  27188. // create a global volume gain node
  27189. if (this.canUseWebAudio) {
  27190. this.masterGain = this.audioContext.createGain();
  27191. this.masterGain.gain.value = 1;
  27192. this.masterGain.connect(this.audioContext.destination);
  27193. }
  27194. }
  27195. AudioEngine.prototype.dispose = function () {
  27196. if (this.canUseWebAudio) {
  27197. if (this._connectedAnalyser) {
  27198. this._connectedAnalyser.stopDebugCanvas();
  27199. this._connectedAnalyser.dispose();
  27200. this.masterGain.disconnect();
  27201. this.masterGain.connect(this.audioContext.destination);
  27202. this._connectedAnalyser = null;
  27203. }
  27204. this.masterGain.gain.value = 1;
  27205. }
  27206. this.WarnedWebAudioUnsupported = false;
  27207. };
  27208. AudioEngine.prototype.getGlobalVolume = function () {
  27209. if (this.canUseWebAudio) {
  27210. return this.masterGain.gain.value;
  27211. }
  27212. else {
  27213. return -1;
  27214. }
  27215. };
  27216. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  27217. if (this.canUseWebAudio) {
  27218. this.masterGain.gain.value = newVolume;
  27219. }
  27220. };
  27221. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  27222. if (this._connectedAnalyser) {
  27223. this._connectedAnalyser.stopDebugCanvas();
  27224. }
  27225. this._connectedAnalyser = analyser;
  27226. if (this.canUseWebAudio) {
  27227. this.masterGain.disconnect();
  27228. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  27229. }
  27230. };
  27231. return AudioEngine;
  27232. })();
  27233. BABYLON.AudioEngine = AudioEngine;
  27234. })(BABYLON || (BABYLON = {}));
  27235. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  27236. (function (BABYLON) {
  27237. var Sound = (function () {
  27238. /**
  27239. * Create a sound and attach it to a scene
  27240. * @param name Name of your sound
  27241. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  27242. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  27243. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  27244. */
  27245. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  27246. var _this = this;
  27247. this.autoplay = false;
  27248. this.loop = false;
  27249. this.useCustomAttenuation = false;
  27250. this.spatialSound = false;
  27251. this.refDistance = 1;
  27252. this.rolloffFactor = 1;
  27253. this.maxDistance = 100;
  27254. this.distanceModel = "linear";
  27255. this._panningModel = "equalpower";
  27256. this._playbackRate = 1;
  27257. this._startTime = 0;
  27258. this._startOffset = 0;
  27259. this._position = BABYLON.Vector3.Zero();
  27260. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27261. this._volume = 1;
  27262. this._isLoaded = false;
  27263. this._isReadyToPlay = false;
  27264. this.isPlaying = false;
  27265. this.isPaused = false;
  27266. this._isDirectional = false;
  27267. // Used if you'd like to create a directional sound.
  27268. // If not set, the sound will be omnidirectional
  27269. this._coneInnerAngle = 360;
  27270. this._coneOuterAngle = 360;
  27271. this._coneOuterGain = 0;
  27272. this.name = name;
  27273. this._scene = scene;
  27274. this._readyToPlayCallback = readyToPlayCallback;
  27275. // Default custom attenuation function is a linear attenuation
  27276. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27277. if (currentDistance < maxDistance) {
  27278. return currentVolume * (1 - currentDistance / maxDistance);
  27279. }
  27280. else {
  27281. return 0;
  27282. }
  27283. };
  27284. if (options) {
  27285. this.autoplay = options.autoplay || false;
  27286. this.loop = options.loop || false;
  27287. // if volume === 0, we need another way to check this option
  27288. if (options.volume !== undefined) {
  27289. this._volume = options.volume;
  27290. }
  27291. this.spatialSound = options.spatialSound || false;
  27292. this.maxDistance = options.maxDistance || 100;
  27293. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27294. this.rolloffFactor = options.rolloffFactor || 1;
  27295. this.refDistance = options.refDistance || 1;
  27296. this.distanceModel = options.distanceModel || "linear";
  27297. this._playbackRate = options.playbackRate || 1;
  27298. }
  27299. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27300. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27301. this._soundGain.gain.value = this._volume;
  27302. this._inputAudioNode = this._soundGain;
  27303. this._ouputAudioNode = this._soundGain;
  27304. if (this.spatialSound) {
  27305. this._createSpatialParameters();
  27306. }
  27307. this._scene.mainSoundTrack.AddSound(this);
  27308. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27309. if (urlOrArrayBuffer) {
  27310. // If it's an URL
  27311. if (typeof (urlOrArrayBuffer) === "string") {
  27312. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  27313. _this._soundLoaded(data);
  27314. }, null, null, true);
  27315. }
  27316. else {
  27317. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27318. this._soundLoaded(urlOrArrayBuffer);
  27319. }
  27320. else {
  27321. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27322. }
  27323. }
  27324. }
  27325. }
  27326. else {
  27327. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27328. this._scene.mainSoundTrack.AddSound(this);
  27329. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27330. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27331. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27332. }
  27333. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27334. if (this._readyToPlayCallback) {
  27335. window.setTimeout(function () {
  27336. _this._readyToPlayCallback();
  27337. }, 1000);
  27338. }
  27339. }
  27340. }
  27341. Sound.prototype.dispose = function () {
  27342. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27343. if (this.isPlaying) {
  27344. this.stop();
  27345. }
  27346. this._isReadyToPlay = false;
  27347. if (this.soundTrackId === -1) {
  27348. this._scene.mainSoundTrack.RemoveSound(this);
  27349. }
  27350. else {
  27351. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27352. }
  27353. if (this._soundGain) {
  27354. this._soundGain.disconnect();
  27355. this._soundGain = null;
  27356. }
  27357. if (this._soundPanner) {
  27358. this._soundPanner.disconnect();
  27359. this._soundPanner = null;
  27360. }
  27361. if (this._soundSource) {
  27362. this._soundSource.disconnect();
  27363. this._soundSource = null;
  27364. }
  27365. this._audioBuffer = null;
  27366. if (this._connectedMesh) {
  27367. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27368. this._connectedMesh = null;
  27369. }
  27370. }
  27371. };
  27372. Sound.prototype._soundLoaded = function (audioData) {
  27373. var _this = this;
  27374. this._isLoaded = true;
  27375. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27376. _this._audioBuffer = buffer;
  27377. _this._isReadyToPlay = true;
  27378. if (_this.autoplay) {
  27379. _this.play();
  27380. }
  27381. if (_this._readyToPlayCallback) {
  27382. _this._readyToPlayCallback();
  27383. }
  27384. }, function (error) {
  27385. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27386. });
  27387. };
  27388. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27389. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27390. this._audioBuffer = audioBuffer;
  27391. this._isReadyToPlay = true;
  27392. }
  27393. };
  27394. Sound.prototype.updateOptions = function (options) {
  27395. if (options) {
  27396. this.loop = options.loop || this.loop;
  27397. this.maxDistance = options.maxDistance || this.maxDistance;
  27398. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27399. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27400. this.refDistance = options.refDistance || this.refDistance;
  27401. this.distanceModel = options.distanceModel || this.distanceModel;
  27402. this._playbackRate = options.playbackRate || this._playbackRate;
  27403. }
  27404. };
  27405. Sound.prototype._createSpatialParameters = function () {
  27406. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27407. if (this._scene.headphone) {
  27408. this._panningModel = "HRTF";
  27409. }
  27410. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27411. if (this.useCustomAttenuation) {
  27412. // Tricks to disable in a way embedded Web Audio attenuation
  27413. this._soundPanner.distanceModel = "linear";
  27414. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27415. this._soundPanner.refDistance = 1;
  27416. this._soundPanner.rolloffFactor = 1;
  27417. this._soundPanner.panningModel = this._panningModel;
  27418. }
  27419. else {
  27420. this._soundPanner.distanceModel = this.distanceModel;
  27421. this._soundPanner.maxDistance = this.maxDistance;
  27422. this._soundPanner.refDistance = this.refDistance;
  27423. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27424. this._soundPanner.panningModel = this._panningModel;
  27425. }
  27426. this._soundPanner.connect(this._ouputAudioNode);
  27427. this._inputAudioNode = this._soundPanner;
  27428. }
  27429. };
  27430. Sound.prototype.switchPanningModelToHRTF = function () {
  27431. this._panningModel = "HRTF";
  27432. this._switchPanningModel();
  27433. };
  27434. Sound.prototype.switchPanningModelToEqualPower = function () {
  27435. this._panningModel = "equalpower";
  27436. this._switchPanningModel();
  27437. };
  27438. Sound.prototype._switchPanningModel = function () {
  27439. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27440. this._soundPanner.panningModel = this._panningModel;
  27441. }
  27442. };
  27443. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27444. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27445. this._ouputAudioNode.disconnect();
  27446. this._ouputAudioNode.connect(soundTrackAudioNode);
  27447. }
  27448. };
  27449. /**
  27450. * Transform this sound into a directional source
  27451. * @param coneInnerAngle Size of the inner cone in degree
  27452. * @param coneOuterAngle Size of the outer cone in degree
  27453. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27454. */
  27455. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27456. if (coneOuterAngle < coneInnerAngle) {
  27457. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27458. return;
  27459. }
  27460. this._coneInnerAngle = coneInnerAngle;
  27461. this._coneOuterAngle = coneOuterAngle;
  27462. this._coneOuterGain = coneOuterGain;
  27463. this._isDirectional = true;
  27464. if (this.isPlaying && this.loop) {
  27465. this.stop();
  27466. this.play();
  27467. }
  27468. };
  27469. Sound.prototype.setPosition = function (newPosition) {
  27470. this._position = newPosition;
  27471. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27472. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27473. }
  27474. };
  27475. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27476. this._localDirection = newLocalDirection;
  27477. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27478. this._updateDirection();
  27479. }
  27480. };
  27481. Sound.prototype._updateDirection = function () {
  27482. var mat = this._connectedMesh.getWorldMatrix();
  27483. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27484. direction.normalize();
  27485. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27486. };
  27487. Sound.prototype.updateDistanceFromListener = function () {
  27488. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27489. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27490. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27491. }
  27492. };
  27493. Sound.prototype.setAttenuationFunction = function (callback) {
  27494. this._customAttenuationFunction = callback;
  27495. };
  27496. /**
  27497. * Play the sound
  27498. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27499. */
  27500. Sound.prototype.play = function (time) {
  27501. var _this = this;
  27502. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27503. try {
  27504. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27505. if (!this._soundSource) {
  27506. if (this.spatialSound) {
  27507. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27508. if (this._isDirectional) {
  27509. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27510. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27511. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27512. if (this._connectedMesh) {
  27513. this._updateDirection();
  27514. }
  27515. else {
  27516. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27517. }
  27518. }
  27519. }
  27520. }
  27521. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27522. this._soundSource.buffer = this._audioBuffer;
  27523. this._soundSource.connect(this._inputAudioNode);
  27524. this._soundSource.loop = this.loop;
  27525. this._soundSource.playbackRate.value = this._playbackRate;
  27526. this._startTime = startTime;
  27527. this._soundSource.onended = function () {
  27528. _this._onended();
  27529. };
  27530. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27531. this.isPlaying = true;
  27532. this.isPaused = false;
  27533. }
  27534. catch (ex) {
  27535. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27536. }
  27537. }
  27538. };
  27539. Sound.prototype._onended = function () {
  27540. this.isPlaying = false;
  27541. if (this.onended) {
  27542. this.onended();
  27543. }
  27544. };
  27545. /**
  27546. * Stop the sound
  27547. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27548. */
  27549. Sound.prototype.stop = function (time) {
  27550. if (this.isPlaying) {
  27551. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27552. this._soundSource.stop(stopTime);
  27553. this.isPlaying = false;
  27554. }
  27555. };
  27556. Sound.prototype.pause = function () {
  27557. if (this.isPlaying) {
  27558. this.stop(0);
  27559. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27560. this.isPaused = true;
  27561. }
  27562. };
  27563. Sound.prototype.setVolume = function (newVolume, time) {
  27564. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27565. if (time) {
  27566. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27567. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27568. }
  27569. else {
  27570. this._soundGain.gain.value = newVolume;
  27571. }
  27572. }
  27573. this._volume = newVolume;
  27574. };
  27575. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27576. this._playbackRate = newPlaybackRate;
  27577. if (this.isPlaying) {
  27578. this._soundSource.playbackRate.value = this._playbackRate;
  27579. }
  27580. };
  27581. Sound.prototype.getVolume = function () {
  27582. return this._volume;
  27583. };
  27584. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27585. var _this = this;
  27586. this._connectedMesh = meshToConnectTo;
  27587. if (!this.spatialSound) {
  27588. this._createSpatialParameters();
  27589. this.spatialSound = true;
  27590. if (this.isPlaying && this.loop) {
  27591. this.stop();
  27592. this.play();
  27593. }
  27594. }
  27595. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27596. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27597. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27598. };
  27599. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27600. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27601. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27602. this._updateDirection();
  27603. }
  27604. };
  27605. return Sound;
  27606. })();
  27607. BABYLON.Sound = Sound;
  27608. })(BABYLON || (BABYLON = {}));
  27609. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27610. (function (BABYLON) {
  27611. var SoundTrack = (function () {
  27612. function SoundTrack(scene, options) {
  27613. this.id = -1;
  27614. this._isMainTrack = false;
  27615. this._scene = scene;
  27616. this._audioEngine = BABYLON.Engine.audioEngine;
  27617. this.soundCollection = new Array();
  27618. if (this._audioEngine.canUseWebAudio) {
  27619. this._trackGain = this._audioEngine.audioContext.createGain();
  27620. this._trackGain.connect(this._audioEngine.masterGain);
  27621. if (options) {
  27622. if (options.volume) {
  27623. this._trackGain.gain.value = options.volume;
  27624. }
  27625. if (options.mainTrack) {
  27626. this._isMainTrack = options.mainTrack;
  27627. }
  27628. }
  27629. }
  27630. if (!this._isMainTrack) {
  27631. this._scene.soundTracks.push(this);
  27632. this.id = this._scene.soundTracks.length - 1;
  27633. }
  27634. }
  27635. SoundTrack.prototype.dispose = function () {
  27636. if (this._audioEngine.canUseWebAudio) {
  27637. if (this._connectedAnalyser) {
  27638. this._connectedAnalyser.stopDebugCanvas();
  27639. }
  27640. while (this.soundCollection.length) {
  27641. this.soundCollection[0].dispose();
  27642. }
  27643. this._trackGain.disconnect();
  27644. this._trackGain = null;
  27645. }
  27646. };
  27647. SoundTrack.prototype.AddSound = function (sound) {
  27648. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27649. sound.connectToSoundTrackAudioNode(this._trackGain);
  27650. }
  27651. if (sound.soundTrackId) {
  27652. if (sound.soundTrackId === -1) {
  27653. this._scene.mainSoundTrack.RemoveSound(sound);
  27654. }
  27655. else {
  27656. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27657. }
  27658. }
  27659. this.soundCollection.push(sound);
  27660. sound.soundTrackId = this.id;
  27661. };
  27662. SoundTrack.prototype.RemoveSound = function (sound) {
  27663. var index = this.soundCollection.indexOf(sound);
  27664. if (index !== -1) {
  27665. this.soundCollection.splice(index, 1);
  27666. }
  27667. };
  27668. SoundTrack.prototype.setVolume = function (newVolume) {
  27669. if (this._audioEngine.canUseWebAudio) {
  27670. this._trackGain.gain.value = newVolume;
  27671. }
  27672. };
  27673. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27674. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27675. for (var i = 0; i < this.soundCollection.length; i++) {
  27676. this.soundCollection[i].switchPanningModelToHRTF();
  27677. }
  27678. }
  27679. };
  27680. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27681. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27682. for (var i = 0; i < this.soundCollection.length; i++) {
  27683. this.soundCollection[i].switchPanningModelToEqualPower();
  27684. }
  27685. }
  27686. };
  27687. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27688. if (this._connectedAnalyser) {
  27689. this._connectedAnalyser.stopDebugCanvas();
  27690. }
  27691. this._connectedAnalyser = analyser;
  27692. if (this._audioEngine.canUseWebAudio) {
  27693. this._trackGain.disconnect();
  27694. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27695. }
  27696. };
  27697. return SoundTrack;
  27698. })();
  27699. BABYLON.SoundTrack = SoundTrack;
  27700. })(BABYLON || (BABYLON = {}));
  27701. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27702. (function (BABYLON) {
  27703. var DebugLayer = (function () {
  27704. function DebugLayer(scene) {
  27705. var _this = this;
  27706. this._transformationMatrix = BABYLON.Matrix.Identity();
  27707. this._enabled = false;
  27708. this._labelsEnabled = false;
  27709. this._displayStatistics = true;
  27710. this._displayTree = false;
  27711. this._displayLogs = false;
  27712. this._identityMatrix = BABYLON.Matrix.Identity();
  27713. this.axisRatio = 0.02;
  27714. this.accentColor = "orange";
  27715. this._scene = scene;
  27716. this._syncPositions = function () {
  27717. var engine = _this._scene.getEngine();
  27718. var canvasRect = engine.getRenderingCanvasClientRect();
  27719. if (_this._showUI) {
  27720. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27721. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27722. _this._statsDiv.style.width = "400px";
  27723. _this._statsDiv.style.height = "auto";
  27724. _this._statsSubsetDiv.style.maxHeight = "240px";
  27725. _this._optionsDiv.style.left = "0px";
  27726. _this._optionsDiv.style.top = "10px";
  27727. _this._optionsDiv.style.width = "200px";
  27728. _this._optionsDiv.style.height = "auto";
  27729. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27730. _this._logDiv.style.left = "0px";
  27731. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27732. _this._logDiv.style.width = "600px";
  27733. _this._logDiv.style.height = "160px";
  27734. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27735. _this._treeDiv.style.top = "10px";
  27736. _this._treeDiv.style.width = "300px";
  27737. _this._treeDiv.style.height = "auto";
  27738. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27739. }
  27740. _this._globalDiv.style.left = canvasRect.left + "px";
  27741. _this._globalDiv.style.top = canvasRect.top + "px";
  27742. _this._drawingCanvas.style.left = "0px";
  27743. _this._drawingCanvas.style.top = "0px";
  27744. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27745. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27746. var devicePixelRatio = window.devicePixelRatio || 1;
  27747. var context = _this._drawingContext;
  27748. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27749. _this._ratio = devicePixelRatio / backingStoreRatio;
  27750. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27751. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27752. };
  27753. this._onCanvasClick = function (evt) {
  27754. _this._clickPosition = {
  27755. x: evt.clientX * _this._ratio,
  27756. y: evt.clientY * _this._ratio
  27757. };
  27758. };
  27759. this._syncUI = function () {
  27760. if (_this._showUI) {
  27761. if (_this._displayStatistics) {
  27762. _this._displayStats();
  27763. _this._statsDiv.style.display = "";
  27764. }
  27765. else {
  27766. _this._statsDiv.style.display = "none";
  27767. }
  27768. if (_this._displayLogs) {
  27769. _this._logDiv.style.display = "";
  27770. }
  27771. else {
  27772. _this._logDiv.style.display = "none";
  27773. }
  27774. if (_this._displayTree) {
  27775. _this._treeDiv.style.display = "";
  27776. if (_this._needToRefreshMeshesTree) {
  27777. _this._needToRefreshMeshesTree = false;
  27778. _this._refreshMeshesTreeContent();
  27779. }
  27780. }
  27781. else {
  27782. _this._treeDiv.style.display = "none";
  27783. }
  27784. }
  27785. };
  27786. this._syncData = function () {
  27787. if (_this._labelsEnabled || !_this._showUI) {
  27788. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27789. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27790. var engine = _this._scene.getEngine();
  27791. var viewport = _this._camera.viewport;
  27792. var globalViewport = viewport.toGlobal(engine);
  27793. // Meshes
  27794. var meshes = _this._camera.getActiveMeshes();
  27795. for (var index = 0; index < meshes.length; index++) {
  27796. var mesh = meshes.data[index];
  27797. var position = mesh.getBoundingInfo().boundingSphere.center;
  27798. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27799. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27800. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27801. }
  27802. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27803. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27804. mesh.renderOverlay = !mesh.renderOverlay;
  27805. }, function () {
  27806. return mesh.renderOverlay ? 'red' : 'black';
  27807. });
  27808. }
  27809. }
  27810. // Cameras
  27811. var cameras = _this._scene.cameras;
  27812. for (index = 0; index < cameras.length; index++) {
  27813. var camera = cameras[index];
  27814. if (camera === _this._camera) {
  27815. continue;
  27816. }
  27817. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27818. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27819. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27820. _this._camera.detachControl(engine.getRenderingCanvas());
  27821. _this._camera = camera;
  27822. _this._camera.attachControl(engine.getRenderingCanvas());
  27823. }, function () {
  27824. return "purple";
  27825. });
  27826. }
  27827. }
  27828. // Lights
  27829. var lights = _this._scene.lights;
  27830. for (index = 0; index < lights.length; index++) {
  27831. var light = lights[index];
  27832. if (light.position) {
  27833. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27834. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27835. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27836. light.setEnabled(!light.isEnabled());
  27837. }, function () {
  27838. return light.isEnabled() ? "orange" : "gray";
  27839. });
  27840. }
  27841. }
  27842. }
  27843. }
  27844. _this._clickPosition = undefined;
  27845. };
  27846. }
  27847. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27848. while (this._treeSubsetDiv.hasChildNodes()) {
  27849. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27850. }
  27851. // Add meshes
  27852. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27853. sortedArray.sort(function (a, b) {
  27854. if (a.name === b.name) {
  27855. return 0;
  27856. }
  27857. return (a.name > b.name) ? 1 : -1;
  27858. });
  27859. for (var index = 0; index < sortedArray.length; index++) {
  27860. var mesh = sortedArray[index];
  27861. if (!mesh.isEnabled()) {
  27862. continue;
  27863. }
  27864. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27865. m.isVisible = element.checked;
  27866. }, mesh);
  27867. }
  27868. };
  27869. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27870. this._drawingContext.beginPath();
  27871. this._drawingContext.moveTo(zero.x, zero.y);
  27872. this._drawingContext.lineTo(unit.x, unit.y);
  27873. this._drawingContext.strokeStyle = color;
  27874. this._drawingContext.lineWidth = 4;
  27875. this._drawingContext.stroke();
  27876. this._drawingContext.font = "normal 14px Segoe UI";
  27877. this._drawingContext.fillStyle = color;
  27878. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27879. };
  27880. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27881. var position = mesh.getBoundingInfo().boundingSphere.center;
  27882. var worldMatrix = mesh.getWorldMatrix();
  27883. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27884. var unit = (unprojectedVector.subtract(position)).length();
  27885. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27886. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27887. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27888. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27889. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27890. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27891. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27892. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27893. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27894. };
  27895. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27896. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27897. this._drawingContext.font = "normal 12px Segoe UI";
  27898. var textMetrics = this._drawingContext.measureText(text);
  27899. var centerX = projectedPosition.x - textMetrics.width / 2;
  27900. var centerY = projectedPosition.y;
  27901. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27902. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27903. onClick();
  27904. }
  27905. this._drawingContext.beginPath();
  27906. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27907. this._drawingContext.fillStyle = getFillStyle();
  27908. this._drawingContext.globalAlpha = 0.5;
  27909. this._drawingContext.fill();
  27910. this._drawingContext.globalAlpha = 1.0;
  27911. this._drawingContext.strokeStyle = '#FFFFFF';
  27912. this._drawingContext.lineWidth = 1;
  27913. this._drawingContext.stroke();
  27914. this._drawingContext.fillStyle = "#FFFFFF";
  27915. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27916. this._drawingContext.beginPath();
  27917. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27918. this._drawingContext.fill();
  27919. }
  27920. };
  27921. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27922. if (!this._clickPosition) {
  27923. return false;
  27924. }
  27925. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27926. return false;
  27927. }
  27928. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27929. return false;
  27930. }
  27931. return true;
  27932. };
  27933. DebugLayer.prototype.isVisible = function () {
  27934. return this._enabled;
  27935. };
  27936. DebugLayer.prototype.hide = function () {
  27937. if (!this._enabled) {
  27938. return;
  27939. }
  27940. this._enabled = false;
  27941. var engine = this._scene.getEngine();
  27942. this._scene.unregisterBeforeRender(this._syncData);
  27943. this._scene.unregisterAfterRender(this._syncUI);
  27944. document.body.removeChild(this._globalDiv);
  27945. window.removeEventListener("resize", this._syncPositions);
  27946. this._scene.forceShowBoundingBoxes = false;
  27947. this._scene.forceWireframe = false;
  27948. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27949. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27950. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27951. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27952. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27953. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27954. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27955. this._scene.shadowsEnabled = true;
  27956. this._scene.particlesEnabled = true;
  27957. this._scene.postProcessesEnabled = true;
  27958. this._scene.collisionsEnabled = true;
  27959. this._scene.lightsEnabled = true;
  27960. this._scene.texturesEnabled = true;
  27961. this._scene.lensFlaresEnabled = true;
  27962. this._scene.proceduralTexturesEnabled = true;
  27963. this._scene.renderTargetsEnabled = true;
  27964. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27965. };
  27966. DebugLayer.prototype.show = function (showUI, camera) {
  27967. if (showUI === void 0) { showUI = true; }
  27968. if (camera === void 0) { camera = null; }
  27969. if (this._enabled) {
  27970. return;
  27971. }
  27972. this._enabled = true;
  27973. if (camera) {
  27974. this._camera = camera;
  27975. }
  27976. else {
  27977. this._camera = this._scene.activeCamera;
  27978. }
  27979. this._showUI = showUI;
  27980. var engine = this._scene.getEngine();
  27981. this._globalDiv = document.createElement("div");
  27982. document.body.appendChild(this._globalDiv);
  27983. this._generateDOMelements();
  27984. window.addEventListener("resize", this._syncPositions);
  27985. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27986. this._syncPositions();
  27987. this._scene.registerBeforeRender(this._syncData);
  27988. this._scene.registerAfterRender(this._syncUI);
  27989. };
  27990. DebugLayer.prototype._clearLabels = function () {
  27991. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27992. for (var index = 0; index < this._scene.meshes.length; index++) {
  27993. var mesh = this._scene.meshes[index];
  27994. mesh.renderOverlay = false;
  27995. }
  27996. };
  27997. DebugLayer.prototype._generateheader = function (root, text) {
  27998. var header = document.createElement("div");
  27999. header.innerHTML = text + "&nbsp;";
  28000. header.style.textAlign = "right";
  28001. header.style.width = "100%";
  28002. header.style.color = "white";
  28003. header.style.backgroundColor = "Black";
  28004. header.style.padding = "5px 5px 4px 0px";
  28005. header.style.marginLeft = "-5px";
  28006. header.style.fontWeight = "bold";
  28007. root.appendChild(header);
  28008. };
  28009. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28010. var label = document.createElement("label");
  28011. label.innerHTML = title;
  28012. label.style.color = color;
  28013. root.appendChild(label);
  28014. root.appendChild(document.createElement("br"));
  28015. };
  28016. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28017. if (tag === void 0) { tag = null; }
  28018. var label = document.createElement("label");
  28019. var boundingBoxesCheckbox = document.createElement("input");
  28020. boundingBoxesCheckbox.type = "checkbox";
  28021. boundingBoxesCheckbox.checked = initialState;
  28022. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28023. task(evt.target, tag);
  28024. });
  28025. label.appendChild(boundingBoxesCheckbox);
  28026. var container = document.createElement("span");
  28027. var leftPart = document.createElement("span");
  28028. var rightPart = document.createElement("span");
  28029. rightPart.style.cssFloat = "right";
  28030. leftPart.innerHTML = leftTitle;
  28031. rightPart.innerHTML = rightTitle;
  28032. rightPart.style.fontSize = "12px";
  28033. rightPart.style.maxWidth = "200px";
  28034. container.appendChild(leftPart);
  28035. container.appendChild(rightPart);
  28036. label.appendChild(container);
  28037. root.appendChild(label);
  28038. root.appendChild(document.createElement("br"));
  28039. };
  28040. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28041. if (tag === void 0) { tag = null; }
  28042. var label = document.createElement("label");
  28043. var checkBox = document.createElement("input");
  28044. checkBox.type = "checkbox";
  28045. checkBox.checked = initialState;
  28046. checkBox.addEventListener("change", function (evt) {
  28047. task(evt.target, tag);
  28048. });
  28049. label.appendChild(checkBox);
  28050. label.appendChild(document.createTextNode(title));
  28051. root.appendChild(label);
  28052. root.appendChild(document.createElement("br"));
  28053. };
  28054. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28055. if (tag === void 0) { tag = null; }
  28056. var button = document.createElement("button");
  28057. button.innerHTML = title;
  28058. button.style.height = "24px";
  28059. button.style.color = "#444444";
  28060. button.style.border = "1px solid white";
  28061. button.className = "debugLayerButton";
  28062. button.addEventListener("click", function (evt) {
  28063. task(evt.target, tag);
  28064. });
  28065. root.appendChild(button);
  28066. root.appendChild(document.createElement("br"));
  28067. };
  28068. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28069. if (tag === void 0) { tag = null; }
  28070. var label = document.createElement("label");
  28071. var boundingBoxesRadio = document.createElement("input");
  28072. boundingBoxesRadio.type = "radio";
  28073. boundingBoxesRadio.name = name;
  28074. boundingBoxesRadio.checked = initialState;
  28075. boundingBoxesRadio.addEventListener("change", function (evt) {
  28076. task(evt.target, tag);
  28077. });
  28078. label.appendChild(boundingBoxesRadio);
  28079. label.appendChild(document.createTextNode(title));
  28080. root.appendChild(label);
  28081. root.appendChild(document.createElement("br"));
  28082. };
  28083. DebugLayer.prototype._generateDOMelements = function () {
  28084. var _this = this;
  28085. this._globalDiv.id = "DebugLayer";
  28086. this._globalDiv.style.position = "absolute";
  28087. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28088. this._globalDiv.style.fontSize = "14px";
  28089. this._globalDiv.style.color = "white";
  28090. // Drawing canvas
  28091. this._drawingCanvas = document.createElement("canvas");
  28092. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28093. this._drawingCanvas.style.position = "absolute";
  28094. this._drawingCanvas.style.pointerEvents = "none";
  28095. this._drawingContext = this._drawingCanvas.getContext("2d");
  28096. this._globalDiv.appendChild(this._drawingCanvas);
  28097. if (this._showUI) {
  28098. var background = "rgba(128, 128, 128, 0.4)";
  28099. var border = "rgb(180, 180, 180) solid 1px";
  28100. // Stats
  28101. this._statsDiv = document.createElement("div");
  28102. this._statsDiv.id = "DebugLayerStats";
  28103. this._statsDiv.style.border = border;
  28104. this._statsDiv.style.position = "absolute";
  28105. this._statsDiv.style.background = background;
  28106. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28107. this._generateheader(this._statsDiv, "STATISTICS");
  28108. this._statsSubsetDiv = document.createElement("div");
  28109. this._statsSubsetDiv.style.paddingTop = "5px";
  28110. this._statsSubsetDiv.style.paddingBottom = "5px";
  28111. this._statsSubsetDiv.style.overflowY = "auto";
  28112. this._statsDiv.appendChild(this._statsSubsetDiv);
  28113. // Tree
  28114. this._treeDiv = document.createElement("div");
  28115. this._treeDiv.id = "DebugLayerTree";
  28116. this._treeDiv.style.border = border;
  28117. this._treeDiv.style.position = "absolute";
  28118. this._treeDiv.style.background = background;
  28119. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28120. this._treeDiv.style.display = "none";
  28121. this._generateheader(this._treeDiv, "MESHES TREE");
  28122. this._treeSubsetDiv = document.createElement("div");
  28123. this._treeSubsetDiv.style.paddingTop = "5px";
  28124. this._treeSubsetDiv.style.paddingRight = "5px";
  28125. this._treeSubsetDiv.style.overflowY = "auto";
  28126. this._treeSubsetDiv.style.maxHeight = "300px";
  28127. this._treeDiv.appendChild(this._treeSubsetDiv);
  28128. this._needToRefreshMeshesTree = true;
  28129. // Logs
  28130. this._logDiv = document.createElement("div");
  28131. this._logDiv.style.border = border;
  28132. this._logDiv.id = "DebugLayerLogs";
  28133. this._logDiv.style.position = "absolute";
  28134. this._logDiv.style.background = background;
  28135. this._logDiv.style.padding = "0px 0px 0px 5px";
  28136. this._logDiv.style.display = "none";
  28137. this._generateheader(this._logDiv, "LOGS");
  28138. this._logSubsetDiv = document.createElement("div");
  28139. this._logSubsetDiv.style.height = "127px";
  28140. this._logSubsetDiv.style.paddingTop = "5px";
  28141. this._logSubsetDiv.style.overflowY = "auto";
  28142. this._logSubsetDiv.style.fontSize = "12px";
  28143. this._logSubsetDiv.style.fontFamily = "consolas";
  28144. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28145. this._logDiv.appendChild(this._logSubsetDiv);
  28146. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28147. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28148. };
  28149. // Options
  28150. this._optionsDiv = document.createElement("div");
  28151. this._optionsDiv.id = "DebugLayerOptions";
  28152. this._optionsDiv.style.border = border;
  28153. this._optionsDiv.style.position = "absolute";
  28154. this._optionsDiv.style.background = background;
  28155. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28156. this._optionsDiv.style.overflowY = "auto";
  28157. this._generateheader(this._optionsDiv, "OPTIONS");
  28158. this._optionsSubsetDiv = document.createElement("div");
  28159. this._optionsSubsetDiv.style.paddingTop = "5px";
  28160. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28161. this._optionsSubsetDiv.style.overflowY = "auto";
  28162. this._optionsSubsetDiv.style.maxHeight = "200px";
  28163. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28164. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28165. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  28166. _this._displayStatistics = element.checked;
  28167. });
  28168. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  28169. _this._displayLogs = element.checked;
  28170. });
  28171. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28172. _this._displayTree = element.checked;
  28173. _this._needToRefreshMeshesTree = true;
  28174. });
  28175. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28176. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28177. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  28178. _this._scene.forceShowBoundingBoxes = element.checked;
  28179. });
  28180. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28181. _this._labelsEnabled = element.checked;
  28182. if (!_this._labelsEnabled) {
  28183. _this._clearLabels();
  28184. }
  28185. });
  28186. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28187. if (element.checked) {
  28188. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28189. }
  28190. else {
  28191. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28192. }
  28193. });
  28194. ;
  28195. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28196. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28197. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28198. if (element.checked) {
  28199. _this._scene.forceWireframe = false;
  28200. _this._scene.forcePointsCloud = false;
  28201. }
  28202. });
  28203. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28204. if (element.checked) {
  28205. _this._scene.forceWireframe = true;
  28206. _this._scene.forcePointsCloud = false;
  28207. }
  28208. });
  28209. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28210. if (element.checked) {
  28211. _this._scene.forceWireframe = false;
  28212. _this._scene.forcePointsCloud = true;
  28213. }
  28214. });
  28215. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28216. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28217. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  28218. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  28219. });
  28220. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  28221. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  28222. });
  28223. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  28224. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  28225. });
  28226. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  28227. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  28228. });
  28229. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  28230. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  28231. });
  28232. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  28233. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  28234. });
  28235. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  28236. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  28237. });
  28238. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  28239. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  28240. });
  28241. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28242. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28243. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  28244. _this._scene.animationsEnabled = element.checked;
  28245. });
  28246. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  28247. _this._scene.collisionsEnabled = element.checked;
  28248. });
  28249. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  28250. _this._scene.fogEnabled = element.checked;
  28251. });
  28252. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  28253. _this._scene.lensFlaresEnabled = element.checked;
  28254. });
  28255. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  28256. _this._scene.lightsEnabled = element.checked;
  28257. });
  28258. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  28259. _this._scene.particlesEnabled = element.checked;
  28260. });
  28261. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  28262. _this._scene.postProcessesEnabled = element.checked;
  28263. });
  28264. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  28265. _this._scene.proceduralTexturesEnabled = element.checked;
  28266. });
  28267. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  28268. _this._scene.renderTargetsEnabled = element.checked;
  28269. });
  28270. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  28271. _this._scene.shadowsEnabled = element.checked;
  28272. });
  28273. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  28274. _this._scene.skeletonsEnabled = element.checked;
  28275. });
  28276. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  28277. _this._scene.spritesEnabled = element.checked;
  28278. });
  28279. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  28280. _this._scene.texturesEnabled = element.checked;
  28281. });
  28282. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28283. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28284. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28285. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28286. if (element.checked) {
  28287. _this._scene.headphone = true;
  28288. }
  28289. });
  28290. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28291. if (element.checked) {
  28292. _this._scene.headphone = false;
  28293. }
  28294. });
  28295. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28296. _this._scene.audioEnabled = !element.checked;
  28297. });
  28298. }
  28299. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28300. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28301. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  28302. _this._scene.dumpNextRenderTargets = true;
  28303. });
  28304. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28305. this._globalDiv.appendChild(this._statsDiv);
  28306. this._globalDiv.appendChild(this._logDiv);
  28307. this._globalDiv.appendChild(this._optionsDiv);
  28308. this._globalDiv.appendChild(this._treeDiv);
  28309. }
  28310. };
  28311. DebugLayer.prototype._displayStats = function () {
  28312. var scene = this._scene;
  28313. var engine = scene.getEngine();
  28314. var glInfo = engine.getGlInfo();
  28315. 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>";
  28316. if (this.customStatsFunction) {
  28317. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28318. }
  28319. };
  28320. return DebugLayer;
  28321. })();
  28322. BABYLON.DebugLayer = DebugLayer;
  28323. })(BABYLON || (BABYLON = {}));
  28324. //# sourceMappingURL=babylon.debugLayer.js.map
  28325. var BABYLON;
  28326. (function (BABYLON) {
  28327. var RawTexture = (function (_super) {
  28328. __extends(RawTexture, _super);
  28329. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  28330. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28331. if (invertY === void 0) { invertY = false; }
  28332. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28333. _super.call(this, null, scene, !generateMipMaps, invertY);
  28334. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  28335. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28336. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28337. }
  28338. // Statics
  28339. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28340. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28341. if (invertY === void 0) { invertY = false; }
  28342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28343. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28344. };
  28345. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28346. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28347. if (invertY === void 0) { invertY = false; }
  28348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28349. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28350. };
  28351. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28352. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28353. if (invertY === void 0) { invertY = false; }
  28354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28355. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28356. };
  28357. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28358. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28359. if (invertY === void 0) { invertY = false; }
  28360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28361. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28362. };
  28363. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28364. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28365. if (invertY === void 0) { invertY = false; }
  28366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28367. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28368. };
  28369. return RawTexture;
  28370. })(BABYLON.Texture);
  28371. BABYLON.RawTexture = RawTexture;
  28372. })(BABYLON || (BABYLON = {}));
  28373. //# sourceMappingURL=babylon.rawTexture.js.map
  28374. var BABYLON;
  28375. (function (BABYLON) {
  28376. var IndexedVector2 = (function (_super) {
  28377. __extends(IndexedVector2, _super);
  28378. function IndexedVector2(original, index) {
  28379. _super.call(this, original.x, original.y);
  28380. this.index = index;
  28381. }
  28382. return IndexedVector2;
  28383. })(BABYLON.Vector2);
  28384. var PolygonPoints = (function () {
  28385. function PolygonPoints() {
  28386. this.elements = new Array();
  28387. }
  28388. PolygonPoints.prototype.add = function (originalPoints) {
  28389. var _this = this;
  28390. var result = new Array();
  28391. originalPoints.forEach(function (point) {
  28392. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28393. var newPoint = new IndexedVector2(point, _this.elements.length);
  28394. result.push(newPoint);
  28395. _this.elements.push(newPoint);
  28396. }
  28397. });
  28398. return result;
  28399. };
  28400. PolygonPoints.prototype.computeBounds = function () {
  28401. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28402. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28403. this.elements.forEach(function (point) {
  28404. // x
  28405. if (point.x < lmin.x) {
  28406. lmin.x = point.x;
  28407. }
  28408. else if (point.x > lmax.x) {
  28409. lmax.x = point.x;
  28410. }
  28411. // y
  28412. if (point.y < lmin.y) {
  28413. lmin.y = point.y;
  28414. }
  28415. else if (point.y > lmax.y) {
  28416. lmax.y = point.y;
  28417. }
  28418. });
  28419. return {
  28420. min: lmin,
  28421. max: lmax,
  28422. width: lmax.x - lmin.x,
  28423. height: lmax.y - lmin.y
  28424. };
  28425. };
  28426. return PolygonPoints;
  28427. })();
  28428. var Polygon = (function () {
  28429. function Polygon() {
  28430. }
  28431. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28432. return [
  28433. new BABYLON.Vector2(xmin, ymin),
  28434. new BABYLON.Vector2(xmax, ymin),
  28435. new BABYLON.Vector2(xmax, ymax),
  28436. new BABYLON.Vector2(xmin, ymax)
  28437. ];
  28438. };
  28439. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28440. if (cx === void 0) { cx = 0; }
  28441. if (cy === void 0) { cy = 0; }
  28442. if (numberOfSides === void 0) { numberOfSides = 32; }
  28443. var result = new Array();
  28444. var angle = 0;
  28445. var increment = (Math.PI * 2) / numberOfSides;
  28446. for (var i = 0; i < numberOfSides; i++) {
  28447. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28448. angle -= increment;
  28449. }
  28450. return result;
  28451. };
  28452. Polygon.Parse = function (input) {
  28453. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28454. var i, result = [];
  28455. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28456. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28457. }
  28458. return result;
  28459. };
  28460. Polygon.StartingAt = function (x, y) {
  28461. return BABYLON.Path2.StartingAt(x, y);
  28462. };
  28463. return Polygon;
  28464. })();
  28465. BABYLON.Polygon = Polygon;
  28466. var PolygonMeshBuilder = (function () {
  28467. function PolygonMeshBuilder(name, contours, scene) {
  28468. this._points = new PolygonPoints();
  28469. if (!("poly2tri" in window)) {
  28470. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28471. }
  28472. this._name = name;
  28473. this._scene = scene;
  28474. var points;
  28475. if (contours instanceof BABYLON.Path2) {
  28476. points = contours.getPoints();
  28477. }
  28478. else {
  28479. points = contours;
  28480. }
  28481. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28482. }
  28483. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28484. this._swctx.addHole(this._points.add(hole));
  28485. return this;
  28486. };
  28487. PolygonMeshBuilder.prototype.build = function (updatable) {
  28488. if (updatable === void 0) { updatable = false; }
  28489. var result = new BABYLON.Mesh(this._name, this._scene);
  28490. var normals = [];
  28491. var positions = [];
  28492. var uvs = [];
  28493. var bounds = this._points.computeBounds();
  28494. this._points.elements.forEach(function (p) {
  28495. normals.push(0, 1.0, 0);
  28496. positions.push(p.x, 0, p.y);
  28497. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28498. });
  28499. var indices = [];
  28500. this._swctx.triangulate();
  28501. this._swctx.getTriangles().forEach(function (triangle) {
  28502. triangle.getPoints().forEach(function (point) {
  28503. indices.push(point.index);
  28504. });
  28505. });
  28506. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28507. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28508. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28509. result.setIndices(indices);
  28510. return result;
  28511. };
  28512. return PolygonMeshBuilder;
  28513. })();
  28514. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28515. })(BABYLON || (BABYLON = {}));
  28516. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28517. (function (BABYLON) {
  28518. var SimplificationSettings = (function () {
  28519. function SimplificationSettings(quality, distance, optimizeMesh) {
  28520. this.quality = quality;
  28521. this.distance = distance;
  28522. this.optimizeMesh = optimizeMesh;
  28523. }
  28524. return SimplificationSettings;
  28525. })();
  28526. BABYLON.SimplificationSettings = SimplificationSettings;
  28527. var SimplificationQueue = (function () {
  28528. function SimplificationQueue() {
  28529. this.running = false;
  28530. this._simplificationArray = [];
  28531. }
  28532. SimplificationQueue.prototype.addTask = function (task) {
  28533. this._simplificationArray.push(task);
  28534. };
  28535. SimplificationQueue.prototype.executeNext = function () {
  28536. var task = this._simplificationArray.pop();
  28537. if (task) {
  28538. this.running = true;
  28539. this.runSimplification(task);
  28540. }
  28541. else {
  28542. this.running = false;
  28543. }
  28544. };
  28545. SimplificationQueue.prototype.runSimplification = function (task) {
  28546. var _this = this;
  28547. if (task.parallelProcessing) {
  28548. //parallel simplifier
  28549. task.settings.forEach(function (setting) {
  28550. var simplifier = _this.getSimplifier(task);
  28551. simplifier.simplify(setting, function (newMesh) {
  28552. task.mesh.addLODLevel(setting.distance, newMesh);
  28553. newMesh.isVisible = true;
  28554. //check if it is the last
  28555. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28556. //all done, run the success callback.
  28557. task.successCallback();
  28558. }
  28559. _this.executeNext();
  28560. });
  28561. });
  28562. }
  28563. else {
  28564. //single simplifier.
  28565. var simplifier = this.getSimplifier(task);
  28566. var runDecimation = function (setting, callback) {
  28567. simplifier.simplify(setting, function (newMesh) {
  28568. task.mesh.addLODLevel(setting.distance, newMesh);
  28569. newMesh.isVisible = true;
  28570. //run the next quality level
  28571. callback();
  28572. });
  28573. };
  28574. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28575. runDecimation(task.settings[loop.index], function () {
  28576. loop.executeNext();
  28577. });
  28578. }, function () {
  28579. //execution ended, run the success callback.
  28580. if (task.successCallback) {
  28581. task.successCallback();
  28582. }
  28583. _this.executeNext();
  28584. });
  28585. }
  28586. };
  28587. SimplificationQueue.prototype.getSimplifier = function (task) {
  28588. switch (task.simplificationType) {
  28589. case 0 /* QUADRATIC */:
  28590. default:
  28591. return new QuadraticErrorSimplification(task.mesh);
  28592. }
  28593. };
  28594. return SimplificationQueue;
  28595. })();
  28596. BABYLON.SimplificationQueue = SimplificationQueue;
  28597. /**
  28598. * The implemented types of simplification.
  28599. * At the moment only Quadratic Error Decimation is implemented.
  28600. */
  28601. (function (SimplificationType) {
  28602. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28603. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28604. var SimplificationType = BABYLON.SimplificationType;
  28605. var DecimationTriangle = (function () {
  28606. function DecimationTriangle(vertices) {
  28607. this.vertices = vertices;
  28608. this.error = new Array(4);
  28609. this.deleted = false;
  28610. this.isDirty = false;
  28611. this.deletePending = false;
  28612. this.borderFactor = 0;
  28613. }
  28614. return DecimationTriangle;
  28615. })();
  28616. BABYLON.DecimationTriangle = DecimationTriangle;
  28617. var DecimationVertex = (function () {
  28618. function DecimationVertex(position, id) {
  28619. this.position = position;
  28620. this.id = id;
  28621. this.isBorder = true;
  28622. this.q = new QuadraticMatrix();
  28623. this.triangleCount = 0;
  28624. this.triangleStart = 0;
  28625. this.originalOffsets = [];
  28626. }
  28627. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28628. this.position.copyFrom(newPosition);
  28629. };
  28630. return DecimationVertex;
  28631. })();
  28632. BABYLON.DecimationVertex = DecimationVertex;
  28633. var QuadraticMatrix = (function () {
  28634. function QuadraticMatrix(data) {
  28635. this.data = new Array(10);
  28636. for (var i = 0; i < 10; ++i) {
  28637. if (data && data[i]) {
  28638. this.data[i] = data[i];
  28639. }
  28640. else {
  28641. this.data[i] = 0;
  28642. }
  28643. }
  28644. }
  28645. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28646. 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];
  28647. return det;
  28648. };
  28649. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28650. for (var i = 0; i < 10; ++i) {
  28651. this.data[i] += matrix.data[i];
  28652. }
  28653. };
  28654. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28655. for (var i = 0; i < 10; ++i) {
  28656. this.data[i] += data[i];
  28657. }
  28658. };
  28659. QuadraticMatrix.prototype.add = function (matrix) {
  28660. var m = new QuadraticMatrix();
  28661. for (var i = 0; i < 10; ++i) {
  28662. m.data[i] = this.data[i] + matrix.data[i];
  28663. }
  28664. return m;
  28665. };
  28666. QuadraticMatrix.FromData = function (a, b, c, d) {
  28667. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28668. };
  28669. //returning an array to avoid garbage collection
  28670. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28671. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28672. };
  28673. return QuadraticMatrix;
  28674. })();
  28675. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28676. var Reference = (function () {
  28677. function Reference(vertexId, triangleId) {
  28678. this.vertexId = vertexId;
  28679. this.triangleId = triangleId;
  28680. }
  28681. return Reference;
  28682. })();
  28683. BABYLON.Reference = Reference;
  28684. /**
  28685. * An implementation of the Quadratic Error simplification algorithm.
  28686. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28687. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28688. * @author RaananW
  28689. */
  28690. var QuadraticErrorSimplification = (function () {
  28691. function QuadraticErrorSimplification(_mesh) {
  28692. this._mesh = _mesh;
  28693. this.initialized = false;
  28694. this.syncIterations = 5000;
  28695. this.aggressiveness = 7;
  28696. this.decimationIterations = 100;
  28697. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28698. }
  28699. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28700. var _this = this;
  28701. this.initDecimatedMesh();
  28702. //iterating through the submeshes array, one after the other.
  28703. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28704. _this.initWithMesh(loop.index, function () {
  28705. _this.runDecimation(settings, loop.index, function () {
  28706. loop.executeNext();
  28707. });
  28708. }, settings.optimizeMesh);
  28709. }, function () {
  28710. setTimeout(function () {
  28711. successCallback(_this._reconstructedMesh);
  28712. }, 0);
  28713. });
  28714. };
  28715. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28716. var _this = this;
  28717. var gCount = 0;
  28718. triangle.vertices.forEach(function (vertex) {
  28719. var count = 0;
  28720. var vPos = vertex.position;
  28721. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28722. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28723. ++count;
  28724. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28725. ++count;
  28726. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28727. ++count;
  28728. if (count > 1) {
  28729. ++gCount;
  28730. }
  28731. ;
  28732. });
  28733. if (gCount > 1) {
  28734. console.log(triangle, gCount);
  28735. }
  28736. return gCount > 1;
  28737. };
  28738. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28739. var _this = this;
  28740. var targetCount = ~~(this.triangles.length * settings.quality);
  28741. var deletedTriangles = 0;
  28742. var triangleCount = this.triangles.length;
  28743. var iterationFunction = function (iteration, callback) {
  28744. setTimeout(function () {
  28745. if (iteration % 5 === 0) {
  28746. _this.updateMesh(iteration === 0);
  28747. }
  28748. for (var i = 0; i < _this.triangles.length; ++i) {
  28749. _this.triangles[i].isDirty = false;
  28750. }
  28751. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28752. var trianglesIterator = function (i) {
  28753. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28754. var t = _this.triangles[tIdx];
  28755. if (!t)
  28756. return;
  28757. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28758. return;
  28759. }
  28760. for (var j = 0; j < 3; ++j) {
  28761. if (t.error[j] < threshold) {
  28762. var deleted0 = [];
  28763. var deleted1 = [];
  28764. var v0 = t.vertices[j];
  28765. var v1 = t.vertices[(j + 1) % 3];
  28766. if (v0.isBorder !== v1.isBorder)
  28767. continue;
  28768. var p = BABYLON.Vector3.Zero();
  28769. var n = BABYLON.Vector3.Zero();
  28770. var uv = BABYLON.Vector2.Zero();
  28771. var color = new BABYLON.Color4(0, 0, 0, 1);
  28772. _this.calculateError(v0, v1, p, n, uv, color);
  28773. var delTr = [];
  28774. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28775. continue;
  28776. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28777. continue;
  28778. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28779. continue;
  28780. var uniqueArray = [];
  28781. delTr.forEach(function (deletedT) {
  28782. if (uniqueArray.indexOf(deletedT) === -1) {
  28783. deletedT.deletePending = true;
  28784. uniqueArray.push(deletedT);
  28785. }
  28786. });
  28787. if (uniqueArray.length % 2 != 0) {
  28788. continue;
  28789. }
  28790. v0.q = v1.q.add(v0.q);
  28791. v0.updatePosition(p);
  28792. var tStart = _this.references.length;
  28793. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28794. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28795. var tCount = _this.references.length - tStart;
  28796. if (tCount <= v0.triangleCount) {
  28797. if (tCount) {
  28798. for (var c = 0; c < tCount; c++) {
  28799. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28800. }
  28801. }
  28802. }
  28803. else {
  28804. v0.triangleStart = tStart;
  28805. }
  28806. v0.triangleCount = tCount;
  28807. break;
  28808. }
  28809. }
  28810. };
  28811. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28812. return (triangleCount - deletedTriangles <= targetCount);
  28813. });
  28814. }, 0);
  28815. };
  28816. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28817. if (triangleCount - deletedTriangles <= targetCount)
  28818. loop.breakLoop();
  28819. else {
  28820. iterationFunction(loop.index, function () {
  28821. loop.executeNext();
  28822. });
  28823. }
  28824. }, function () {
  28825. setTimeout(function () {
  28826. //reconstruct this part of the mesh
  28827. _this.reconstructMesh(submeshIndex);
  28828. successCallback();
  28829. }, 0);
  28830. });
  28831. };
  28832. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28833. var _this = this;
  28834. this.vertices = [];
  28835. this.triangles = [];
  28836. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28837. var indices = this._mesh.getIndices();
  28838. var submesh = this._mesh.subMeshes[submeshIndex];
  28839. var findInVertices = function (positionToSearch) {
  28840. if (optimizeMesh) {
  28841. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  28842. if (_this.vertices[ii].position.equals(positionToSearch)) {
  28843. return _this.vertices[ii];
  28844. }
  28845. }
  28846. }
  28847. return null;
  28848. };
  28849. var vertexReferences = [];
  28850. var vertexInit = function (i) {
  28851. var offset = i + submesh.verticesStart;
  28852. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  28853. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  28854. vertex.originalOffsets.push(offset);
  28855. if (vertex.id == _this.vertices.length) {
  28856. _this.vertices.push(vertex);
  28857. }
  28858. vertexReferences.push(vertex.id);
  28859. };
  28860. //var totalVertices = mesh.getTotalVertices();
  28861. var totalVertices = submesh.verticesCount;
  28862. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  28863. var indicesInit = function (i) {
  28864. var offset = (submesh.indexStart / 3) + i;
  28865. var pos = (offset * 3);
  28866. var i0 = indices[pos + 0];
  28867. var i1 = indices[pos + 1];
  28868. var i2 = indices[pos + 2];
  28869. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  28870. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  28871. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  28872. var triangle = new DecimationTriangle([v0, v1, v2]);
  28873. triangle.originalOffset = pos;
  28874. _this.triangles.push(triangle);
  28875. };
  28876. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28877. _this.init(callback);
  28878. });
  28879. });
  28880. };
  28881. QuadraticErrorSimplification.prototype.init = function (callback) {
  28882. var _this = this;
  28883. var triangleInit1 = function (i) {
  28884. var t = _this.triangles[i];
  28885. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  28886. for (var j = 0; j < 3; j++) {
  28887. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  28888. }
  28889. };
  28890. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28891. var triangleInit2 = function (i) {
  28892. var t = _this.triangles[i];
  28893. for (var j = 0; j < 3; ++j) {
  28894. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  28895. }
  28896. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28897. };
  28898. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28899. _this.initialized = true;
  28900. callback();
  28901. });
  28902. });
  28903. };
  28904. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28905. var newTriangles = [];
  28906. var i;
  28907. for (i = 0; i < this.vertices.length; ++i) {
  28908. this.vertices[i].triangleCount = 0;
  28909. }
  28910. var t;
  28911. var j;
  28912. for (i = 0; i < this.triangles.length; ++i) {
  28913. if (!this.triangles[i].deleted) {
  28914. t = this.triangles[i];
  28915. for (j = 0; j < 3; ++j) {
  28916. t.vertices[j].triangleCount = 1;
  28917. }
  28918. newTriangles.push(t);
  28919. }
  28920. }
  28921. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28922. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28923. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28924. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28925. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28926. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28927. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28928. var vertexCount = 0;
  28929. for (i = 0; i < this.vertices.length; ++i) {
  28930. var vertex = this.vertices[i];
  28931. vertex.id = vertexCount;
  28932. if (vertex.triangleCount) {
  28933. vertex.originalOffsets.forEach(function (originalOffset) {
  28934. newPositionData.push(vertex.position.x);
  28935. newPositionData.push(vertex.position.y);
  28936. newPositionData.push(vertex.position.z);
  28937. newNormalData.push(normalData[originalOffset * 3]);
  28938. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  28939. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  28940. if (uvs && uvs.length) {
  28941. newUVsData.push(uvs[(originalOffset * 2)]);
  28942. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  28943. }
  28944. else if (colorsData && colorsData.length) {
  28945. newColorsData.push(colorsData[(originalOffset * 4)]);
  28946. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  28947. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  28948. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  28949. }
  28950. ++vertexCount;
  28951. });
  28952. }
  28953. }
  28954. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28955. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28956. var submeshesArray = this._reconstructedMesh.subMeshes;
  28957. this._reconstructedMesh.subMeshes = [];
  28958. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28959. var originalIndices = this._mesh.getIndices();
  28960. for (i = 0; i < newTriangles.length; ++i) {
  28961. var t = newTriangles[i];
  28962. //now get the new referencing point for each vertex
  28963. [0, 1, 2].forEach(function (idx) {
  28964. var id = originalIndices[t.originalOffset + idx];
  28965. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  28966. if (offset < 0)
  28967. offset = 0;
  28968. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  28969. });
  28970. }
  28971. //overwriting the old vertex buffers and indices.
  28972. this._reconstructedMesh.setIndices(newIndicesArray);
  28973. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28974. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28975. if (newUVsData.length > 0)
  28976. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28977. if (newColorsData.length > 0)
  28978. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28979. //create submesh
  28980. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28981. if (submeshIndex > 0) {
  28982. this._reconstructedMesh.subMeshes = [];
  28983. submeshesArray.forEach(function (submesh) {
  28984. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28985. });
  28986. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28987. }
  28988. };
  28989. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28990. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28991. this._reconstructedMesh.material = this._mesh.material;
  28992. this._reconstructedMesh.parent = this._mesh.parent;
  28993. this._reconstructedMesh.isVisible = false;
  28994. };
  28995. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  28996. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28997. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28998. if (t.deleted)
  28999. continue;
  29000. var s = this.references[vertex1.triangleStart + i].vertexId;
  29001. var v1 = t.vertices[(s + 1) % 3];
  29002. var v2 = t.vertices[(s + 2) % 3];
  29003. if ((v1 === vertex2 || v2 === vertex2)) {
  29004. deletedArray[i] = true;
  29005. delTr.push(t);
  29006. continue;
  29007. }
  29008. var d1 = v1.position.subtract(point);
  29009. d1 = d1.normalize();
  29010. var d2 = v2.position.subtract(point);
  29011. d2 = d2.normalize();
  29012. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29013. return true;
  29014. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29015. deletedArray[i] = false;
  29016. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29017. return true;
  29018. }
  29019. return false;
  29020. };
  29021. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29022. var newDeleted = deletedTriangles;
  29023. for (var i = 0; i < vertex.triangleCount; ++i) {
  29024. var ref = this.references[vertex.triangleStart + i];
  29025. var t = this.triangles[ref.triangleId];
  29026. if (t.deleted)
  29027. continue;
  29028. if (deletedArray[i] && t.deletePending) {
  29029. t.deleted = true;
  29030. newDeleted++;
  29031. continue;
  29032. }
  29033. t.vertices[ref.vertexId] = origVertex;
  29034. t.isDirty = true;
  29035. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29036. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29037. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29038. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29039. this.references.push(ref);
  29040. }
  29041. return newDeleted;
  29042. };
  29043. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29044. for (var i = 0; i < this.vertices.length; ++i) {
  29045. var vCount = [];
  29046. var vId = [];
  29047. var v = this.vertices[i];
  29048. var j;
  29049. for (j = 0; j < v.triangleCount; ++j) {
  29050. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29051. for (var ii = 0; ii < 3; ii++) {
  29052. var ofs = 0;
  29053. var vv = triangle.vertices[ii];
  29054. while (ofs < vCount.length) {
  29055. if (vId[ofs] === vv.id)
  29056. break;
  29057. ++ofs;
  29058. }
  29059. if (ofs === vCount.length) {
  29060. vCount.push(1);
  29061. vId.push(vv.id);
  29062. }
  29063. else {
  29064. vCount[ofs]++;
  29065. }
  29066. }
  29067. }
  29068. for (j = 0; j < vCount.length; ++j) {
  29069. if (vCount[j] === 1) {
  29070. this.vertices[vId[j]].isBorder = true;
  29071. }
  29072. else {
  29073. this.vertices[vId[j]].isBorder = false;
  29074. }
  29075. }
  29076. }
  29077. };
  29078. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29079. if (identifyBorders === void 0) { identifyBorders = false; }
  29080. var i;
  29081. if (!identifyBorders) {
  29082. var newTrianglesVector = [];
  29083. for (i = 0; i < this.triangles.length; ++i) {
  29084. if (!this.triangles[i].deleted) {
  29085. newTrianglesVector.push(this.triangles[i]);
  29086. }
  29087. }
  29088. this.triangles = newTrianglesVector;
  29089. }
  29090. for (i = 0; i < this.vertices.length; ++i) {
  29091. this.vertices[i].triangleCount = 0;
  29092. this.vertices[i].triangleStart = 0;
  29093. }
  29094. var t;
  29095. var j;
  29096. var v;
  29097. for (i = 0; i < this.triangles.length; ++i) {
  29098. t = this.triangles[i];
  29099. for (j = 0; j < 3; ++j) {
  29100. v = t.vertices[j];
  29101. v.triangleCount++;
  29102. }
  29103. }
  29104. var tStart = 0;
  29105. for (i = 0; i < this.vertices.length; ++i) {
  29106. this.vertices[i].triangleStart = tStart;
  29107. tStart += this.vertices[i].triangleCount;
  29108. this.vertices[i].triangleCount = 0;
  29109. }
  29110. var newReferences = new Array(this.triangles.length * 3);
  29111. for (i = 0; i < this.triangles.length; ++i) {
  29112. t = this.triangles[i];
  29113. for (j = 0; j < 3; ++j) {
  29114. v = t.vertices[j];
  29115. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29116. v.triangleCount++;
  29117. }
  29118. }
  29119. this.references = newReferences;
  29120. if (identifyBorders) {
  29121. this.identifyBorder();
  29122. }
  29123. };
  29124. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29125. var x = point.x;
  29126. var y = point.y;
  29127. var z = point.z;
  29128. 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];
  29129. };
  29130. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29131. var q = vertex1.q.add(vertex2.q);
  29132. var border = vertex1.isBorder && vertex2.isBorder;
  29133. var error = 0;
  29134. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29135. if (qDet !== 0 && !border) {
  29136. if (!pointResult) {
  29137. pointResult = BABYLON.Vector3.Zero();
  29138. }
  29139. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29140. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29141. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29142. error = this.vertexError(q, pointResult);
  29143. }
  29144. else {
  29145. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29146. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29147. var error1 = this.vertexError(q, vertex1.position);
  29148. var error2 = this.vertexError(q, vertex2.position);
  29149. var error3 = this.vertexError(q, p3);
  29150. error = Math.min(error1, error2, error3);
  29151. if (error === error1) {
  29152. if (pointResult) {
  29153. pointResult.copyFrom(vertex1.position);
  29154. }
  29155. }
  29156. else if (error === error2) {
  29157. if (pointResult) {
  29158. pointResult.copyFrom(vertex2.position);
  29159. }
  29160. }
  29161. else {
  29162. if (pointResult) {
  29163. pointResult.copyFrom(p3);
  29164. }
  29165. }
  29166. }
  29167. return error;
  29168. };
  29169. return QuadraticErrorSimplification;
  29170. })();
  29171. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29172. })(BABYLON || (BABYLON = {}));
  29173. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  29174. (function (BABYLON) {
  29175. var Analyser = (function () {
  29176. function Analyser(scene) {
  29177. this.SMOOTHING = 0.75;
  29178. this.FFT_SIZE = 512;
  29179. this.BARGRAPHAMPLITUDE = 256;
  29180. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  29181. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  29182. this._scene = scene;
  29183. this._audioEngine = BABYLON.Engine.audioEngine;
  29184. if (this._audioEngine.canUseWebAudio) {
  29185. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  29186. this._webAudioAnalyser.minDecibels = -140;
  29187. this._webAudioAnalyser.maxDecibels = 0;
  29188. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29189. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29190. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  29191. }
  29192. }
  29193. Analyser.prototype.getFrequencyBinCount = function () {
  29194. if (this._audioEngine.canUseWebAudio) {
  29195. return this._webAudioAnalyser.frequencyBinCount;
  29196. }
  29197. else {
  29198. return 0;
  29199. }
  29200. };
  29201. Analyser.prototype.getByteFrequencyData = function () {
  29202. if (this._audioEngine.canUseWebAudio) {
  29203. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29204. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29205. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  29206. }
  29207. return this._byteFreqs;
  29208. };
  29209. Analyser.prototype.getByteTimeDomainData = function () {
  29210. if (this._audioEngine.canUseWebAudio) {
  29211. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29212. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29213. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  29214. }
  29215. return this._byteTime;
  29216. };
  29217. Analyser.prototype.getFloatFrequencyData = function () {
  29218. if (this._audioEngine.canUseWebAudio) {
  29219. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29220. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29221. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  29222. }
  29223. return this._floatFreqs;
  29224. };
  29225. Analyser.prototype.drawDebugCanvas = function () {
  29226. var _this = this;
  29227. if (this._audioEngine.canUseWebAudio) {
  29228. if (!this._debugCanvas) {
  29229. this._debugCanvas = document.createElement("canvas");
  29230. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  29231. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  29232. this._debugCanvas.style.position = "absolute";
  29233. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  29234. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  29235. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  29236. document.body.appendChild(this._debugCanvas);
  29237. this._registerFunc = function () {
  29238. _this.drawDebugCanvas();
  29239. };
  29240. this._scene.registerBeforeRender(this._registerFunc);
  29241. }
  29242. if (this._registerFunc) {
  29243. var workingArray = this.getByteFrequencyData();
  29244. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  29245. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  29246. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  29247. var value = workingArray[i];
  29248. var percent = value / this.BARGRAPHAMPLITUDE;
  29249. var height = this.DEBUGCANVASSIZE.height * percent;
  29250. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  29251. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  29252. var hue = i / this.getFrequencyBinCount() * 360;
  29253. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  29254. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  29255. }
  29256. }
  29257. }
  29258. };
  29259. Analyser.prototype.stopDebugCanvas = function () {
  29260. if (this._debugCanvas) {
  29261. this._scene.unregisterBeforeRender(this._registerFunc);
  29262. this._registerFunc = null;
  29263. document.body.removeChild(this._debugCanvas);
  29264. this._debugCanvas = null;
  29265. this._debugCanvasContext = null;
  29266. }
  29267. };
  29268. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  29269. if (this._audioEngine.canUseWebAudio) {
  29270. inputAudioNode.connect(this._webAudioAnalyser);
  29271. this._webAudioAnalyser.connect(outputAudioNode);
  29272. }
  29273. };
  29274. Analyser.prototype.dispose = function () {
  29275. if (this._audioEngine.canUseWebAudio) {
  29276. this._webAudioAnalyser.disconnect();
  29277. }
  29278. };
  29279. return Analyser;
  29280. })();
  29281. BABYLON.Analyser = Analyser;
  29282. })(BABYLON || (BABYLON = {}));
  29283. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  29284. (function (BABYLON) {
  29285. var DepthRenderer = (function () {
  29286. function DepthRenderer(scene, type) {
  29287. var _this = this;
  29288. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  29289. this._viewMatrix = BABYLON.Matrix.Zero();
  29290. this._projectionMatrix = BABYLON.Matrix.Zero();
  29291. this._transformMatrix = BABYLON.Matrix.Zero();
  29292. this._worldViewProjection = BABYLON.Matrix.Zero();
  29293. this._scene = scene;
  29294. var engine = scene.getEngine();
  29295. // Render target
  29296. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  29297. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29298. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29299. this._depthMap.refreshRate = 1;
  29300. this._depthMap.renderParticles = false;
  29301. this._depthMap.renderList = null;
  29302. // Custom render function
  29303. var renderSubMesh = function (subMesh) {
  29304. var mesh = subMesh.getRenderingMesh();
  29305. var scene = _this._scene;
  29306. var engine = scene.getEngine();
  29307. // Culling
  29308. engine.setState(subMesh.getMaterial().backFaceCulling);
  29309. // Managing instances
  29310. var batch = mesh._getInstancesRenderList(subMesh._id);
  29311. if (batch.mustReturn) {
  29312. return;
  29313. }
  29314. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29315. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29316. engine.enableEffect(_this._effect);
  29317. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  29318. var material = subMesh.getMaterial();
  29319. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29320. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  29321. // Alpha test
  29322. if (material && material.needAlphaTesting()) {
  29323. var alphaTexture = material.getAlphaTestTexture();
  29324. _this._effect.setTexture("diffuseSampler", alphaTexture);
  29325. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29326. }
  29327. // Bones
  29328. if (mesh.useBones) {
  29329. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29330. }
  29331. // Draw
  29332. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29333. }
  29334. };
  29335. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29336. var index;
  29337. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29338. renderSubMesh(opaqueSubMeshes.data[index]);
  29339. }
  29340. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29341. renderSubMesh(alphaTestSubMeshes.data[index]);
  29342. }
  29343. };
  29344. }
  29345. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29346. var defines = [];
  29347. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29348. var mesh = subMesh.getMesh();
  29349. var scene = mesh.getScene();
  29350. var material = subMesh.getMaterial();
  29351. // Alpha test
  29352. if (material && material.needAlphaTesting()) {
  29353. defines.push("#define ALPHATEST");
  29354. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29355. attribs.push(BABYLON.VertexBuffer.UVKind);
  29356. defines.push("#define UV1");
  29357. }
  29358. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29359. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29360. defines.push("#define UV2");
  29361. }
  29362. }
  29363. // Bones
  29364. if (mesh.useBones) {
  29365. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29366. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29367. defines.push("#define BONES");
  29368. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29369. }
  29370. // Instances
  29371. if (useInstances) {
  29372. defines.push("#define INSTANCES");
  29373. attribs.push("world0");
  29374. attribs.push("world1");
  29375. attribs.push("world2");
  29376. attribs.push("world3");
  29377. }
  29378. // Get correct effect
  29379. var join = defines.join("\n");
  29380. if (this._cachedDefines !== join) {
  29381. this._cachedDefines = join;
  29382. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29383. }
  29384. return this._effect.isReady();
  29385. };
  29386. DepthRenderer.prototype.getDepthMap = function () {
  29387. return this._depthMap;
  29388. };
  29389. // Methods
  29390. DepthRenderer.prototype.dispose = function () {
  29391. this._depthMap.dispose();
  29392. };
  29393. return DepthRenderer;
  29394. })();
  29395. BABYLON.DepthRenderer = DepthRenderer;
  29396. })(BABYLON || (BABYLON = {}));
  29397. //# sourceMappingURL=babylon.depthRenderer.js.map
  29398. var BABYLON;
  29399. (function (BABYLON) {
  29400. var SSAORenderingPipeline = (function (_super) {
  29401. __extends(SSAORenderingPipeline, _super);
  29402. /**
  29403. * @constructor
  29404. * @param {string} name - The rendering pipeline name
  29405. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29406. * @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 }
  29407. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29408. */
  29409. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29410. var _this = this;
  29411. _super.call(this, scene.getEngine(), name);
  29412. // Members
  29413. /**
  29414. * The PassPostProcess id in the pipeline that contains the original scene color
  29415. * @type {string}
  29416. */
  29417. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29418. /**
  29419. * The SSAO PostProcess id in the pipeline
  29420. * @type {string}
  29421. */
  29422. this.SSAORenderEffect = "SSAORenderEffect";
  29423. /**
  29424. * The horizontal blur PostProcess id in the pipeline
  29425. * @type {string}
  29426. */
  29427. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29428. /**
  29429. * The vertical blur PostProcess id in the pipeline
  29430. * @type {string}
  29431. */
  29432. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29433. /**
  29434. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29435. * @type {string}
  29436. */
  29437. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29438. /**
  29439. * The output strength of the SSAO post-process. Default value is 1.0.
  29440. * @type {number}
  29441. */
  29442. this.totalStrength = 1.0;
  29443. /**
  29444. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29445. * @type {number}
  29446. */
  29447. this.radius = 0.0002;
  29448. /**
  29449. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29450. * Must not be equal to fallOff and superior to fallOff.
  29451. * Default value is 0.0075
  29452. * @type {number}
  29453. */
  29454. this.area = 0.0075;
  29455. /**
  29456. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29457. * Must not be equal to area and inferior to area.
  29458. * Default value is 0.0002
  29459. * @type {number}
  29460. */
  29461. this.fallOff = 0.0002;
  29462. this._firstUpdate = true;
  29463. this._scene = scene;
  29464. // Set up assets
  29465. this._createRandomTexture();
  29466. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29467. var ssaoRatio = ratio.ssaoRatio || ratio;
  29468. var combineRatio = ratio.combineRatio || ratio;
  29469. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29470. this._createSSAOPostProcess(ssaoRatio);
  29471. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29472. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29473. this._createSSAOCombinePostProcess(combineRatio);
  29474. // Set up pipeline
  29475. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29476. return _this._originalColorPostProcess;
  29477. }, true));
  29478. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29479. return _this._ssaoPostProcess;
  29480. }, true));
  29481. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29482. return _this._blurHPostProcess;
  29483. }, true));
  29484. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29485. return _this._blurVPostProcess;
  29486. }, true));
  29487. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29488. return _this._ssaoCombinePostProcess;
  29489. }, true));
  29490. // Finish
  29491. scene.postProcessRenderPipelineManager.addPipeline(this);
  29492. if (cameras)
  29493. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29494. }
  29495. // Public Methods
  29496. /**
  29497. * Returns the horizontal blur PostProcess
  29498. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29499. */
  29500. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29501. return this._blurHPostProcess;
  29502. };
  29503. /**
  29504. * Returns the vertical blur PostProcess
  29505. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29506. */
  29507. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29508. return this._blurVPostProcess;
  29509. };
  29510. /**
  29511. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29512. */
  29513. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29514. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29515. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29516. this._originalColorPostProcess = undefined;
  29517. this._ssaoPostProcess = undefined;
  29518. this._blurHPostProcess = undefined;
  29519. this._blurVPostProcess = undefined;
  29520. this._ssaoCombinePostProcess = undefined;
  29521. this._randomTexture.dispose();
  29522. if (disableDepthRender)
  29523. this._scene.disableDepthRenderer();
  29524. };
  29525. // Private Methods
  29526. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29527. var _this = this;
  29528. var sampleSphere = [
  29529. 0.5381,
  29530. 0.1856,
  29531. -0.4319,
  29532. 0.1379,
  29533. 0.2486,
  29534. 0.4430,
  29535. 0.3371,
  29536. 0.5679,
  29537. -0.0057,
  29538. -0.6999,
  29539. -0.0451,
  29540. -0.0019,
  29541. 0.0689,
  29542. -0.1598,
  29543. -0.8547,
  29544. 0.0560,
  29545. 0.0069,
  29546. -0.1843,
  29547. -0.0146,
  29548. 0.1402,
  29549. 0.0762,
  29550. 0.0100,
  29551. -0.1924,
  29552. -0.0344,
  29553. -0.3577,
  29554. -0.5301,
  29555. -0.4358,
  29556. -0.3169,
  29557. 0.1063,
  29558. 0.0158,
  29559. 0.0103,
  29560. -0.5869,
  29561. 0.0046,
  29562. -0.0897,
  29563. -0.4940,
  29564. 0.3287,
  29565. 0.7119,
  29566. -0.0154,
  29567. -0.0918,
  29568. -0.0533,
  29569. 0.0596,
  29570. -0.5411,
  29571. 0.0352,
  29572. -0.0631,
  29573. 0.5460,
  29574. -0.4776,
  29575. 0.2847,
  29576. -0.0271
  29577. ];
  29578. var samplesFactor = 1.0 / 16.0;
  29579. 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);
  29580. this._ssaoPostProcess.onApply = function (effect) {
  29581. if (_this._firstUpdate) {
  29582. effect.setArray3("sampleSphere", sampleSphere);
  29583. effect.setFloat("samplesFactor", samplesFactor);
  29584. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29585. _this._firstUpdate = false;
  29586. }
  29587. effect.setFloat("totalStrength", _this.totalStrength);
  29588. effect.setFloat("radius", _this.radius);
  29589. effect.setFloat("area", _this.area);
  29590. effect.setFloat("fallOff", _this.fallOff);
  29591. effect.setTexture("textureSampler", _this._depthTexture);
  29592. effect.setTexture("randomSampler", _this._randomTexture);
  29593. };
  29594. };
  29595. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29596. var _this = this;
  29597. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29598. this._ssaoCombinePostProcess.onApply = function (effect) {
  29599. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29600. };
  29601. };
  29602. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29603. var size = 512;
  29604. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29605. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29606. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29607. var context = this._randomTexture.getContext();
  29608. var rand = function (min, max) {
  29609. return Math.random() * (max - min) + min;
  29610. };
  29611. for (var x = 0; x < size; x++) {
  29612. for (var y = 0; y < size; y++) {
  29613. var randVector = BABYLON.Vector3.Zero();
  29614. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29615. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29616. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29617. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29618. context.fillRect(x, y, 1, 1);
  29619. }
  29620. }
  29621. this._randomTexture.update(false);
  29622. };
  29623. return SSAORenderingPipeline;
  29624. })(BABYLON.PostProcessRenderPipeline);
  29625. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29626. })(BABYLON || (BABYLON = {}));
  29627. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29628. var BABYLON;
  29629. (function (BABYLON) {
  29630. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29631. var VolumetricLightScatteringPostProcess = (function (_super) {
  29632. __extends(VolumetricLightScatteringPostProcess, _super);
  29633. /**
  29634. * @constructor
  29635. * @param {string} name - The post-process name
  29636. * @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)
  29637. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29638. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29639. * @param {number} samples - The post-process quality, default 100
  29640. * @param {number} samplingMode - The post-process filtering mode
  29641. * @param {BABYLON.Engine} engine - The babylon engine
  29642. * @param {boolean} reusable - If the post-process is reusable
  29643. */
  29644. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29645. var _this = this;
  29646. if (samples === void 0) { samples = 100; }
  29647. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29648. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29649. this._screenCoordinates = BABYLON.Vector2.Zero();
  29650. /**
  29651. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29652. * @type {boolean}
  29653. */
  29654. this.useCustomMeshPosition = false;
  29655. /**
  29656. * If the post-process should inverse the light scattering direction
  29657. * @type {boolean}
  29658. */
  29659. this.invert = true;
  29660. /**
  29661. * Array containing the excluded meshes not rendered in the internal pass
  29662. */
  29663. this.excludedMeshes = new Array();
  29664. this.exposure = 0.3;
  29665. this.decay = 0.96815;
  29666. this.weight = 0.58767;
  29667. this.density = 0.926;
  29668. var scene = camera.getScene();
  29669. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29670. // Configure mesh
  29671. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29672. // Configure
  29673. this._createPass(scene, ratio.passRatio || ratio);
  29674. this.onApply = function (effect) {
  29675. _this._updateMeshScreenCoordinates(scene);
  29676. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29677. effect.setFloat("exposure", _this.exposure);
  29678. effect.setFloat("decay", _this.decay);
  29679. effect.setFloat("weight", _this.weight);
  29680. effect.setFloat("density", _this.density);
  29681. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29682. };
  29683. }
  29684. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29685. var mesh = subMesh.getMesh();
  29686. var defines = [];
  29687. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29688. var material = subMesh.getMaterial();
  29689. var needUV = false;
  29690. // Render this.mesh as default
  29691. if (mesh === this.mesh) {
  29692. defines.push("#define BASIC_RENDER");
  29693. defines.push("#define NEED_UV");
  29694. needUV = true;
  29695. }
  29696. // Alpha test
  29697. if (material) {
  29698. if (material.needAlphaTesting() || mesh === this.mesh)
  29699. defines.push("#define ALPHATEST");
  29700. if (material.opacityTexture !== undefined) {
  29701. defines.push("#define OPACITY");
  29702. if (material.opacityTexture.getAlphaFromRGB)
  29703. defines.push("#define OPACITYRGB");
  29704. if (!needUV)
  29705. defines.push("#define NEED_UV");
  29706. }
  29707. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29708. attribs.push(BABYLON.VertexBuffer.UVKind);
  29709. defines.push("#define UV1");
  29710. }
  29711. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29712. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29713. defines.push("#define UV2");
  29714. }
  29715. }
  29716. // Bones
  29717. if (mesh.useBones) {
  29718. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29719. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29720. defines.push("#define BONES");
  29721. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29722. }
  29723. // Instances
  29724. if (useInstances) {
  29725. defines.push("#define INSTANCES");
  29726. attribs.push("world0");
  29727. attribs.push("world1");
  29728. attribs.push("world2");
  29729. attribs.push("world3");
  29730. }
  29731. // Get correct effect
  29732. var join = defines.join("\n");
  29733. if (this._cachedDefines !== join) {
  29734. this._cachedDefines = join;
  29735. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29736. }
  29737. return this._volumetricLightScatteringPass.isReady();
  29738. };
  29739. /**
  29740. * Sets the new light position for light scattering effect
  29741. * @param {BABYLON.Vector3} The new custom light position
  29742. */
  29743. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29744. this._customMeshPosition = position;
  29745. };
  29746. /**
  29747. * Returns the light position for light scattering effect
  29748. * @return {BABYLON.Vector3} The custom light position
  29749. */
  29750. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29751. return this._customMeshPosition;
  29752. };
  29753. /**
  29754. * Disposes the internal assets and detaches the post-process from the camera
  29755. */
  29756. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29757. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29758. if (rttIndex !== -1) {
  29759. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29760. }
  29761. this._volumetricLightScatteringRTT.dispose();
  29762. _super.prototype.dispose.call(this, camera);
  29763. };
  29764. /**
  29765. * Returns the render target texture used by the post-process
  29766. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29767. */
  29768. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29769. return this._volumetricLightScatteringRTT;
  29770. };
  29771. // Private methods
  29772. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29773. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29774. return true;
  29775. }
  29776. return false;
  29777. };
  29778. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29779. var _this = this;
  29780. var engine = scene.getEngine();
  29781. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29782. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29783. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29784. this._volumetricLightScatteringRTT.renderList = null;
  29785. this._volumetricLightScatteringRTT.renderParticles = false;
  29786. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29787. // Custom render function for submeshes
  29788. var renderSubMesh = function (subMesh) {
  29789. var mesh = subMesh.getRenderingMesh();
  29790. if (_this._meshExcluded(mesh)) {
  29791. return;
  29792. }
  29793. var scene = mesh.getScene();
  29794. var engine = scene.getEngine();
  29795. // Culling
  29796. engine.setState(subMesh.getMaterial().backFaceCulling);
  29797. // Managing instances
  29798. var batch = mesh._getInstancesRenderList(subMesh._id);
  29799. if (batch.mustReturn) {
  29800. return;
  29801. }
  29802. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29803. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29804. engine.enableEffect(_this._volumetricLightScatteringPass);
  29805. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29806. var material = subMesh.getMaterial();
  29807. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29808. // Alpha test
  29809. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29810. var alphaTexture = material.getAlphaTestTexture();
  29811. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29812. if (alphaTexture) {
  29813. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29814. }
  29815. if (material.opacityTexture !== undefined) {
  29816. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29817. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  29818. }
  29819. }
  29820. // Bones
  29821. if (mesh.useBones) {
  29822. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29823. }
  29824. // Draw
  29825. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29826. }
  29827. };
  29828. // Render target texture callbacks
  29829. var savedSceneClearColor;
  29830. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  29831. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29832. savedSceneClearColor = scene.clearColor;
  29833. scene.clearColor = sceneClearColor;
  29834. };
  29835. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29836. scene.clearColor = savedSceneClearColor;
  29837. };
  29838. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29839. var engine = scene.getEngine();
  29840. var index;
  29841. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29842. renderSubMesh(opaqueSubMeshes.data[index]);
  29843. }
  29844. engine.setAlphaTesting(true);
  29845. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29846. renderSubMesh(alphaTestSubMeshes.data[index]);
  29847. }
  29848. engine.setAlphaTesting(false);
  29849. if (transparentSubMeshes.length) {
  29850. for (index = 0; index < transparentSubMeshes.length; index++) {
  29851. var submesh = transparentSubMeshes.data[index];
  29852. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  29853. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  29854. }
  29855. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  29856. sortedArray.sort(function (a, b) {
  29857. // Alpha index first
  29858. if (a._alphaIndex > b._alphaIndex) {
  29859. return 1;
  29860. }
  29861. if (a._alphaIndex < b._alphaIndex) {
  29862. return -1;
  29863. }
  29864. // Then distance to camera
  29865. if (a._distanceToCamera < b._distanceToCamera) {
  29866. return 1;
  29867. }
  29868. if (a._distanceToCamera > b._distanceToCamera) {
  29869. return -1;
  29870. }
  29871. return 0;
  29872. });
  29873. // Render sub meshes
  29874. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29875. for (index = 0; index < sortedArray.length; index++) {
  29876. renderSubMesh(sortedArray[index]);
  29877. }
  29878. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29879. }
  29880. };
  29881. };
  29882. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29883. var transform = scene.getTransformMatrix();
  29884. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29885. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29886. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29887. if (this.invert)
  29888. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29889. };
  29890. // Static methods
  29891. /**
  29892. * Creates a default mesh for the Volumeric Light Scattering post-process
  29893. * @param {string} The mesh name
  29894. * @param {BABYLON.Scene} The scene where to create the mesh
  29895. * @return {BABYLON.Mesh} the default mesh
  29896. */
  29897. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29898. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29899. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29900. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29901. return mesh;
  29902. };
  29903. return VolumetricLightScatteringPostProcess;
  29904. })(BABYLON.PostProcess);
  29905. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29906. })(BABYLON || (BABYLON = {}));
  29907. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29908. var BABYLON;
  29909. (function (BABYLON) {
  29910. var LensRenderingPipeline = (function (_super) {
  29911. __extends(LensRenderingPipeline, _super);
  29912. /**
  29913. * @constructor
  29914. *
  29915. * Effect parameters are as follow:
  29916. * {
  29917. * chromatic_aberration: number; // from 0 to x (1 for realism)
  29918. * edge_blur: number; // from 0 to x (1 for realism)
  29919. * distortion: number; // from 0 to x (1 for realism)
  29920. * grain_amount: number; // from 0 to 1
  29921. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29922. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  29923. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29924. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29925. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  29926. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  29927. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29928. * }
  29929. * Note: if an effect parameter is unset, effect is disabled
  29930. *
  29931. * @param {string} name - The rendering pipeline name
  29932. * @param {object} parameters - An object containing all parameters (see above)
  29933. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29934. * @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)
  29935. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29936. */
  29937. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29938. var _this = this;
  29939. if (ratio === void 0) { ratio = 1.0; }
  29940. _super.call(this, scene.getEngine(), name);
  29941. // Lens effects can be of the following:
  29942. // - chromatic aberration (slight shift of RGB colors)
  29943. // - blur on the edge of the lens
  29944. // - lens distortion
  29945. // - depth-of-field blur & highlights enhancing
  29946. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  29947. // - grain effect (noise or custom texture)
  29948. // Two additional texture samplers are needed:
  29949. // - depth map (for depth-of-field)
  29950. // - grain texture
  29951. /**
  29952. * The chromatic aberration PostProcess id in the pipeline
  29953. * @type {string}
  29954. */
  29955. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29956. /**
  29957. * The highlights enhancing PostProcess id in the pipeline
  29958. * @type {string}
  29959. */
  29960. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  29961. /**
  29962. * The depth-of-field PostProcess id in the pipeline
  29963. * @type {string}
  29964. */
  29965. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29966. this._scene = scene;
  29967. // Fetch texture samplers
  29968. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29969. if (parameters.grain_texture) {
  29970. this._grainTexture = parameters.grain_texture;
  29971. }
  29972. else {
  29973. this._createGrainTexture();
  29974. }
  29975. // save parameters
  29976. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29977. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29978. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29979. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29980. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  29981. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29982. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29983. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29984. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29985. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29986. // Create effects
  29987. this._createChromaticAberrationPostProcess(ratio);
  29988. this._createHighlightsPostProcess(ratio);
  29989. this._createDepthOfFieldPostProcess(ratio);
  29990. // Set up pipeline
  29991. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29992. return _this._chromaticAberrationPostProcess;
  29993. }, true));
  29994. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  29995. return _this._highlightsPostProcess;
  29996. }, true));
  29997. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29998. return _this._depthOfFieldPostProcess;
  29999. }, true));
  30000. if (this._highlightsGain == -1) {
  30001. this._disableEffect(this.HighlightsEnhancingEffect, null);
  30002. }
  30003. // Finish
  30004. scene.postProcessRenderPipelineManager.addPipeline(this);
  30005. if (cameras) {
  30006. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30007. }
  30008. }
  30009. // public methods (self explanatory)
  30010. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  30011. this._edgeBlur = amount;
  30012. };
  30013. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  30014. this._edgeBlur = 0;
  30015. };
  30016. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  30017. this._grainAmount = amount;
  30018. };
  30019. LensRenderingPipeline.prototype.disableGrain = function () {
  30020. this._grainAmount = 0;
  30021. };
  30022. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  30023. this._chromaticAberration = amount;
  30024. };
  30025. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  30026. this._chromaticAberration = 0;
  30027. };
  30028. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  30029. this._distortion = amount;
  30030. };
  30031. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  30032. this._distortion = 0;
  30033. };
  30034. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  30035. this._dofDepth = amount;
  30036. };
  30037. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  30038. this._dofDepth = -1;
  30039. };
  30040. LensRenderingPipeline.prototype.setAperture = function (amount) {
  30041. this._dofAperture = amount;
  30042. };
  30043. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  30044. this._dofPentagon = true;
  30045. };
  30046. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  30047. this._dofPentagon = false;
  30048. };
  30049. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  30050. this._blurNoise = true;
  30051. };
  30052. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  30053. this._blurNoise = false;
  30054. };
  30055. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  30056. this._highlightsGain = amount;
  30057. };
  30058. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  30059. if (this._highlightsGain == -1) {
  30060. this._highlightsGain = 1.0;
  30061. }
  30062. this._highlightsThreshold = amount;
  30063. };
  30064. LensRenderingPipeline.prototype.disableHighlights = function () {
  30065. this._highlightsGain = -1;
  30066. };
  30067. /**
  30068. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  30069. */
  30070. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30071. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30072. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30073. this._chromaticAberrationPostProcess = undefined;
  30074. this._highlightsPostProcess = undefined;
  30075. this._depthOfFieldPostProcess = undefined;
  30076. this._grainTexture.dispose();
  30077. if (disableDepthRender)
  30078. this._scene.disableDepthRenderer();
  30079. };
  30080. // colors shifting and distortion
  30081. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  30082. var _this = this;
  30083. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30084. this._chromaticAberrationPostProcess.onApply = function (effect) {
  30085. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  30086. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30087. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30088. };
  30089. };
  30090. // highlights enhancing
  30091. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  30092. var _this = this;
  30093. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30094. this._highlightsPostProcess.onApply = function (effect) {
  30095. effect.setFloat('gain', _this._highlightsGain);
  30096. effect.setFloat('threshold', _this._highlightsThreshold);
  30097. effect.setBool('pentagon', _this._dofPentagon);
  30098. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  30099. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30100. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30101. };
  30102. };
  30103. // colors shifting and distortion
  30104. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  30105. var _this = this;
  30106. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  30107. "focus_depth",
  30108. "aperture",
  30109. "pentagon",
  30110. "maxZ",
  30111. "edge_blur",
  30112. "chromatic_aberration",
  30113. "distortion",
  30114. "blur_noise",
  30115. "grain_amount",
  30116. "screen_width",
  30117. "screen_height",
  30118. "highlights"
  30119. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30120. this._depthOfFieldPostProcess.onApply = function (effect) {
  30121. effect.setBool('blur_noise', _this._blurNoise);
  30122. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  30123. effect.setFloat('grain_amount', _this._grainAmount);
  30124. effect.setTexture("depthSampler", _this._depthTexture);
  30125. effect.setTexture("grainSampler", _this._grainTexture);
  30126. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  30127. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  30128. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30129. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30130. effect.setFloat('distortion', _this._distortion);
  30131. effect.setFloat('focus_depth', _this._dofDepth);
  30132. effect.setFloat('aperture', _this._dofAperture);
  30133. effect.setFloat('edge_blur', _this._edgeBlur);
  30134. effect.setBool('highlights', (_this._highlightsGain != -1));
  30135. };
  30136. };
  30137. // creates a black and white random noise texture, 512x512
  30138. LensRenderingPipeline.prototype._createGrainTexture = function () {
  30139. var size = 512;
  30140. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30141. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30142. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30143. var context = this._grainTexture.getContext();
  30144. var rand = function (min, max) {
  30145. return Math.random() * (max - min) + min;
  30146. };
  30147. var value;
  30148. for (var x = 0; x < size; x++) {
  30149. for (var y = 0; y < size; y++) {
  30150. value = Math.floor(rand(0.42, 0.58) * 255);
  30151. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  30152. context.fillRect(x, y, 1, 1);
  30153. }
  30154. }
  30155. this._grainTexture.update(false);
  30156. };
  30157. return LensRenderingPipeline;
  30158. })(BABYLON.PostProcessRenderPipeline);
  30159. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  30160. })(BABYLON || (BABYLON = {}));
  30161. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  30162. // This post-process allows the modification of rendered colors by using
  30163. // a 'look-up table' (LUT). This effect is also called Color Grading.
  30164. //
  30165. // The object needs to be provided an url to a texture containing the color
  30166. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  30167. // Use an image editing software to tweak the LUT to match your needs.
  30168. //
  30169. // For an example of a color LUT, see here:
  30170. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  30171. // For explanations on color grading, see here:
  30172. // http://udn.epicgames.com/Three/ColorGrading.html
  30173. //
  30174. var BABYLON;
  30175. (function (BABYLON) {
  30176. var ColorCorrectionPostProcess = (function (_super) {
  30177. __extends(ColorCorrectionPostProcess, _super);
  30178. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  30179. var _this = this;
  30180. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  30181. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  30182. this._colorTableTexture.anisotropicFilteringLevel = 1;
  30183. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30184. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30185. this.onApply = function (effect) {
  30186. effect.setTexture("colorTable", _this._colorTableTexture);
  30187. };
  30188. }
  30189. return ColorCorrectionPostProcess;
  30190. })(BABYLON.PostProcess);
  30191. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  30192. })(BABYLON || (BABYLON = {}));
  30193. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  30194. (function (BABYLON) {
  30195. var SmartCollection = (function () {
  30196. function SmartCollection(capacity) {
  30197. if (capacity === void 0) { capacity = 10; }
  30198. this.count = 0;
  30199. this._initialCapacity = capacity;
  30200. this.items = {};
  30201. this._keys = new Array(this._initialCapacity);
  30202. }
  30203. SmartCollection.prototype.add = function (key, item) {
  30204. if (this.items[key] != undefined) {
  30205. return -1;
  30206. }
  30207. this.items[key] = item;
  30208. //literal keys are always strings, but we keep source type of key in _keys array
  30209. this._keys[this.count++] = key;
  30210. if (this.count > this._keys.length) {
  30211. this._keys.length *= 2;
  30212. }
  30213. return this.count;
  30214. };
  30215. SmartCollection.prototype.remove = function (key) {
  30216. if (this.items[key] == undefined) {
  30217. return -1;
  30218. }
  30219. return this.removeItemOfIndex(this.indexOf(key));
  30220. };
  30221. SmartCollection.prototype.removeItemOfIndex = function (index) {
  30222. if (index < this.count && index > -1) {
  30223. delete this.items[this._keys[index]];
  30224. while (index < this.count) {
  30225. this._keys[index] = this._keys[index + 1];
  30226. index++;
  30227. }
  30228. }
  30229. else {
  30230. return -1;
  30231. }
  30232. return --this.count;
  30233. };
  30234. SmartCollection.prototype.indexOf = function (key) {
  30235. for (var i = 0; i !== this.count; i++) {
  30236. if (this._keys[i] === key) {
  30237. return i;
  30238. }
  30239. }
  30240. return -1;
  30241. };
  30242. SmartCollection.prototype.item = function (key) {
  30243. return this.items[key];
  30244. };
  30245. SmartCollection.prototype.getAllKeys = function () {
  30246. if (this.count > 0) {
  30247. var keys = new Array(this.count);
  30248. for (var i = 0; i < this.count; i++) {
  30249. keys[i] = this._keys[i];
  30250. }
  30251. return keys;
  30252. }
  30253. else {
  30254. return undefined;
  30255. }
  30256. };
  30257. SmartCollection.prototype.getKeyByIndex = function (index) {
  30258. if (index < this.count && index > -1) {
  30259. return this._keys[index];
  30260. }
  30261. else {
  30262. return undefined;
  30263. }
  30264. };
  30265. SmartCollection.prototype.getItemByIndex = function (index) {
  30266. if (index < this.count && index > -1) {
  30267. return this.items[this._keys[index]];
  30268. }
  30269. else {
  30270. return undefined;
  30271. }
  30272. };
  30273. SmartCollection.prototype.empty = function () {
  30274. if (this.count > 0) {
  30275. this.count = 0;
  30276. this.items = {};
  30277. this._keys = new Array(this._initialCapacity);
  30278. }
  30279. };
  30280. return SmartCollection;
  30281. })();
  30282. BABYLON.SmartCollection = SmartCollection;
  30283. })(BABYLON || (BABYLON = {}));
  30284. //# sourceMappingURL=babylon.smartCollection.js.map